package alicloud
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"os/user"
"path/filepath"
"reflect"
"runtime"
"strconv"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/denverdino/aliyungo/cs"
"github.com/aliyun/aliyun-datahub-sdk-go/datahub"
sls "github.com/aliyun/aliyun-log-go-sdk"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
"github.com/aliyun/fc-go-sdk"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"gopkg.in/yaml.v2"
"math"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/denverdino/aliyungo/common"
"github.com/google/uuid"
"github.com/mitchellh/go-homedir"
)
type InstanceNetWork string
const (
ClassicNet = InstanceNetWork("classic")
VpcNet = InstanceNetWork("vpc")
)
type PayType string
const (
PrePaid = PayType("PrePaid")
PostPaid = PayType("PostPaid")
Prepaid = PayType("Prepaid")
Postpaid = PayType("Postpaid")
)
const (
NormalMode = "normal"
SafetyMode = "safety"
)
type DdosbgpInsatnceType string
const (
Enterprise = DdosbgpInsatnceType("Enterprise")
Professional = DdosbgpInsatnceType("Professional")
)
type DdosbgpInstanceIpType string
const (
IPv4 = DdosbgpInstanceIpType("IPv4")
IPv6 = DdosbgpInstanceIpType("IPv6")
)
type NetType string
const (
Internet = NetType("Internet")
Intranet = NetType("Intranet")
)
type NetworkType string
const (
Classic = NetworkType("Classic")
Vpc = NetworkType("Vpc")
ClassicInternet = NetworkType("classic_internet")
ClassicIntranet = NetworkType("classic_intranet")
PUBLIC = NetworkType("PUBLIC")
PRIVATE = NetworkType("PRIVATE")
)
type NodeType string
const (
WORKER = NodeType("WORKER")
KIBANA = NodeType("KIBANA")
)
type ActionType string
const (
OPEN = ActionType("OPEN")
CLOSE = ActionType("CLOSE")
)
type TimeType string
const (
Hour = TimeType("Hour")
Day = TimeType("Day")
Week = TimeType("Week")
Month = TimeType("Month")
Year = TimeType("Year")
)
type IpVersion string
const (
IPV4 = IpVersion("ipv4")
IPV6 = IpVersion("ipv6")
)
type Status string
const (
Pending = Status("Pending")
Creating = Status("Creating")
Running = Status("Running")
Available = Status("Available")
Unavailable = Status("Unavailable")
Modifying = Status("Modifying")
Deleting = Status("Deleting")
Starting = Status("Starting")
Stopping = Status("Stopping")
Stopped = Status("Stopped")
Normal = Status("Normal")
Changing = Status("Changing")
Online = Status("online")
Configuring = Status("configuring")
Associating = Status("Associating")
Unassociating = Status("Unassociating")
InUse = Status("InUse")
DiskInUse = Status("In_use")
Active = Status("Active")
Inactive = Status("Inactive")
Idle = Status("Idle")
SoldOut = Status("SoldOut")
InService = Status("InService")
Removing = Status("Removing")
DisabledStatus = Status("Disabled")
Init = Status("Init")
Provisioning = Status("Provisioning")
Updating = Status("Updating")
FinancialLocked = Status("FinancialLocked")
PUBLISHED = Status("Published")
NOPUBLISHED = Status("NonPublished")
Deleted = Status("Deleted")
Null = Status("Null")
Enable = Status("Enable")
BINDED = Status("BINDED")
)
type IPType string
const (
Inner = IPType("Inner")
Private = IPType("Private")
Public = IPType("Public")
)
type ResourceType string
const (
ResourceTypeInstance = ResourceType("Instance")
ResourceTypeDisk = ResourceType("Disk")
ResourceTypeVSwitch = ResourceType("VSwitch")
ResourceTypeRds = ResourceType("Rds")
ResourceTypePolarDB = ResourceType("PolarDB")
IoOptimized = ResourceType("IoOptimized")
ResourceTypeRkv = ResourceType("KVStore")
ResourceTypeFC = ResourceType("FunctionCompute")
ResourceTypeElasticsearch = ResourceType("Elasticsearch")
ResourceTypeSlb = ResourceType("Slb")
ResourceTypeMongoDB = ResourceType("MongoDB")
ResourceTypeGpdb = ResourceType("Gpdb")
ResourceTypeHBase = ResourceType("HBase")
ResourceTypeAdb = ResourceType("ADB")
ResourceTypeCassandra = ResourceType("Cassandra")
)
type InternetChargeType string
const (
PayByBandwidth = InternetChargeType("PayByBandwidth")
PayByTraffic = InternetChargeType("PayByTraffic")
PayBy95 = InternetChargeType("PayBy95")
)
type AccountSite string
const (
DomesticSite = AccountSite("Domestic")
IntlSite = AccountSite("International")
)
const (
SnapshotCreatingInProcessing = Status("progressing")
SnapshotCreatingAccomplished = Status("accomplished")
SnapshotCreatingFailed = Status("failed")
SnapshotPolicyCreating = Status("Creating")
SnapshotPolicyAvailable = Status("available")
SnapshotPolicyNormal = Status("Normal")
)
// timeout for common product, ecs e.g.
const DefaultTimeout = 120
const Timeout5Minute = 300
const DefaultTimeoutMedium = 500
// timeout for long time progerss product, rds e.g.
const DefaultLongTimeout = 1000
const DefaultIntervalMini = 2
const DefaultIntervalShort = 5
const DefaultIntervalMedium = 10
const DefaultIntervalLong = 20
const (
PageSizeSmall = 10
PageSizeMedium = 20
PageSizeLarge = 50
PageSizeXLarge = 100
)
// Protocol represents network protocol
type Protocol string
// Constants of protocol definition
const (
Http = Protocol("http")
Https = Protocol("https")
Tcp = Protocol("tcp")
Udp = Protocol("udp")
All = Protocol("all")
Icmp = Protocol("icmp")
Gre = Protocol("gre")
)
// ValidProtocols network protocol list
var ValidProtocols = []Protocol{Http, Https, Tcp, Udp}
// simple array value check method, support string type only
func isProtocolValid(value string) bool {
res := false
for _, v := range ValidProtocols {
if string(v) == value {
res = true
}
}
return res
}
// default region for all resource
const DEFAULT_REGION = "cn-beijing"
const INT_MAX = 2147483647
// symbol of multiIZ
const MULTI_IZ_SYMBOL = "MAZ"
const COMMA_SEPARATED = ","
const COLON_SEPARATED = ":"
const SLASH_SEPARATED = "/"
const LOCAL_HOST_IP = "127.0.0.1"
// Takes the result of flatmap.Expand for an array of strings
// and returns a []string
func expandStringList(configured []interface{}) []string {
vs := make([]string, 0, len(configured))
for _, v := range configured {
if v == nil {
continue
}
vs = append(vs, v.(string))
}
return vs
}
// Takes list of string to strings. Expand to an array
// of raw strings and returns a []interface{}
func convertListStringToListInterface(list []string) []interface{} {
vs := make([]interface{}, 0, len(list))
for _, v := range list {
vs = append(vs, v)
}
return vs
}
func expandIntList(configured []interface{}) []int {
vs := make([]int, 0, len(configured))
for _, v := range configured {
vs = append(vs, v.(int))
}
return vs
}
// Convert the result for an array and returns a Json string
func convertListToJsonString(configured []interface{}) string {
if len(configured) < 1 {
return ""
}
result := "["
for i, v := range configured {
if v == nil {
continue
}
result += "\"" + v.(string) + "\""
if i < len(configured)-1 {
result += ","
}
}
result += "]"
return result
}
func convertJsonStringToStringList(src interface{}) (result []interface{}) {
if err, ok := src.([]interface{}); !ok {
panic(err)
}
for _, v := range src.([]interface{}) {
result = append(result, fmt.Sprint(formatInt(v)))
}
return
}
func convertJsonStringToMap(configured string) (map[string]interface{}, error) {
result := make(map[string]interface{})
if err := json.Unmarshal([]byte(configured), &result); err != nil {
return nil, err
}
return result, nil
}
// Convert the result for an array and returns a comma separate
func convertListToCommaSeparate(configured []interface{}) string {
if len(configured) < 1 {
return ""
}
result := ""
for i, v := range configured {
rail := ","
if i == len(configured)-1 {
rail = ""
}
result += v.(string) + rail
}
return result
}
func convertBoolToString(configured bool) string {
return strconv.FormatBool(configured)
}
func convertIntergerToString(configured int) string {
return strconv.Itoa(configured)
}
func convertFloat64ToString(configured float64) string {
return strconv.FormatFloat(configured, 'E', -1, 64)
}
func convertJsonStringToList(configured string) ([]interface{}, error) {
result := make([]interface{}, 0)
if err := json.Unmarshal([]byte(configured), &result); err != nil {
return nil, err
}
return result, nil
}
func convertMaptoJsonString(m map[string]interface{}) (string, error) {
//sm := make(map[string]string, len(m))
//for k, v := range m {
// sm[k] = v.(string)
//}
if result, err := json.Marshal(m); err != nil {
return "", err
} else {
return string(result), nil
}
}
func convertListMapToJsonString(configured []map[string]interface{}) (string, error) {
if len(configured) < 1 {
return "[]", nil
}
result := "["
for i, m := range configured {
if m == nil {
continue
}
sm := make(map[string]interface{}, len(m))
for k, v := range m {
sm[k] = v
}
item, err := json.Marshal(sm)
if err == nil {
result += string(item)
if i < len(configured)-1 {
result += ","
}
}
}
result += "]"
return result, nil
}
func convertMapFloat64ToJsonString(m map[string]interface{}) (string, error) {
sm := make(map[string]json.Number, len(m))
for k, v := range m {
sm[k] = v.(json.Number)
}
if result, err := json.Marshal(sm); err != nil {
return "", err
} else {
return string(result), nil
}
}
func StringPointer(s string) *string {
return &s
}
func BoolPointer(b bool) *bool {
return &b
}
func Int32Pointer(i int32) *int32 {
return &i
}
func Int64Pointer(i int64) *int64 {
return &i
}
func IntMin(x, y int) int {
if x < y {
return x
}
return y
}
const ServerSideEncryptionAes256 = "AES256"
const ServerSideEncryptionKMS = "KMS"
type OptimizedType string
const (
IOOptimized = OptimizedType("optimized")
NoneOptimized = OptimizedType("none")
)
type TagResourceType string
const (
TagResourceImage = TagResourceType("image")
TagResourceInstance = TagResourceType("instance")
TagResourceAcl = TagResourceType("acl")
TagResourceCertificate = TagResourceType("certificate")
TagResourceSnapshot = TagResourceType("snapshot")
TagResourceKeypair = TagResourceType("keypair")
TagResourceDisk = TagResourceType("disk")
TagResourceSecurityGroup = TagResourceType("securitygroup")
TagResourceEni = TagResourceType("eni")
TagResourceCdn = TagResourceType("DOMAIN")
TagResourceVpc = TagResourceType("VPC")
TagResourceVSwitch = TagResourceType("VSWITCH")
TagResourceRouteTable = TagResourceType("ROUTETABLE")
TagResourceEip = TagResourceType("EIP")
TagResourcePlugin = TagResourceType("plugin")
TagResourceApiGroup = TagResourceType("apiGroup")
TagResourceApp = TagResourceType("app")
TagResourceTopic = TagResourceType("topic")
TagResourceConsumerGroup = TagResourceType("consumergroup")
TagResourceCluster = TagResourceType("cluster")
)
type KubernetesNodeType string
const (
KubernetesNodeMaster = ResourceType("Master")
KubernetesNodeWorker = ResourceType("Worker")
)
func getPagination(pageNumber, pageSize int) (pagination common.Pagination) {
pagination.PageSize = pageSize
pagination.PageNumber = pageNumber
return
}
const CharityPageUrl = "http://promotion.alicdn.com/help/oss/error.html"
func userDataHashSum(user_data string) string {
// Check whether the user_data is not Base64 encoded.
// Always calculate hash of base64 decoded value since we
// check against double-encoding when setting it
v, base64DecodeError := base64.StdEncoding.DecodeString(user_data)
if base64DecodeError != nil {
v = []byte(user_data)
}
return string(v)
}
// Remove useless blank in the string.
func Trim(v string) string {
if len(v) < 1 {
return v
}
return strings.Trim(v, " ")
}
func ConvertIntegerToInt(value requests.Integer) (v int, err error) {
if strings.TrimSpace(string(value)) == "" {
return
}
v, err = strconv.Atoi(string(value))
if err != nil {
return v, fmt.Errorf("Converting integer %s to int got an error: %#v.", value, err)
}
return
}
func GetUserHomeDir() (string, error) {
usr, err := user.Current()
if err != nil {
return "", fmt.Errorf("Get current user got an error: %#v.", err)
}
return usr.HomeDir, nil
}
func writeToFile(filePath string, data interface{}) error {
var out string
switch data.(type) {
case string:
out = data.(string)
break
case nil:
return nil
default:
bs, err := json.MarshalIndent(data, "", "\t")
if err != nil {
return fmt.Errorf("MarshalIndent data %#v got an error: %#v", data, err)
}
out = string(bs)
}
if strings.HasPrefix(filePath, "~") {
home, err := GetUserHomeDir()
if err != nil {
return err
}
if home != "" {
filePath = strings.Replace(filePath, "~", home, 1)
}
}
if _, err := os.Stat(filePath); err == nil {
if err := os.Remove(filePath); err != nil {
return err
}
}
return ioutil.WriteFile(filePath, []byte(out), 422)
}
type Invoker struct {
catchers []*Catcher
}
type Catcher struct {
Reason string
RetryCount int
RetryWaitSeconds int
}
var ClientErrorCatcher = Catcher{AliyunGoClientFailure, 10, 5}
var ServiceBusyCatcher = Catcher{"ServiceUnavailable", 10, 5}
var ThrottlingCatcher = Catcher{Throttling, 50, 2}
func NewInvoker() Invoker {
i := Invoker{}
i.AddCatcher(ClientErrorCatcher)
i.AddCatcher(ServiceBusyCatcher)
i.AddCatcher(ThrottlingCatcher)
return i
}
func (a *Invoker) AddCatcher(catcher Catcher) {
a.catchers = append(a.catchers, &catcher)
}
func (a *Invoker) Run(f func() error) error {
err := f()
if err == nil {
return nil
}
for _, catcher := range a.catchers {
if IsExpectedErrors(err, []string{catcher.Reason}) {
catcher.RetryCount--
if catcher.RetryCount <= 0 {
return fmt.Errorf("Retry timeout and got an error: %#v.", err)
} else {
time.Sleep(time.Duration(catcher.RetryWaitSeconds) * time.Second)
return a.Run(f)
}
}
}
return err
}
func buildClientToken(action string) string {
token := strings.TrimSpace(fmt.Sprintf("TF-%s-%d-%s", action, time.Now().Unix(), strings.Trim(uuid.New().String(), "-")))
if len(token) > 64 {
token = token[0:64]
}
return token
}
func getNextpageNumber(number requests.Integer) (requests.Integer, error) {
page, err := strconv.Atoi(string(number))
if err != nil {
return "", err
}
return requests.NewInteger(page + 1), nil
}
func terraformToAPI(field string) string {
var result string
for _, v := range strings.Split(field, "_") {
if len(v) > 0 {
result = fmt.Sprintf("%s%s%s", result, strings.ToUpper(string(v[0])), v[1:])
}
}
return result
}
func compareJsonTemplateAreEquivalent(tem1, tem2 string) (bool, error) {
obj1 := make(map[string]interface{})
err := json.Unmarshal([]byte(tem1), &obj1)
if err != nil {
return false, err
}
canonicalJson1, _ := json.Marshal(obj1)
obj2 := make(map[string]interface{})
err = json.Unmarshal([]byte(tem2), &obj2)
if err != nil {
return false, err
}
canonicalJson2, _ := json.Marshal(obj2)
equal := bytes.Compare(canonicalJson1, canonicalJson2) == 0
if !equal {
log.Printf("[DEBUG] Canonical template are not equal.\nFirst: %s\nSecond: %s\n",
canonicalJson1, canonicalJson2)
}
return equal, nil
}
func compareYamlTemplateAreEquivalent(tem1, tem2 string) (bool, error) {
var obj1 interface{}
err := yaml.Unmarshal([]byte(tem1), &obj1)
if err != nil {
return false, err
}
canonicalYaml1, _ := yaml.Marshal(obj1)
var obj2 interface{}
err = yaml.Unmarshal([]byte(tem2), &obj2)
if err != nil {
return false, err
}
canonicalYaml2, _ := yaml.Marshal(obj2)
equal := bytes.Compare(canonicalYaml1, canonicalYaml2) == 0
if !equal {
log.Printf("[DEBUG] Canonical template are not equal.\nFirst: %s\nSecond: %s\n",
canonicalYaml1, canonicalYaml2)
}
return equal, nil
}
// loadFileContent returns contents of a file in a given path
func loadFileContent(v string) ([]byte, error) {
filename, err := homedir.Expand(v)
if err != nil {
return nil, err
}
fileContent, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
return fileContent, nil
}
func debugOn() bool {
for _, part := range strings.Split(os.Getenv("DEBUG"), ",") {
if strings.TrimSpace(part) == "terraform" {
return true
}
}
return false
}
func addDebug(action, content interface{}, requestInfo ...interface{}) {
if debugOn() {
trace := "[DEBUG TRACE]:\n"
for skip := 1; skip < 5; skip++ {
_, filepath, line, _ := runtime.Caller(skip)
trace += fmt.Sprintf("%s:%d\n", filepath, line)
}
if len(requestInfo) > 0 {
var request = struct {
Domain string
Version string
UserAgent string
ActionName string
Method string
Product string
Region string
AK string
}{}
switch requestInfo[0].(type) {
case *requests.RpcRequest:
tmp := requestInfo[0].(*requests.RpcRequest)
request.Domain = tmp.GetDomain()
request.Version = tmp.GetVersion()
request.ActionName = tmp.GetActionName()
request.Method = tmp.GetMethod()
request.Product = tmp.GetProduct()
request.Region = tmp.GetRegionId()
case *requests.RoaRequest:
tmp := requestInfo[0].(*requests.RoaRequest)
request.Domain = tmp.GetDomain()
request.Version = tmp.GetVersion()
request.ActionName = tmp.GetActionName()
request.Method = tmp.GetMethod()
request.Product = tmp.GetProduct()
request.Region = tmp.GetRegionId()
case *requests.CommonRequest:
tmp := requestInfo[0].(*requests.CommonRequest)
request.Domain = tmp.GetDomain()
request.Version = tmp.GetVersion()
request.ActionName = tmp.GetActionName()
request.Method = tmp.GetMethod()
request.Product = tmp.GetProduct()
request.Region = tmp.GetRegionId()
case *fc.Client:
client := requestInfo[0].(*fc.Client)
request.Version = client.Config.APIVersion
request.Product = "FC"
request.ActionName = fmt.Sprintf("%s", action)
case *sls.Client:
request.Product = "LOG"
request.ActionName = fmt.Sprintf("%s", action)
case *tablestore.TableStoreClient:
request.Product = "OTS"
request.ActionName = fmt.Sprintf("%s", action)
case *oss.Client:
request.Product = "OSS"
request.ActionName = fmt.Sprintf("%s", action)
case *datahub.DataHub:
request.Product = "DataHub"
request.ActionName = fmt.Sprintf("%s", action)
case *cs.Client:
request.Product = "CS"
request.ActionName = fmt.Sprintf("%s", action)
}
requestContent := ""
if len(requestInfo) > 1 {
requestContent = fmt.Sprintf("%#v", requestInfo[1])
}
if len(requestInfo) == 1 {
if v, ok := requestInfo[0].(map[string]interface{}); ok {
if res, err := json.Marshal(&v); err == nil {
requestContent = string(res)
}
if res, err := json.Marshal(&content); err == nil {
content = string(res)
}
}
}
content = fmt.Sprintf("%vDomain:%v, Version:%v, ActionName:%v, Method:%v, Product:%v, Region:%v\n\n"+
"*************** %s Request ***************\n%#v\n",
content, request.Domain, request.Version, request.ActionName,
request.Method, request.Product, request.Region, request.ActionName, requestContent)
}
//fmt.Printf(DefaultDebugMsg, action, content, trace)
log.Printf(DefaultDebugMsg, action, content, trace)
}
}
// Return a ComplexError which including extra error message, error occurred file and path
func GetFunc(level int) string {
pc, _, _, ok := runtime.Caller(level)
if !ok {
log.Printf("[ERROR] runtime.Caller error in GetFuncName.")
return ""
}
return strings.TrimPrefix(filepath.Ext(runtime.FuncForPC(pc).Name()), ".")
}
func ParseResourceId(id string, length int) (parts []string, err error) {
parts = strings.Split(id, ":")
if len(parts) != length {
err = WrapError(fmt.Errorf("Invalid Resource Id %s. Expected parts' length %d, got %d", id, length, len(parts)))
}
return parts, err
}
func ParseSlbListenerId(id string) (parts []string, err error) {
parts = strings.Split(id, ":")
if len(parts) != 2 && len(parts) != 3 {
err = WrapError(fmt.Errorf("Invalid alicloud_slb_listener Id %s. Expected Id format is <slb id>:<protocol>:< frontend>.", id))
}
return parts, err
}
func GetCenChildInstanceType(id string) (c string, e error) {
if strings.HasPrefix(id, "vpc") {
return ChildInstanceTypeVpc, nil
} else if strings.HasPrefix(id, "vbr") {
return ChildInstanceTypeVbr, nil
} else if strings.HasPrefix(id, "ccn") {
return ChildInstanceTypeCcn, nil
} else {
return c, fmt.Errorf("CEN child instance ID invalid. Now, it only supports VPC or VBR or CCN instance.")
}
}
func BuildStateConf(pending, target []string, timeout, delay time.Duration, f resource.StateRefreshFunc) *resource.StateChangeConf {
return &resource.StateChangeConf{
Pending: pending,
Target: target,
Refresh: f,
Timeout: timeout,
Delay: delay,
MinTimeout: 3 * time.Second,
}
}
func incrementalWait(firstDuration time.Duration, increaseDuration time.Duration) func() {
retryCount := 1
return func() {
var waitTime time.Duration
if retryCount == 1 {
waitTime = firstDuration
} else if retryCount > 1 {
waitTime += increaseDuration
}
time.Sleep(waitTime)
retryCount++
}
}
// If auto renew, the period computed from computePeriodByUnit will be changed
// This method used to compute a period accourding to current period and unit
func computePeriodByUnit(createTime, endTime interface{}, currentPeriod int, periodUnit string) (int, error) {
var createTimeStr, endTimeStr string
switch value := createTime.(type) {
case int64:
createTimeStr = time.Unix(createTime.(int64), 0).Format(time.RFC3339)
endTimeStr = time.Unix(endTime.(int64), 0).Format(time.RFC3339)
case string:
createTimeStr = createTime.(string)
endTimeStr = endTime.(string)
default:
return 0, WrapError(fmt.Errorf("Unsupported time type: %#v", value))
}
// currently, there is time value does not format as standard RFC3339
UnStandardRFC3339 := "2006-01-02T15:04Z07:00"
create, err := time.Parse(time.RFC3339, createTimeStr)
if err != nil {
log.Printf("Parase the CreateTime %#v failed and error is: %#v.", createTime, err)
create, err = time.Parse(UnStandardRFC3339, createTimeStr)
if err != nil {
return 0, WrapError(err)
}
}
end, err := time.Parse(time.RFC3339, endTimeStr)
if err != nil {
log.Printf("Parase the EndTime %#v failed and error is: %#v.", endTime, err)
end, err = time.Parse(UnStandardRFC3339, endTimeStr)
if err != nil {
return 0, WrapError(err)
}
}
var period int
switch periodUnit {
case "Month":
period = int(math.Floor(end.Sub(create).Hours() / 24 / 30))
case "Week":
period = int(math.Floor(end.Sub(create).Hours() / 24 / 7))
case "Year":
period = int(math.Floor(end.Sub(create).Hours() / 24 / 365))
default:
err = fmt.Errorf("Unexpected period unit %s", periodUnit)
}
// The period at least is 1
if period < 1 {
period = 1
}
if period > 12 {
period = 12
}
// period can not be modified and if the new period is changed, using the previous one.
if currentPeriod > 0 && currentPeriod != period {
period = currentPeriod
}
return period, WrapError(err)
}
func checkWaitForReady(object interface{}, conditions map[string]interface{}) (bool, map[string]interface{}, error) {
if conditions == nil {
return false, nil, nil
}
objectType := reflect.TypeOf(object)
objectValue := reflect.ValueOf(object)
values := make(map[string]interface{})
for key, value := range conditions {
if _, ok := objectType.FieldByName(key); ok {
current := objectValue.FieldByName(key)
values[key] = current
if fmt.Sprintf("%v", current) != fmt.Sprintf("%v", value) {
return false, values, nil
}
} else {
return false, values, WrapError(fmt.Errorf("There is missing attribute %s in the object.", key))
}
}
return true, values, nil
}
// When using teadsl, we need to convert float, int64 and int32 to int for comparison.
func formatInt(src interface{}) int {
if src == nil {
return 0
}
attrType := reflect.TypeOf(src)
switch attrType.String() {
case "float64":
return int(src.(float64))
case "float32":
return int(src.(float32))
case "int64":
return int(src.(int64))
case "int32":
return int(src.(int32))
case "int":
return src.(int)
case "string":
v, err := strconv.Atoi(src.(string))
if err != nil {
panic(err)
}
return v
case "json.Number":
v, err := strconv.Atoi(src.(json.Number).String())
if err != nil {
panic(err)
}
return v
default:
panic(fmt.Sprintf("Not support type %s", attrType.String()))
}
}
func convertArrayObjectToJsonString(src interface{}) (string, error) {
res, err := json.Marshal(&src)
if err != nil {
return "", err
}
return string(res), nil
}
func convertArrayToString(src interface{}, sep string) string {
if src == nil {
return ""
}
items := make([]string, 0)
for _, v := range src.([]interface{}) {
items = append(items, fmt.Sprint(v))
}
return strings.Join(items, sep)
}
func splitMultiZoneId(id string) (ids []string) {
if !(strings.Contains(id, MULTI_IZ_SYMBOL) || strings.Contains(id, "(")) {
return
}
firstIndex := strings.Index(id, MULTI_IZ_SYMBOL)
secondIndex := strings.Index(id, "(")
for _, p := range strings.Split(id[secondIndex+1:len(id)-1], COMMA_SEPARATED) {
ids = append(ids, id[:firstIndex]+string(p))
}
return
}
func Case2Camel(name string) string {
name = strings.Replace(name, "_", " ", -1)
name = strings.Title(name)
return strings.Replace(name, " ", "", -1)
}
func FirstLower(s string) string {
if s == "" {
return ""
}
return strings.ToLower(s[:1]) + s[1:]
}
// SplitSlice Divides the slice into blocks of the specified size
func SplitSlice(xs []interface{}, chunkSize int) [][]interface{} {
if len(xs) == 0 {
return nil
}
divided := make([][]interface{}, (len(xs)+chunkSize-1)/chunkSize)
prev := 0
i := 0
till := len(xs) - chunkSize
for prev < till {
next := prev + chunkSize
divided[i] = xs[prev:next]
prev = next
i++
}
divided[i] = xs[prev:]
return divided
}
func isPagingRequest(d *schema.ResourceData) bool {
v, ok := d.GetOk("page_number")
return ok && v.(int) > 0
}
func setPagingRequest(d *schema.ResourceData, request map[string]interface{}, maxPageSize int) {
if v, ok := d.GetOk("page_number"); ok && v.(int) > 0 {
request["PageNumber"] = v.(int)
} else {
request["PageNumber"] = 1
}
if v, ok := d.GetOk("page_size"); ok && v.(int) > 0 {
request["PageSize"] = v.(int)
} else {
request["PageSize"] = PageSizeLarge
}
return
}
package alicloud
import (
"log"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudAccount() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAccountRead,
Schema: map[string]*schema.Schema{
// Computed values
"id": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudAccountRead(d *schema.ResourceData, meta interface{}) error {
accountId, err := meta.(*connectivity.AliyunClient).AccountId()
if err != nil {
return err
}
log.Printf("[DEBUG] alicloud_account - account ID found: %#v", accountId)
d.SetId(accountId)
return nil
}
package alicloud
import (
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudAckService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAckServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"type": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"propayasgo", "edgepayasgo", "gspayasgo"}, false),
Required: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudAckServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("AckServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
action := "OpenAckService"
query := map[string]*string{
"type": StringPointer(d.Get("type").(string)),
}
conn, err := meta.(*connectivity.AliyunClient).NewTeaRoaCommonClient(connectivity.OpenAckService)
if err != nil {
return WrapError(err)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequestWithAction(StringPointer(action), StringPointer("2015-12-15"), nil, StringPointer("POST"), StringPointer("AK"), String("/service/open"), query, nil, nil, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"QPS Limit Exceeded"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
addDebug(action, response, nil)
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ORDER.OPEND"}) {
d.SetId("AckServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ack_service", action, AlibabaCloudSdkGoERROR)
}
d.SetId("AckServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudActiontrailHistoryDeliveryJobs() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudActiontrailHistoryDeliveryJobsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IntInSlice([]int{0, 1, 2, 3}),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"jobs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"end_time": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"history_delivery_job_id": {
Type: schema.TypeString,
Computed: true,
},
"home_region": {
Type: schema.TypeString,
Computed: true,
},
"start_time": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeInt,
Computed: true,
},
"trail_name": {
Type: schema.TypeString,
Computed: true,
},
"updated_time": {
Type: schema.TypeString,
Computed: true,
},
"job_status": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"region": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudActiontrailHistoryDeliveryJobsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListDeliveryHistoryJobs"
request := make(map[string]interface{})
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOkExists("status")
var response map[string]interface{}
conn, err := client.NewActiontrailClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-07-06"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_actiontrail_history_delivery_jobs", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.DeliveryHistoryJobs", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.DeliveryHistoryJobs", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["JobId"])]; !ok {
continue
}
}
if statusOk && status.(int) != formatInt(item["JobStatus"]) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": object["CreatedTime"],
"end_time": object["EndTime"],
"id": fmt.Sprint(object["JobId"]),
"history_delivery_job_id": fmt.Sprint(object["JobId"]),
"home_region": object["HomeRegion"],
"start_time": object["StartTime"],
"status": formatInt(object["JobStatus"]),
"trail_name": object["TrailName"],
"updated_time": object["UpdatedTime"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["JobId"])
actiontrailService := ActiontrailService{client}
getResp, err := actiontrailService.DescribeActiontrailHistoryDeliveryJob(id)
if err != nil {
return WrapError(err)
}
jobStatus := make([]map[string]interface{}, 0)
if jobStatusList, ok := getResp["Status"]; ok {
jobStatusListArg, _ := jobStatusList.([]interface{})
for _, v := range jobStatusListArg {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"region": m1["Region"],
"status": formatInt(m1["Status"]),
}
jobStatus = append(jobStatus, temp1)
}
}
}
mapping["job_status"] = jobStatus
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("jobs", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudActiontrailTrails() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudActiontrailTrailsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"include_organization_trail": {
Type: schema.TypeBool,
Optional: true,
Default: false,
ForceNew: true,
},
"include_shadow_trails": {
Type: schema.TypeBool,
Optional: true,
Default: false,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Disable", "Enable", "Fresh"}, false),
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"trails": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"event_rw": {
Type: schema.TypeString,
Computed: true,
},
"is_organization_trail": {
Type: schema.TypeBool,
Computed: true,
},
"oss_bucket_name": {
Type: schema.TypeString,
Computed: true,
},
"oss_key_prefix": {
Type: schema.TypeString,
Computed: true,
},
"oss_write_role_arn": {
Type: schema.TypeString,
Computed: true,
},
"sls_project_arn": {
Type: schema.TypeString,
Computed: true,
},
"sls_write_role_arn": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"trail_name": {
Type: schema.TypeString,
Computed: true,
},
"trail_region": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"actiontrails": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"event_rw": {
Type: schema.TypeString,
Computed: true,
},
"is_organization_trail": {
Type: schema.TypeBool,
Computed: true,
},
"oss_bucket_name": {
Type: schema.TypeString,
Computed: true,
},
"oss_key_prefix": {
Type: schema.TypeString,
Computed: true,
},
"oss_write_role_arn": {
Type: schema.TypeString,
Computed: true,
},
"sls_project_arn": {
Type: schema.TypeString,
Computed: true,
},
"sls_write_role_arn": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"trail_name": {
Type: schema.TypeString,
Computed: true,
},
"trail_region": {
Type: schema.TypeString,
Computed: true,
},
},
},
Deprecated: "Field 'actiontrails' has been deprecated from version 1.95.0. Use 'trails' instead.",
},
},
}
}
func dataSourceAlicloudActiontrailTrailsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeTrails"
request := make(map[string]interface{})
if v, ok := d.GetOkExists("include_organization_trail"); ok {
request["IncludeOrganizationTrail"] = v
}
if v, ok := d.GetOkExists("include_shadow_trails"); ok {
request["IncludeShadowTrails"] = v
}
var objects []map[string]interface{}
var trailNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
trailNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewActiontrailClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-07-06"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_actiontrail_trails", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.TrailList", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.TrailList", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if trailNameRegex != nil {
if !trailNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Name"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"event_rw": object["EventRW"],
"is_organization_trail": object["IsOrganizationTrail"],
"oss_bucket_name": object["OssBucketName"],
"oss_key_prefix": object["OssKeyPrefix"],
"oss_write_role_arn": object["OssWriteRoleArn"],
"sls_project_arn": object["SlsProjectArn"],
"sls_write_role_arn": object["SlsWriteRoleArn"],
"status": object["Status"],
"id": fmt.Sprint(object["Name"]),
"trail_name": fmt.Sprint(object["Name"]),
"trail_region": object["TrailRegion"],
}
ids = append(ids, fmt.Sprint(object["Name"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("actiontrails", s); err != nil {
return WrapError(err)
}
if err := d.Set("trails", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"strings"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudAdbDbClusters() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAdbDbClustersRead,
Schema: map[string]*schema.Schema{
"description_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"descriptions": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ClassChanging", "Creating", "Deleting", "NetAddressCreating", "NetAddressDeleting", "Preparing", "Restoring", "Running"}, false),
},
"tags": tagsSchema(),
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"page_number": {
Type: schema.TypeInt,
Optional: true,
},
"page_size": {
Type: schema.TypeInt,
Optional: true,
Default: 100,
},
"clusters": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"auto_renew_period": {
Type: schema.TypeInt,
Computed: true,
},
"commodity_code": {
Type: schema.TypeString,
Computed: true,
},
"compute_resource": {
Type: schema.TypeString,
Computed: true,
},
"connection_string": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"db_cluster_category": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"db_cluster_id": {
Type: schema.TypeString,
Computed: true,
},
"db_cluster_network_type": {
Type: schema.TypeString,
Computed: true,
},
"network_type": {
Type: schema.TypeString,
Computed: true,
},
"db_cluster_type": {
Type: schema.TypeString,
Computed: true,
},
"db_cluster_version": {
Type: schema.TypeString,
Computed: true,
},
"db_node_class": {
Type: schema.TypeString,
Computed: true,
},
"db_node_count": {
Type: schema.TypeInt,
Computed: true,
},
"db_node_storage": {
Type: schema.TypeInt,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"disk_type": {
Type: schema.TypeString,
Computed: true,
},
"dts_job_id": {
Type: schema.TypeString,
Computed: true,
},
"elastic_io_resource": {
Type: schema.TypeInt,
Computed: true,
},
"engine": {
Type: schema.TypeString,
Computed: true,
},
"engine_version": {
Type: schema.TypeString,
Computed: true,
},
"executor_count": {
Type: schema.TypeString,
Computed: true,
},
"expire_time": {
Type: schema.TypeString,
Computed: true,
},
"expired": {
Type: schema.TypeString,
Computed: true,
},
"lock_mode": {
Type: schema.TypeString,
Computed: true,
},
"lock_reason": {
Type: schema.TypeString,
Computed: true,
},
"maintain_time": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"charge_type": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeInt,
Computed: true,
},
"rds_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"renewal_status": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"security_ips": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"storage_resource": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"vpc_cloud_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
"mode": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"total_count": {
Type: schema.TypeInt,
Computed: true,
},
},
}
}
func dataSourceAlicloudAdbDbClustersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDBClusters"
request := make(map[string]interface{})
if v, ok := d.GetOk("description"); ok {
request["DBClusterDescription"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("status"); ok {
request["DBClusterStatus"] = v
}
if v, ok := d.GetOk("tags"); ok {
tags := make([]map[string]interface{}, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, map[string]interface{}{
"Key": key,
"Value": value.(string),
})
}
request["Tag.*"] = tags
}
if v, ok := d.GetOk("page_number"); ok && v.(int) > 0 {
request["PageNumber"] = v.(int)
} else {
request["PageNumber"] = 1
}
if v, ok := d.GetOk("page_size"); ok && v.(int) > 0 {
request["PageSize"] = v.(int)
} else {
request["PageSize"] = PageSizeLarge
}
var objects []interface{}
var descriptionRegex *regexp.Regexp
if v, ok := d.GetOk("description_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
descriptionRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewAdsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_adb_db_clusters", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Items.DBCluster", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Items.DBCluster", response)
}
result, _ := resp.([]interface{})
if isPagingRequest(d) {
objects = result
break
}
for _, v := range result {
item := v.(map[string]interface{})
if descriptionRegex != nil {
if !descriptionRegex.MatchString(fmt.Sprint(item["DBClusterDescription"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DBClusterId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
descriptions := make([]string, 0)
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, v := range objects {
object := v.(map[string]interface{})
mapping := map[string]interface{}{
"commodity_code": object["CommodityCode"],
"compute_resource": object["ComputeResource"],
"connection_string": object["ConnectionString"],
"create_time": object["CreateTime"],
"db_cluster_category": convertAdbDBClusterCategoryResponse(object["Category"].(string)),
"id": fmt.Sprint(object["DBClusterId"]),
"db_cluster_id": fmt.Sprint(object["DBClusterId"]),
"db_cluster_network_type": object["DBClusterNetworkType"],
"network_type": object["DBClusterNetworkType"],
"db_cluster_type": object["DBClusterType"],
"db_node_class": object["DBNodeClass"],
"db_node_count": object["DBNodeCount"],
"db_node_storage": object["DBNodeStorage"],
"description": object["DBClusterDescription"],
"disk_type": object["DiskType"],
"dts_job_id": object["DtsJobId"],
"elastic_io_resource": formatInt(object["ElasticIOResource"]),
"engine": object["Engine"],
"executor_count": object["ExecutorCount"],
"expire_time": object["ExpireTime"],
"expired": fmt.Sprint(object["Expired"]),
"lock_mode": object["LockMode"],
"lock_reason": object["LockReason"],
"payment_type": convertAdbDBClusterPaymentTypeResponse(object["PayType"].(string)),
"charge_type": getChargeType(object["PayType"].(string)),
"port": formatInt(object["Port"]),
"rds_instance_id": object["RdsInstanceId"],
"region_id": object["RegionId"],
"resource_group_id": object["ResourceGroupId"],
"status": object["DBClusterStatus"],
"storage_resource": object["StorageResource"],
"vpc_cloud_instance_id": object["VPCCloudInstanceId"],
"vpc_id": object["VPCId"],
"vswitch_id": object["VSwitchId"],
"zone_id": object["ZoneId"],
"mode": object["Mode"],
"db_cluster_version": object["DBVersion"],
}
descriptions = append(descriptions, object["DBClusterDescription"].(string))
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags.Tag", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["Key"].(string)
value := t.(map[string]interface{})["Value"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["DBClusterId"]))
s = append(s, mapping)
continue
}
adbService := AdbService{client}
id := fmt.Sprint(object["DBClusterId"])
if object["PayType"].(string) == string(Prepaid) {
getResp, err := adbService.DescribeAutoRenewAttribute(id)
if err != nil {
return WrapError(err)
}
mapping["auto_renew_period"] = getResp["Duration"]
mapping["renewal_status"] = getResp["RenewalStatus"]
}
getResp1, err := adbService.DescribeDBClusterAccessWhiteList(id)
if err != nil {
return WrapError(err)
}
mapping["security_ips"] = strings.Split(getResp1["SecurityIPList"].(string), ",")
getResp2, err := adbService.DescribeAdbDbCluster(id)
if err != nil {
return WrapError(err)
}
mapping["engine_version"] = getResp2["EngineVersion"]
mapping["maintain_time"] = getResp2["MaintainTime"]
ids = append(ids, fmt.Sprint(object["DBClusterId"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("descriptions", descriptions); err != nil {
return WrapError(err)
}
if err := d.Set("clusters", s); err != nil {
return WrapError(err)
}
if err := d.Set("total_count", formatInt(response["TotalCount"])); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"sort"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/services/adb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudAdbZones() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAdbZonesRead,
Schema: map[string]*schema.Schema{
"multi": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"zones": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"multi_zone_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
},
}
}
func dataSourceAlicloudAdbZonesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
multi := d.Get("multi").(bool)
var zoneIds []string
request := adb.CreateDescribeRegionsRequest()
request.RegionId = client.RegionId
raw, err := client.WithAdbClient(func(adbClient *adb.Client) (interface{}, error) {
return adbClient.DescribeRegions(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_adb_zones", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
regions, _ := raw.(*adb.DescribeRegionsResponse)
if len(regions.Regions.Region) <= 0 {
return WrapError(fmt.Errorf("[ERROR] There is no available region for adb."))
}
for _, r := range regions.Regions.Region {
for _, zone := range r.Zones.Zone {
if multi && strings.Contains(zone.ZoneId, MULTI_IZ_SYMBOL) && r.RegionId == string(client.Region) {
zoneIds = append(zoneIds, zone.ZoneId)
continue
}
if !multi && !strings.Contains(zone.ZoneId, MULTI_IZ_SYMBOL) && r.RegionId == string(client.Region) {
zoneIds = append(zoneIds, zone.ZoneId)
continue
}
}
}
if len(zoneIds) > 0 {
sort.Strings(zoneIds)
}
var s []map[string]interface{}
if !multi {
for _, zoneId := range zoneIds {
mapping := map[string]interface{}{"id": zoneId}
s = append(s, mapping)
}
} else {
for _, zoneId := range zoneIds {
mapping := map[string]interface{}{
"id": zoneId,
"multi_zone_ids": splitMultiZoneId(zoneId),
}
s = append(s, mapping)
}
}
d.SetId(dataResourceIdHash(zoneIds))
if err := d.Set("zones", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", zoneIds); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudAlbAcls() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAlbAclsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"acl_ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"acl_name": {
Type: schema.TypeString,
Optional: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "Configuring", "Provisioning"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"acls": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"acl_entries": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Computed: true,
},
"entry": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"acl_id": {
Type: schema.TypeString,
Computed: true,
},
"acl_name": {
Type: schema.TypeString,
Computed: true,
},
"address_ip_version": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudAlbAclsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListAcls"
request := make(map[string]interface{})
if m, ok := d.GetOk("acl_ids"); ok {
for k, v := range m.([]interface{}) {
request[fmt.Sprintf("AclIds.%d", k+1)] = v.(string)
}
}
if v, ok := d.GetOk("acl_name"); ok {
AclNames := []string{v.(string)}
request["AclNames"] = AclNames
}
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var aclNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
aclNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_alb_acls", action, AlibabaCloudSdkGoERROR)
}
totalCount, err := jsonpath.Get("$.TotalCount", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.TotalCount", response)
}
if fmt.Sprint(totalCount) == "0" {
break
}
resp, err := jsonpath.Get("$.Acls", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Acls", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if aclNameRegex != nil && !aclNameRegex.MatchString(fmt.Sprint(item["AclName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["AclId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["AclStatus"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["AclId"]),
"acl_id": fmt.Sprint(object["AclId"]),
"acl_name": object["AclName"],
"address_ip_version": object["AddressIPVersion"],
"resource_group_id": object["ResourceGroupId"],
"status": object["AclStatus"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["AclName"])
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["AclId"])
albService := AlbService{client}
getResp, err := albService.ListAclEntries(id)
if err != nil {
return WrapError(err)
}
aclEntries := make([]map[string]interface{}, 0)
for _, v := range getResp {
temp1 := map[string]interface{}{
"description": v["Description"],
"entry": v["Entry"],
"status": v["Status"],
}
aclEntries = append(aclEntries, temp1)
}
mapping["acl_entries"] = aclEntries
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("acls", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudAlbHealthCheckTemplates() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAlbHealthCheckTemplatesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"health_check_template_ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"health_check_template_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[A-Za-z][A-Za-z0-9\\_\\.\\-]{1,127}$`), "The name must be 2 to 128 characters in length, and can contain letters, digits, periods (.), underscores (_), and hyphens (-). The name must start with a letter."),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"templates": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"health_check_codes": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"health_check_connect_port": {
Type: schema.TypeInt,
Computed: true,
},
"health_check_host": {
Type: schema.TypeString,
Computed: true,
},
"health_check_http_version": {
Type: schema.TypeString,
Computed: true,
},
"health_check_interval": {
Type: schema.TypeInt,
Computed: true,
},
"health_check_method": {
Type: schema.TypeString,
Computed: true,
},
"health_check_path": {
Type: schema.TypeString,
Computed: true,
},
"health_check_protocol": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"health_check_template_id": {
Type: schema.TypeString,
Computed: true,
},
"health_check_template_name": {
Type: schema.TypeString,
Computed: true,
},
"health_check_timeout": {
Type: schema.TypeInt,
Computed: true,
},
"healthy_threshold": {
Type: schema.TypeInt,
Computed: true,
},
"unhealthy_threshold": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudAlbHealthCheckTemplatesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListHealthCheckTemplates"
request := make(map[string]interface{})
if m, ok := d.GetOk("health_check_template_ids"); ok {
for k, v := range m.([]interface{}) {
request[fmt.Sprintf("HealthCheckTemplateIds.%d", k+1)] = v.(string)
}
}
if v, ok := d.GetOk("health_check_template_name"); ok {
request["HealthCheckTemplateNames.1"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var healthCheckTemplateNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
healthCheckTemplateNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_alb_health_check_templates", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.HealthCheckTemplates", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.HealthCheckTemplates", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if healthCheckTemplateNameRegex != nil && !healthCheckTemplateNameRegex.MatchString(fmt.Sprint(item["HealthCheckTemplateName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["HealthCheckTemplateId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"health_check_codes": object["HealthCheckCodes"],
"health_check_connect_port": formatInt(object["HealthCheckConnectPort"]),
"health_check_host": object["HealthCheckHost"],
"health_check_http_version": object["HealthCheckHttpVersion"],
"health_check_interval": formatInt(object["HealthCheckInterval"]),
"health_check_method": object["HealthCheckMethod"],
"health_check_path": object["HealthCheckPath"],
"health_check_protocol": object["HealthCheckProtocol"],
"id": fmt.Sprint(object["HealthCheckTemplateId"]),
"health_check_template_id": fmt.Sprint(object["HealthCheckTemplateId"]),
"health_check_template_name": object["HealthCheckTemplateName"],
"health_check_timeout": formatInt(object["HealthCheckTimeout"]),
"healthy_threshold": formatInt(object["HealthyThreshold"]),
"unhealthy_threshold": formatInt(object["UnhealthyThreshold"]),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["HealthCheckTemplateName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("templates", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudAlbListeners() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAlbListenersRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"listener_ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"listener_protocol": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"HTTP", "HTTPS", "QUIC"}, false),
},
"load_balancer_ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Provisioning", "Running", "Configuring", "Stopped"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"listeners": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"access_log_record_customized_headers_enabled": {
Type: schema.TypeBool,
Computed: true,
},
"access_log_tracing_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"tracing_enabled": {
Type: schema.TypeBool,
Computed: true,
},
"tracing_sample": {
Type: schema.TypeInt,
Computed: true,
},
"tracing_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"acl_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"acl_relations": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"acl_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"acl_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"certificates": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"certificate_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"default_actions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"type": {
Type: schema.TypeString,
Computed: true,
},
"forward_group_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"server_group_tuples": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"server_group_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
},
},
"gzip_enabled": {
Type: schema.TypeBool,
Computed: true,
},
"http2_enabled": {
Type: schema.TypeBool,
Computed: true,
},
"idle_timeout": {
Type: schema.TypeInt,
Computed: true,
},
"listener_description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"listener_id": {
Type: schema.TypeString,
Computed: true,
},
"listener_port": {
Type: schema.TypeInt,
Computed: true,
},
"listener_protocol": {
Type: schema.TypeString,
Computed: true,
},
"load_balancer_id": {
Type: schema.TypeString,
Computed: true,
},
"max_results": {
Type: schema.TypeString,
Computed: true,
},
"next_token": {
Type: schema.TypeString,
Computed: true,
},
"quic_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"quic_listener_id": {
Type: schema.TypeString,
Computed: true,
},
"quic_upgrade_enabled": {
Type: schema.TypeBool,
Computed: true,
},
},
},
},
"request_timeout": {
Type: schema.TypeInt,
Computed: true,
},
"security_policy_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"xforwarded_for_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"xforwardedforclientcert_issuerdnalias": {
Type: schema.TypeString,
Computed: true,
},
"xforwardedforclientcert_issuerdnenabled": {
Type: schema.TypeBool,
Computed: true,
},
"xforwardedforclientcertclientverifyalias": {
Type: schema.TypeString,
Computed: true,
},
"xforwardedforclientcertclientverifyenabled": {
Type: schema.TypeBool,
Computed: true,
},
"xforwardedforclientcertfingerprintalias": {
Type: schema.TypeString,
Computed: true,
},
"xforwardedforclientcertfingerprintenabled": {
Type: schema.TypeBool,
Computed: true,
},
"xforwardedforclientcertsubjectdnalias": {
Type: schema.TypeString,
Computed: true,
},
"xforwardedforclientcertsubjectdnenabled": {
Type: schema.TypeBool,
Computed: true,
},
"xforwardedforclientsrcportenabled": {
Type: schema.TypeBool,
Computed: true,
},
"xforwardedforenabled": {
Type: schema.TypeBool,
Computed: true,
},
"xforwardedforprotoenabled": {
Type: schema.TypeBool,
Computed: true,
},
"xforwardedforslbidenabled": {
Type: schema.TypeBool,
Computed: true,
},
"xforwardedforslbportenabled": {
Type: schema.TypeBool,
Computed: true,
},
},
},
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudAlbListenersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListListeners"
request := make(map[string]interface{})
if m, ok := d.GetOk("listener_ids"); ok {
for k, v := range m.([]interface{}) {
request[fmt.Sprintf("ListenerIds.%d", k+1)] = v.(string)
}
}
if v, ok := d.GetOk("listener_protocol"); ok {
request["ListenerProtocol"] = v
}
if m, ok := d.GetOk("load_balancer_ids"); ok {
for k, v := range m.([]interface{}) {
request[fmt.Sprintf("LoadBalancerIds.%d", k+1)] = v.(string)
}
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_alb_listeners", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Listeners", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Listeners", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ListenerId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["ListenerStatus"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"max_results": fmt.Sprint(response["MaxResults"]),
"next_token": response["NextToken"],
}
mapping["access_log_record_customized_headers_enabled"] = object["LogConfig.AccessLogRecordCustomizedHeadersEnabled"]
mapping["gzip_enabled"] = object["GzipEnabled"]
mapping["http2_enabled"] = object["Http2Enabled"]
mapping["idle_timeout"] = object["IdleTimeout"]
mapping["listener_description"] = object["ListenerDescription"]
mapping["id"] = fmt.Sprint(object["ListenerId"])
mapping["listener_id"] = object["ListenerId"]
mapping["listener_port"] = object["ListenerPort"]
mapping["listener_protocol"] = object["ListenerProtocol"]
mapping["load_balancer_id"] = object["LoadBalancerId"]
mapping["request_timeout"] = object["RequestTimeout"]
mapping["security_policy_id"] = object["SecurityPolicyId"]
mapping["status"] = object["ListenerStatus"]
xforwardedForConfigSli := make([]map[string]interface{}, 0)
if xforwardedForConfig, ok := object["XForwardedForConfig"]; ok && len(xforwardedForConfig.(map[string]interface{})) > 0 {
xforwardedForConfigMap := make(map[string]interface{})
xforwardedForConfigMap["xforwardedforclientcert_issuerdnalias"] = xforwardedForConfig.(map[string]interface{})["XForwardedForClientCertIssuerDNAlias"]
xforwardedForConfigMap["xforwardedforclientcert_issuerdnenabled"] = xforwardedForConfig.(map[string]interface{})["XForwardedForClientCertIssuerDNEnabled"]
xforwardedForConfigMap["xforwardedforclientcertclientverifyalias"] = xforwardedForConfig.(map[string]interface{})["XForwardedForClientCertClientVerifyAlias"]
xforwardedForConfigMap["xforwardedforclientcertclientverifyenabled"] = xforwardedForConfig.(map[string]interface{})["XForwardedForClientCertClientVerifyEnabled"]
xforwardedForConfigMap["xforwardedforclientcertfingerprintalias"] = xforwardedForConfig.(map[string]interface{})["XForwardedForClientCertFingerprintAlias"]
xforwardedForConfigMap["xforwardedforclientcertfingerprintenabled"] = xforwardedForConfig.(map[string]interface{})["XForwardedForClientCertFingerprintEnabled"]
xforwardedForConfigMap["xforwardedforclientcertsubjectdnalias"] = xforwardedForConfig.(map[string]interface{})["XForwardedForClientCertSubjectDNAlias"]
xforwardedForConfigMap["xforwardedforclientcertsubjectdnenabled"] = xforwardedForConfig.(map[string]interface{})["XForwardedForClientCertSubjectDNEnabled"]
xforwardedForConfigMap["xforwardedforclientsrcportenabled"] = xforwardedForConfig.(map[string]interface{})["XForwardedForClientSrcPortEnabled"]
xforwardedForConfigMap["xforwardedforenabled"] = xforwardedForConfig.(map[string]interface{})["XForwardedForEnabled"]
xforwardedForConfigMap["xforwardedforprotoenabled"] = xforwardedForConfig.(map[string]interface{})["XForwardedForProtoEnabled"]
xforwardedForConfigMap["xforwardedforslbidenabled"] = xforwardedForConfig.(map[string]interface{})["XForwardedForSLBIdEnabled"]
xforwardedForConfigMap["xforwardedforslbportenabled"] = xforwardedForConfig.(map[string]interface{})["XForwardedForSLBPortEnabled"]
xforwardedForConfigSli = append(xforwardedForConfigSli, xforwardedForConfigMap)
}
mapping["xforwarded_for_config"] = xforwardedForConfigSli
ids = append(ids, fmt.Sprint(mapping["id"]))
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["ListenerId"])
albService := AlbService{client}
getResp, err := albService.DescribeAlbListener(id)
if err != nil {
return WrapError(err)
}
certificatesMaps := make([]map[string]interface{}, 0)
if certificatesList, ok := getResp["Certificates"]; ok && certificatesList != nil {
for _, certificatesListItem := range certificatesList.([]interface{}) {
if certificatesListItemArg, ok := certificatesListItem.(map[string]interface{}); ok {
certificatesListItemMap := map[string]interface{}{}
certificatesListItemMap["certificate_id"] = certificatesListItemArg["CertificateId"]
certificatesMaps = append(certificatesMaps, certificatesListItemMap)
}
}
}
mapping["certificates"] = certificatesMaps
defaultActionsMaps := make([]map[string]interface{}, 0)
if defaultActionsList, ok := getResp["DefaultActions"].([]interface{}); ok {
for _, defaultActions := range defaultActionsList {
defaultActionsArg := defaultActions.(map[string]interface{})
defaultActionsMap := map[string]interface{}{}
defaultActionsMap["type"] = defaultActionsArg["Type"]
forwardGroupConfig := defaultActionsArg["ForwardGroupConfig"]
forwardGroupConfigArg := forwardGroupConfig.(map[string]interface{})
serverGroupTuplesMaps := make([]map[string]interface{}, 0)
for _, serverGroupTuples := range forwardGroupConfigArg["ServerGroupTuples"].([]interface{}) {
serverGroupTuplesArg := serverGroupTuples.(map[string]interface{})
serverGroupTuplesMap := map[string]interface{}{}
serverGroupTuplesMap["server_group_id"] = serverGroupTuplesArg["ServerGroupId"]
serverGroupTuplesMaps = append(serverGroupTuplesMaps, serverGroupTuplesMap)
}
forwardGroupConfigMaps := make([]map[string]interface{}, 0)
forwardGroupConfigMap := map[string]interface{}{}
forwardGroupConfigMap["server_group_tuples"] = serverGroupTuplesMaps
forwardGroupConfigMaps = append(forwardGroupConfigMaps, forwardGroupConfigMap)
defaultActionsMap["forward_group_config"] = forwardGroupConfigMaps
defaultActionsMaps = append(defaultActionsMaps, defaultActionsMap)
}
}
mapping["default_actions"] = defaultActionsMaps
aclConfigSli := make([]map[string]interface{}, 0)
if aclConfig, ok := getResp["AclConfig"]; ok && len(aclConfig.(map[string]interface{})) > 0 {
aclConfigMap := make(map[string]interface{})
aclRelationsSli := make([]map[string]interface{}, 0)
if v, ok := aclConfig.(map[string]interface{})["AclRelations"]; ok && len(v.([]interface{})) > 0 {
for _, aclRelations := range v.([]interface{}) {
aclRelationsMap := make(map[string]interface{})
aclRelationsMap["acl_id"] = aclRelations.(map[string]interface{})["AclId"]
aclRelationsMap["status"] = aclRelations.(map[string]interface{})["Status"]
aclRelationsSli = append(aclRelationsSli, aclRelationsMap)
}
}
aclConfigMap["acl_relations"] = aclRelationsSli
aclConfigMap["acl_type"] = aclConfig.(map[string]interface{})["AclType"]
aclConfigSli = append(aclConfigSli, aclConfigMap)
}
mapping["acl_config"] = aclConfigSli
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("listeners", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudAlbLoadBalancers() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAlbLoadBalancersRead,
Schema: map[string]*schema.Schema{
"address_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Intranet", "Internet"}, false),
},
"load_balancer_bussiness_status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Abnormal", "Normal"}, false),
Deprecated: "Field 'load_balancer_bussiness_status' has been deprecated from provider version 1.142.0 and it will be removed in the future version. Please use the new attribute 'load_balancer_business_status' instead.",
},
"load_balancer_business_status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Abnormal", "Normal"}, false),
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"load_balancer_ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"load_balancer_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Configuring", "CreateFailed", "Inactive", "Provisioning"}, false),
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"tags": tagsSchema(),
"vpc_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vpc_ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"balancers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"access_log_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"log_project": {
Type: schema.TypeString,
Computed: true,
},
"log_store": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"address_allocated_mode": {
Type: schema.TypeString,
Computed: true,
},
"address_type": {
Type: schema.TypeString,
Computed: true,
},
"bandwidth_package_id": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"deletion_protection_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enabled": {
Type: schema.TypeBool,
Computed: true,
},
"enabled_time": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"dns_name": {
Type: schema.TypeString,
Computed: true,
},
"load_balancer_billing_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"pay_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"load_balancer_bussiness_status": {
Type: schema.TypeString,
Computed: true,
Deprecated: "Field 'load_balancer_bussiness_status' has been deprecated from provider version 1.142.0 and it will be removed in the future version. Please use the new parameter 'load_balancer_business_status' instead.",
},
"load_balancer_business_status": {
Type: schema.TypeString,
Computed: true,
},
"load_balancer_edition": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"load_balancer_id": {
Type: schema.TypeString,
Computed: true,
},
"load_balancer_name": {
Type: schema.TypeString,
Computed: true,
},
"load_balancer_operation_locks": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"lock_reason": {
Type: schema.TypeString,
Computed: true,
},
"lock_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"modification_protection_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"reason": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_mappings": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"load_balancer_addresses": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"address": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudAlbLoadBalancersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListLoadBalancers"
request := make(map[string]interface{})
if v, ok := d.GetOk("address_type"); ok {
request["AddressType"] = v
}
if v, ok := d.GetOk("load_balancer_business_status"); ok {
request["LoadBalancerBussinessStatus"] = v
} else if v, ok := d.GetOk("load_balancer_bussiness_status"); ok {
request["LoadBalancerBussinessStatus"] = v
}
if m, ok := d.GetOk("load_balancer_ids"); ok {
for k, v := range m.([]interface{}) {
request[fmt.Sprintf("LoadBalancerIds.%d", k+1)] = v.(string)
}
}
if v, ok := d.GetOk("load_balancer_name"); ok {
request["LoadBalancerNames.1"] = v
}
if v, ok := d.GetOk("status"); ok {
request["LoadBalancerStatus"] = v
}
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("tags"); ok {
tags := make([]map[string]interface{}, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, map[string]interface{}{
"Key": key,
"Value": value.(string),
})
}
request["Tag"] = tags
}
if v, ok := d.GetOk("vpc_id"); ok {
request["VpcIds.*"] = v
}
if m, ok := d.GetOk("vpc_ids"); ok {
for k, v := range m.([]interface{}) {
request[fmt.Sprintf("VpcIds.%d", k+1)] = v.(string)
}
}
if v, ok := d.GetOk("zone_id"); ok {
request["ZoneId"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var loadBalancerNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
loadBalancerNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_alb_load_balancers", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.LoadBalancers", response)
if formatInt(response["TotalCount"]) != 0 && err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.LoadBalancers", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if loadBalancerNameRegex != nil && !loadBalancerNameRegex.MatchString(fmt.Sprint(item["LoadBalancerName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["LoadBalancerId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"access_log_config": object["AccessLogConfig"],
"address_allocated_mode": object["AddressAllocatedMode"],
"address_type": object["AddressType"],
"bandwidth_package_id": object["BandwidthPackageId"],
"create_time": object["CreateTime"],
"deletion_protection_config": object["DeletionProtectionConfig"],
"dns_name": object["DNSName"],
"load_balancer_business_status": object["LoadBalancerBussinessStatus"],
"load_balancer_bussiness_status": object["LoadBalancerBussinessStatus"],
"load_balancer_edition": object["LoadBalancerEdition"],
"id": fmt.Sprint(object["LoadBalancerId"]),
"load_balancer_id": fmt.Sprint(object["LoadBalancerId"]),
"load_balancer_name": object["LoadBalancerName"],
"modification_protection_config": object["ModificationProtectionConfig"],
"resource_group_id": object["ResourceGroupId"],
"vpc_id": object["VpcId"],
}
loadBalancerOperationLocks := make([]map[string]interface{}, 0)
if loadBalancerOperationLocksList, ok := object["LoadBalancerOperationLocks"].([]interface{}); ok {
for _, v := range loadBalancerOperationLocksList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"lock_reason": m1["LockReason"],
"lock_type": m1["LockType"],
}
loadBalancerOperationLocks = append(loadBalancerOperationLocks, temp1)
}
}
}
mapping["load_balancer_operation_locks"] = loadBalancerOperationLocks
accessLogConfigSli := make([]map[string]interface{}, 0)
if len(object["AccessLogConfig"].(map[string]interface{})) > 0 {
accessLogConfig := object["AccessLogConfig"]
accessLogConfigMap := make(map[string]interface{})
accessLogConfigMap["log_project"] = accessLogConfig.(map[string]interface{})["LogProject"]
accessLogConfigMap["log_store"] = accessLogConfig.(map[string]interface{})["LogStore"]
accessLogConfigSli = append(accessLogConfigSli, accessLogConfigMap)
}
mapping["access_log_config"] = accessLogConfigSli
deletionProtectionConfigSli := make([]map[string]interface{}, 0)
if len(object["DeletionProtectionConfig"].(map[string]interface{})) > 0 {
deletionProtectionConfig := object["DeletionProtectionConfig"]
deletionProtectionConfigMap := make(map[string]interface{})
deletionProtectionConfigMap["enabled"] = deletionProtectionConfig.(map[string]interface{})["Enabled"]
deletionProtectionConfigMap["enabled_time"] = deletionProtectionConfig.(map[string]interface{})["EnabledTime"]
deletionProtectionConfigSli = append(deletionProtectionConfigSli, deletionProtectionConfigMap)
}
mapping["deletion_protection_config"] = deletionProtectionConfigSli
modificationProtectionConfigSli := make([]map[string]interface{}, 0)
if len(object["ModificationProtectionConfig"].(map[string]interface{})) > 0 {
modificationProtectionConfig := object["ModificationProtectionConfig"]
modificationProtectionConfigMap := make(map[string]interface{})
modificationProtectionConfigMap["reason"] = modificationProtectionConfig.(map[string]interface{})["Reason"]
modificationProtectionConfigMap["status"] = modificationProtectionConfig.(map[string]interface{})["Status"]
modificationProtectionConfigSli = append(modificationProtectionConfigSli, modificationProtectionConfigMap)
}
mapping["modification_protection_config"] = modificationProtectionConfigSli
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["Key"].(string)
value := t.(map[string]interface{})["Value"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["LoadBalancerName"])
id := fmt.Sprint(object["LoadBalancerId"])
albService := AlbService{client}
getResp, err := albService.DescribeAlbLoadBalancer(id)
if err != nil {
return WrapError(err)
}
if statusOk && status != "" && status != getResp["LoadBalancerStatus"].(string) {
continue
}
mapping["status"] = getResp["LoadBalancerStatus"]
zoneMappings := make([]map[string]interface{}, 0)
if zoneMappingsList, ok := getResp["ZoneMappings"].([]interface{}); ok {
for _, v := range zoneMappingsList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"vswitch_id": m1["VSwitchId"],
"zone_id": m1["ZoneId"],
}
if m1["LoadBalancerAddresses"] != nil {
loadBalancerAddressesMaps := make([]map[string]interface{}, 0)
for _, loadBalancerAddressesValue := range m1["LoadBalancerAddresses"].([]interface{}) {
loadBalancerAddresses := loadBalancerAddressesValue.(map[string]interface{})
loadBalancerAddressesMap := map[string]interface{}{
"address": loadBalancerAddresses["Address"],
}
loadBalancerAddressesMaps = append(loadBalancerAddressesMaps, loadBalancerAddressesMap)
}
temp1["load_balancer_addresses"] = loadBalancerAddressesMaps
}
zoneMappings = append(zoneMappings, temp1)
}
}
}
mapping["zone_mappings"] = zoneMappings
loadBalancerBillingConfigSli := make([]map[string]interface{}, 0)
if object["LoadBalancerBillingConfig"] != nil && len(object["LoadBalancerBillingConfig"].(map[string]interface{})) > 0 {
loadBalancerBillingConfig := object["LoadBalancerBillingConfig"]
loadBalancerBillingConfigMap := make(map[string]interface{})
loadBalancerBillingConfigMap["pay_type"] = convertAlbLoadBalancerPaymentTypeResponse(loadBalancerBillingConfig.(map[string]interface{})["PayType"].(string))
loadBalancerBillingConfigSli = append(loadBalancerBillingConfigSli, loadBalancerBillingConfigMap)
}
mapping["load_balancer_billing_config"] = loadBalancerBillingConfigSli
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("balancers", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudAlbRules() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAlbRulesRead,
Schema: map[string]*schema.Schema{
"listener_ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"load_balancer_ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"rule_ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "Configuring", "Provisioning"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"listener_id": {
Type: schema.TypeString,
Computed: true,
},
"load_balancer_id": {
Type: schema.TypeString,
Computed: true,
},
"priority": {
Type: schema.TypeInt,
Computed: true,
},
"rule_actions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"fixed_response_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"content": {
Type: schema.TypeString,
Computed: true,
},
"content_type": {
Type: schema.TypeString,
Computed: true,
},
"http_code": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"forward_group_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"server_group_tuples": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"server_group_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
"insert_header_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Computed: true,
},
"value": {
Type: schema.TypeString,
Computed: true,
},
"value_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"order": {
Type: schema.TypeInt,
Computed: true,
},
"redirect_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"host": {
Type: schema.TypeString,
Computed: true,
},
"http_code": {
Type: schema.TypeString,
Computed: true,
},
"path": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeString,
Computed: true,
},
"protocol": {
Type: schema.TypeString,
Computed: true,
},
"query": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"rewrite_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"host": {
Type: schema.TypeString,
Computed: true,
},
"path": {
Type: schema.TypeString,
Computed: true,
},
"query": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"rule_conditions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cookie_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"values": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Computed: true,
},
"value": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
"header_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Computed: true,
},
"values": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"host_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"values": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"method_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"values": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"path_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"values": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"query_string_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"values": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Computed: true,
},
"value": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"rule_id": {
Type: schema.TypeString,
Computed: true,
},
"rule_name": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudAlbRulesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListRules"
request := make(map[string]interface{})
if m, ok := d.GetOk("listener_ids"); ok {
for k, v := range m.([]interface{}) {
request[fmt.Sprintf("ListenerIds.%d", k+1)] = v.(string)
}
}
if m, ok := d.GetOk("load_balancer_ids"); ok {
for k, v := range m.([]interface{}) {
request[fmt.Sprintf("LoadBalancerIds.%d", k+1)] = v.(string)
}
}
if m, ok := d.GetOk("rule_ids"); ok {
for k, v := range m.([]interface{}) {
request[fmt.Sprintf("RuleIds.%d", k+1)] = v.(string)
}
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var ruleNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
ruleNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_alb_rules", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Rules", response)
if formatInt(response["TotalCount"]) != 0 && err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Rules", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if ruleNameRegex != nil && !ruleNameRegex.MatchString(fmt.Sprint(item["RuleName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["RuleId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["RuleStatus"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"listener_id": object["ListenerId"],
"load_balancer_id": object["LoadBalancerId"],
"priority": formatInt(object["Priority"]),
"id": fmt.Sprint(object["RuleId"]),
"rule_id": fmt.Sprint(object["RuleId"]),
"rule_name": object["RuleName"],
"status": object["RuleStatus"],
}
ruleActionsMaps := make([]map[string]interface{}, 0)
if ruleActionsList, ok := object["RuleActions"]; ok {
for _, ruleActions := range ruleActionsList.([]interface{}) {
ruleActionsArg := ruleActions.(map[string]interface{})
ruleActionsMap := map[string]interface{}{}
ruleActionsMap["type"] = ruleActionsArg["Type"]
ruleActionsMap["order"] = formatInt(ruleActionsArg["Order"])
if forwardGroupConfig, ok := ruleActionsArg["ForwardGroupConfig"]; ok {
forwardGroupConfigArg := forwardGroupConfig.(map[string]interface{})
if len(forwardGroupConfigArg) > 0 {
serverGroupTuplesMaps := make([]map[string]interface{}, 0)
if forwardGroupConfigArgs, ok := forwardGroupConfigArg["ServerGroupTuples"].([]interface{}); ok {
for _, serverGroupTuples := range forwardGroupConfigArgs {
serverGroupTuplesArg := serverGroupTuples.(map[string]interface{})
serverGroupTuplesMap := map[string]interface{}{}
serverGroupTuplesMap["server_group_id"] = serverGroupTuplesArg["ServerGroupId"]
serverGroupTuplesMaps = append(serverGroupTuplesMaps, serverGroupTuplesMap)
}
}
if len(serverGroupTuplesMaps) > 0 {
forwardGroupConfigMaps := make([]map[string]interface{}, 0)
forwardGroupConfigMap := map[string]interface{}{}
forwardGroupConfigMap["server_group_tuples"] = serverGroupTuplesMaps
forwardGroupConfigMaps = append(forwardGroupConfigMaps, forwardGroupConfigMap)
ruleActionsMap["forward_group_config"] = forwardGroupConfigMaps
ruleActionsMaps = append(ruleActionsMaps, ruleActionsMap)
}
}
}
if fixedResponseConfig, ok := ruleActionsArg["FixedResponseConfig"]; ok {
fixedResponseConfigArg := fixedResponseConfig.(map[string]interface{})
if len(fixedResponseConfigArg) > 0 {
fixedResponseConfigMaps := make([]map[string]interface{}, 0)
fixedResponseConfigMap := make(map[string]interface{}, 0)
fixedResponseConfigMap["content"] = fixedResponseConfigArg["Content"]
fixedResponseConfigMap["content_type"] = fixedResponseConfigArg["ContentType"]
fixedResponseConfigMap["http_code"] = fixedResponseConfigArg["HttpCode"]
fixedResponseConfigMaps = append(fixedResponseConfigMaps, fixedResponseConfigMap)
ruleActionsMap["fixed_response_config"] = fixedResponseConfigMaps
ruleActionsMaps = append(ruleActionsMaps, ruleActionsMap)
}
}
if insertHeaderConfig, ok := ruleActionsArg["InsertHeaderConfig"]; ok {
insertHeaderConfigArg := insertHeaderConfig.(map[string]interface{})
if len(insertHeaderConfigArg) > 0 {
insertHeaderConfigMaps := make([]map[string]interface{}, 0)
insertHeaderConfigMap := make(map[string]interface{}, 0)
insertHeaderConfigMap["key"] = insertHeaderConfigArg["Key"]
insertHeaderConfigMap["value"] = insertHeaderConfigArg["Value"]
insertHeaderConfigMap["value_type"] = insertHeaderConfigArg["ValueType"]
insertHeaderConfigMaps = append(insertHeaderConfigMaps, insertHeaderConfigMap)
ruleActionsMap["insert_header_config"] = insertHeaderConfigMaps
ruleActionsMaps = append(ruleActionsMaps, ruleActionsMap)
}
}
if redirectConfig, ok := ruleActionsArg["RedirectConfig"]; ok {
redirectConfigArg := redirectConfig.(map[string]interface{})
if len(redirectConfigArg) > 0 {
redirectConfigMaps := make([]map[string]interface{}, 0)
redirectConfigMap := make(map[string]interface{}, 0)
redirectConfigMap["host"] = redirectConfigArg["Host"]
redirectConfigMap["http_code"] = redirectConfigArg["HttpCode"]
redirectConfigMap["path"] = redirectConfigArg["Path"]
redirectConfigMap["port"] = formatInt(redirectConfigArg["Port"])
redirectConfigMap["protocol"] = redirectConfigArg["Protocol"]
redirectConfigMap["query"] = redirectConfigArg["Query"]
redirectConfigMaps = append(redirectConfigMaps, redirectConfigMap)
ruleActionsMap["redirect_config"] = redirectConfigMaps
ruleActionsMaps = append(ruleActionsMaps, ruleActionsMap)
}
}
if rewriteConfig, ok := ruleActionsArg["RewriteConfig"]; ok {
rewriteConfigArg := rewriteConfig.(map[string]interface{})
if len(rewriteConfigArg) > 0 {
rewriteConfigMaps := make([]map[string]interface{}, 0)
rewriteConfigMap := make(map[string]interface{}, 0)
rewriteConfigMap["host"] = rewriteConfigArg["Host"]
rewriteConfigMap["path"] = rewriteConfigArg["Path"]
rewriteConfigMap["query"] = rewriteConfigArg["Query"]
rewriteConfigMaps = append(rewriteConfigMaps, rewriteConfigMap)
ruleActionsMap["rewrite_config"] = rewriteConfigMaps
ruleActionsMaps = append(ruleActionsMaps, ruleActionsMap)
}
}
}
}
mapping["rule_actions"] = ruleActionsMaps
ruleConditionsMaps := make([]map[string]interface{}, 0)
if ruleConditionsList, ok := object["RuleConditions"]; ok {
for _, ruleConditions := range ruleConditionsList.([]interface{}) {
ruleConditionsArg := ruleConditions.(map[string]interface{})
ruleConditionsMap := map[string]interface{}{}
ruleConditionsMap["type"] = ruleConditionsArg["Type"]
if cookieConfig, ok := ruleConditionsArg["CookieConfig"]; ok {
cookieConfigArg := cookieConfig.(map[string]interface{})
if len(cookieConfigArg) > 0 {
cookieConfigMaps := make([]map[string]interface{}, 0)
valuesMaps := make([]map[string]interface{}, 0)
for _, values := range cookieConfigArg["Values"].([]interface{}) {
valuesArg := values.(map[string]interface{})
valuesMap := map[string]interface{}{}
valuesMap["key"] = valuesArg["Key"]
valuesMap["value"] = valuesArg["Value"]
valuesMaps = append(valuesMaps, valuesMap)
}
cookieConfigMap := map[string]interface{}{}
cookieConfigMap["values"] = valuesMaps
cookieConfigMaps = append(cookieConfigMaps, cookieConfigMap)
ruleConditionsMap["cookie_config"] = cookieConfigMaps
ruleConditionsMaps = append(ruleConditionsMaps, ruleConditionsMap)
}
}
if headerConfig, ok := ruleConditionsArg["HeaderConfig"]; ok {
headerConfigArg := headerConfig.(map[string]interface{})
if len(headerConfigArg) > 0 {
headerConfigMaps := make([]map[string]interface{}, 0)
headerConfigMap := map[string]interface{}{}
headerConfigMap["values"] = headerConfigArg["Values"].([]interface{})
headerConfigMap["key"] = headerConfigArg["Key"]
headerConfigMaps = append(headerConfigMaps, headerConfigMap)
ruleConditionsMap["header_config"] = headerConfigMaps
ruleConditionsMaps = append(ruleConditionsMaps, ruleConditionsMap)
}
}
if queryStringConfig, ok := ruleConditionsArg["QueryStringConfig"]; ok {
queryStringConfigArg := queryStringConfig.(map[string]interface{})
if len(queryStringConfigArg) > 0 {
queryStringConfigMaps := make([]map[string]interface{}, 0)
queryStringValuesMaps := make([]map[string]interface{}, 0)
for _, values := range queryStringConfigArg["Values"].([]interface{}) {
valuesArg := values.(map[string]interface{})
valuesMap := map[string]interface{}{}
valuesMap["key"] = valuesArg["Key"]
valuesMap["value"] = valuesArg["Value"]
queryStringValuesMaps = append(queryStringValuesMaps, valuesMap)
}
queryStringConfigMap := map[string]interface{}{}
queryStringConfigMap["values"] = queryStringValuesMaps
queryStringConfigMaps = append(queryStringConfigMaps, queryStringConfigMap)
ruleConditionsMap["query_string_config"] = queryStringConfigMaps
ruleConditionsMaps = append(ruleConditionsMaps, ruleConditionsMap)
}
}
if hostConfig, ok := ruleConditionsArg["HostConfig"]; ok {
hostConfigArg := hostConfig.(map[string]interface{})
if len(hostConfigArg) > 0 {
hostConfigMaps := make([]map[string]interface{}, 0)
hostConfigMap := map[string]interface{}{}
hostConfigMap["values"] = hostConfigArg["Values"].([]interface{})
hostConfigMaps = append(hostConfigMaps, hostConfigMap)
ruleConditionsMap["host_config"] = hostConfigMaps
ruleConditionsMaps = append(ruleConditionsMaps, ruleConditionsMap)
}
}
if methodConfig, ok := ruleConditionsArg["MethodConfig"]; ok {
methodConfigArg := methodConfig.(map[string]interface{})
if len(methodConfigArg) > 0 {
methodConfigMaps := make([]map[string]interface{}, 0)
methodConfigMap := map[string]interface{}{}
methodConfigMap["values"] = methodConfigArg["Values"].([]interface{})
methodConfigMaps = append(methodConfigMaps, methodConfigMap)
ruleConditionsMap["method_config"] = methodConfigMaps
ruleConditionsMaps = append(ruleConditionsMaps, ruleConditionsMap)
}
}
if pathConfig, ok := ruleConditionsArg["PathConfig"]; ok {
pathConfigArg := pathConfig.(map[string]interface{})
if len(pathConfigArg) > 0 {
pathConfigMaps := make([]map[string]interface{}, 0)
pathConfigMap := map[string]interface{}{}
pathConfigMap["values"] = pathConfigArg["Values"].([]interface{})
pathConfigMaps = append(pathConfigMaps, pathConfigMap)
ruleConditionsMap["path_config"] = pathConfigMaps
ruleConditionsMaps = append(ruleConditionsMaps, ruleConditionsMap)
}
}
}
}
mapping["rule_conditions"] = ruleConditionsMaps
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["RuleName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("rules", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudAlbSecurityPolicies() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAlbSecurityPoliciesRead,
Schema: map[string]*schema.Schema{
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"security_policy_ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"security_policy_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "Configuring"}, false),
},
"tags": tagsSchema(),
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"policies": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ciphers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"security_policy_id": {
Type: schema.TypeString,
Computed: true,
},
"security_policy_name": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tls_versions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
},
}
}
func dataSourceAlicloudAlbSecurityPoliciesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListSecurityPolicies"
request := make(map[string]interface{})
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("security_policy_ids"); ok {
request["SecurityPolicyIds"] = v
}
if v, ok := d.GetOk("security_policy_name"); ok {
request["SecurityPolicyNames"] = []string{v.(string)}
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var securityPolicyNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
securityPolicyNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_alb_security_policies", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.SecurityPolicies", response)
if formatInt(response["Total"]) != 0 && err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.SecurityPolicies", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if securityPolicyNameRegex != nil && !securityPolicyNameRegex.MatchString(fmt.Sprint(item["SecurityPolicyName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["SecurityPolicyId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["SecurityPolicyStatus"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"ciphers": object["Ciphers"],
"resource_group_id": object["ResourceGroupId"],
"id": fmt.Sprint(object["SecurityPolicyId"]),
"security_policy_id": fmt.Sprint(object["SecurityPolicyId"]),
"security_policy_name": object["SecurityPolicyName"],
"status": object["SecurityPolicyStatus"],
"tls_versions": object["TLSVersions"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["SecurityPolicyName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("policies", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudAlbServerGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAlbServerGroupsRead,
Schema: map[string]*schema.Schema{
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"server_group_ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"server_group_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "Configuring", "Provisioning"}, false),
},
"tags": tagsSchema(),
"vpc_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"health_check_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"health_check_codes": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"health_check_connect_port": {
Type: schema.TypeInt,
Computed: true,
},
"health_check_enabled": {
Type: schema.TypeBool,
Computed: true,
},
"health_check_host": {
Type: schema.TypeString,
Computed: true,
},
"health_check_http_version": {
Type: schema.TypeString,
Computed: true,
},
"health_check_interval": {
Type: schema.TypeInt,
Computed: true,
},
"health_check_method": {
Type: schema.TypeString,
Computed: true,
},
"health_check_path": {
Type: schema.TypeString,
Computed: true,
},
"health_check_protocol": {
Type: schema.TypeString,
Computed: true,
},
"health_check_timeout": {
Type: schema.TypeInt,
Computed: true,
},
"healthy_threshold": {
Type: schema.TypeInt,
Computed: true,
},
"unhealthy_threshold": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"protocol": {
Type: schema.TypeString,
Computed: true,
},
"scheduler": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"server_group_id": {
Type: schema.TypeString,
Computed: true,
},
"server_group_name": {
Type: schema.TypeString,
Computed: true,
},
"servers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeInt,
Computed: true,
},
"server_id": {
Type: schema.TypeString,
Computed: true,
},
"server_ip": {
Type: schema.TypeString,
Computed: true,
},
"server_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"weight": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"sticky_session_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cookie": {
Type: schema.TypeString,
Computed: true,
},
"cookie_timeout": {
Type: schema.TypeInt,
Computed: true,
},
"sticky_session_enabled": {
Type: schema.TypeBool,
Computed: true,
},
"sticky_session_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudAlbServerGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListServerGroups"
request := make(map[string]interface{})
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if m, ok := d.GetOk("server_group_ids"); ok {
for k, v := range m.([]interface{}) {
request[fmt.Sprintf("ServerGroupIds.%d", k+1)] = v.(string)
}
}
if v, ok := d.GetOk("server_group_name"); ok {
request["ServerGroupNames.1"] = v.(string)
}
if v, ok := d.GetOk("tags"); ok {
request["Tag"] = tagsFromMap(v.(map[string]interface{}))
}
if v, ok := d.GetOk("vpc_id"); ok {
request["VpcId"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var serverGroupNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
serverGroupNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_alb_server_groups", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.ServerGroups", response)
if formatInt(response["TotalCount"]) != 0 && err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.ServerGroups", response)
}
result, _ := resp.([]interface{})
if resp != nil {
for _, v := range result {
item := v.(map[string]interface{})
if serverGroupNameRegex != nil && !serverGroupNameRegex.MatchString(fmt.Sprint(item["ServerGroupName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ServerGroupId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["ServerGroupStatus"].(string) {
continue
}
objects = append(objects, item)
}
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"protocol": object["Protocol"],
"scheduler": object["Scheduler"],
"id": fmt.Sprint(object["ServerGroupId"]),
"server_group_id": fmt.Sprint(object["ServerGroupId"]),
"server_group_name": object["ServerGroupName"],
"status": object["ServerGroupStatus"],
"sticky_session_config": object["StickySessionConfig"],
"vpc_id": object["VpcId"],
}
healthCheckConfigSli := make([]map[string]interface{}, 0)
if len(object["HealthCheckConfig"].(map[string]interface{})) > 0 {
healthCheckConfig := object["HealthCheckConfig"]
healthCheckConfigMap := make(map[string]interface{})
healthCheckConfigMap["health_check_codes"] = healthCheckConfig.(map[string]interface{})["HealthCheckCodes"]
healthCheckConfigMap["health_check_connect_port"] = formatInt(healthCheckConfig.(map[string]interface{})["HealthCheckConnectPort"])
healthCheckConfigMap["health_check_enabled"] = healthCheckConfig.(map[string]interface{})["HealthCheckEnabled"]
healthCheckConfigMap["health_check_host"] = healthCheckConfig.(map[string]interface{})["HealthCheckHost"]
healthCheckConfigMap["health_check_http_version"] = healthCheckConfig.(map[string]interface{})["HealthCheckHttpVersion"]
healthCheckConfigMap["health_check_interval"] = formatInt(healthCheckConfig.(map[string]interface{})["HealthCheckInterval"])
healthCheckConfigMap["health_check_method"] = healthCheckConfig.(map[string]interface{})["HealthCheckMethod"]
healthCheckConfigMap["health_check_path"] = healthCheckConfig.(map[string]interface{})["HealthCheckPath"]
healthCheckConfigMap["health_check_protocol"] = healthCheckConfig.(map[string]interface{})["HealthCheckProtocol"]
healthCheckConfigMap["health_check_timeout"] = formatInt(healthCheckConfig.(map[string]interface{})["HealthCheckTimeout"])
healthCheckConfigMap["healthy_threshold"] = formatInt(healthCheckConfig.(map[string]interface{})["HealthyThreshold"])
healthCheckConfigMap["unhealthy_threshold"] = formatInt(healthCheckConfig.(map[string]interface{})["UnhealthyThreshold"])
healthCheckConfigSli = append(healthCheckConfigSli, healthCheckConfigMap)
}
mapping["health_check_config"] = healthCheckConfigSli
stickySessionConfigSli := make([]map[string]interface{}, 0)
if len(object["StickySessionConfig"].(map[string]interface{})) > 0 {
stickySessionConfig := object["StickySessionConfig"]
stickySessionConfigMap := make(map[string]interface{})
stickySessionConfigMap["cookie"] = stickySessionConfig.(map[string]interface{})["Cookie"]
stickySessionConfigMap["cookie_timeout"] = stickySessionConfig.(map[string]interface{})["CookieTimeout"]
stickySessionConfigMap["sticky_session_enabled"] = stickySessionConfig.(map[string]interface{})["StickySessionEnabled"]
stickySessionConfigMap["sticky_session_type"] = stickySessionConfig.(map[string]interface{})["StickySessionType"]
stickySessionConfigSli = append(stickySessionConfigSli, stickySessionConfigMap)
}
mapping["sticky_session_config"] = stickySessionConfigSli
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["ServerGroupName"])
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["ServerGroupId"])
albService := AlbService{client}
serversList, err := albService.ListServerGroupServers(id)
if err != nil {
return WrapError(err)
}
servers := make([]map[string]interface{}, 0)
for _, v := range serversList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"description": m1["Description"],
"port": formatInt(m1["Port"]),
"server_id": m1["ServerId"],
"server_ip": m1["ServerIp"],
"server_type": m1["ServerType"],
"status": m1["Status"],
"weight": formatInt(m1["Weight"]),
}
servers = append(servers, temp1)
}
}
mapping["servers"] = servers
tagResp, _ := albService.ListTagResources(id, "servergroup")
mapping["tags"] = tagsToMap(tagResp)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudAlbZones() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAlbZonesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"zones": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
"local_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudAlbZonesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeZones"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
var objects []map[string]interface{}
var response map[string]interface{}
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_alb_zones", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Zones", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Zones", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
objects = append(objects, item)
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["ZoneId"]),
"zone_id": object["ZoneId"],
"local_name": object["LocalName"],
}
ids = append(ids, fmt.Sprint(object["ZoneId"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("zones", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudAlidnsAccessStrategies() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAlidnsAccessStrategiesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"lang": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"strategy_mode": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"GEO", "LATENCY"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"strategies": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"access_strategy_id": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"create_timestamp": {
Type: schema.TypeString,
Computed: true,
},
"default_addr_pool_type": {
Type: schema.TypeString,
Computed: true,
},
"default_addr_pools": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"addr_count": {
Type: schema.TypeInt,
Computed: true,
},
"addr_pool_id": {
Type: schema.TypeString,
Computed: true,
},
"lba_weight": {
Type: schema.TypeInt,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"default_available_addr_num": {
Type: schema.TypeInt,
Computed: true,
},
"default_latency_optimization": {
Type: schema.TypeString,
Computed: true,
},
"default_lba_strategy": {
Type: schema.TypeString,
Computed: true,
},
"default_max_return_addr_num": {
Type: schema.TypeInt,
Computed: true,
},
"default_min_available_addr_num": {
Type: schema.TypeInt,
Computed: true,
},
"effective_addr_pool_group_type": {
Type: schema.TypeString,
Computed: true,
},
"failover_addr_pool_type": {
Type: schema.TypeString,
Computed: true,
},
"failover_addr_pools": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"addr_count": {
Type: schema.TypeInt,
Computed: true,
},
"addr_pool_id": {
Type: schema.TypeString,
Computed: true,
},
"lba_weight": {
Type: schema.TypeInt,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"failover_available_addr_num": {
Type: schema.TypeInt,
Computed: true,
},
"failover_latency_optimization": {
Type: schema.TypeString,
Computed: true,
},
"failover_lba_strategy": {
Type: schema.TypeString,
Computed: true,
},
"failover_max_return_addr_num": {
Type: schema.TypeInt,
Computed: true,
},
"failover_min_available_addr_num": {
Type: schema.TypeInt,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"access_mode": {
Type: schema.TypeString,
Computed: true,
},
"lines": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"group_code": {
Type: schema.TypeString,
Computed: true,
},
"group_name": {
Type: schema.TypeString,
Computed: true,
},
"line_code": {
Type: schema.TypeString,
Computed: true,
},
"line_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"strategy_mode": {
Type: schema.TypeString,
Computed: true,
},
"strategy_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudAlidnsAccessStrategiesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDnsGtmAccessStrategies"
request := make(map[string]interface{})
request["InstanceId"] = d.Get("instance_id")
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
request["StrategyMode"] = d.Get("strategy_mode")
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
nameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewAlidnsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_alidns_access_strategies", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Strategies.Strategy", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Strategies.Strategy", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if nameRegex != nil {
if !nameRegex.MatchString(fmt.Sprint(item["StrategyName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["StrategyId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["StrategyId"]),
"access_strategy_id": fmt.Sprint(object["StrategyId"]),
"create_time": object["CreateTime"],
"create_timestamp": fmt.Sprint(object["CreateTimestamp"]),
"effective_addr_pool_group_type": object["EffectiveAddrPoolGroupType"],
"strategy_name": object["StrategyName"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["StrategyName"])
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["StrategyId"])
alidnsService := AlidnsService{client}
getResp, err := alidnsService.DescribeAlidnsAccessStrategy(id)
if err != nil {
return WrapError(err)
}
mapping["default_addr_pool_type"] = getResp["DefaultAddrPoolType"]
defaultAddrPool := make([]map[string]interface{}, 0)
if v, ok := getResp["DefaultAddrPools"]; ok {
defaultAddrPools := v.(map[string]interface{})
if v, ok := defaultAddrPools["DefaultAddrPool"]; ok {
defaultAddrPoolList := v.([]interface{})
for _, v := range defaultAddrPoolList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"addr_count": formatInt(m1["AddrCount"]),
"addr_pool_id": m1["Id"],
"lba_weight": formatInt(m1["LbaWeight"]),
"name": m1["Name"],
}
defaultAddrPool = append(defaultAddrPool, temp1)
}
}
}
}
mapping["default_addr_pools"] = defaultAddrPool
if v, ok := getResp["DefaultAvailableAddrNum"]; ok && fmt.Sprint(v) != "0" {
mapping["default_available_addr_num"] = formatInt(v)
}
mapping["default_latency_optimization"] = getResp["DefaultLatencyOptimization"]
mapping["default_lba_strategy"] = getResp["DefaultLbaStrategy"]
if v, ok := getResp["DefaultMaxReturnAddrNum"]; ok && fmt.Sprint(v) != "0" {
mapping["default_max_return_addr_num"] = formatInt(v)
}
if v, ok := getResp["DefaultMinAvailableAddrNum"]; ok && fmt.Sprint(v) != "0" {
mapping["default_min_available_addr_num"] = formatInt(v)
}
mapping["failover_addr_pool_type"] = getResp["FailoverAddrPoolType"]
mapping["access_mode"] = getResp["AccessMode"]
failoverAddrPool := make([]map[string]interface{}, 0)
if v, ok := getResp["FailoverAddrPools"]; ok {
failoverAddrPools := v.(map[string]interface{})
if v, ok := failoverAddrPools["FailoverAddrPool"]; ok {
failoverAddrPoolList := v.([]interface{})
for _, v := range failoverAddrPoolList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"addr_count": formatInt(m1["AddrCount"]),
"addr_pool_id": m1["Id"],
"lba_weight": formatInt(m1["LbaWeight"]),
"name": m1["Name"],
}
failoverAddrPool = append(failoverAddrPool, temp1)
}
}
}
}
mapping["failover_addr_pools"] = failoverAddrPool
if v, ok := getResp["FailoverAvailableAddrNum"]; ok && fmt.Sprint(v) != "0" {
mapping["failover_available_addr_num"] = formatInt(v)
}
mapping["failover_latency_optimization"] = getResp["FailoverLatencyOptimization"]
mapping["failover_lba_strategy"] = getResp["FailoverLbaStrategy"]
if v, ok := getResp["FailoverMaxReturnAddrNum"]; ok && fmt.Sprint(v) != "0" {
mapping["failover_max_return_addr_num"] = formatInt(v)
}
if v, ok := getResp["FailoverMinAvailableAddrNum"]; ok && fmt.Sprint(v) != "0" {
mapping["failover_min_available_addr_num"] = formatInt(v)
}
mapping["instance_id"] = getResp["InstanceId"]
lineMaps := make([]map[string]interface{}, 0)
if v, ok := getResp["Lines"]; ok {
lines := v.(map[string]interface{})
if v, ok := lines["Line"]; ok {
lineList := v.([]interface{})
for _, v := range lineList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"group_code": m1["GroupCode"],
"group_name": m1["GroupName"],
"line_code": m1["LineCode"],
"line_name": m1["LineName"],
}
lineMaps = append(lineMaps, temp1)
}
}
}
}
mapping["lines"] = lineMaps
mapping["strategy_mode"] = getResp["StrategyMode"]
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("strategies", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudAlidnsAddressPools() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAlidnsAddressPoolsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"pools": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"address_pool_id": {
Type: schema.TypeString,
Computed: true,
},
"address_pool_name": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"create_timestamp": {
Type: schema.TypeString,
Computed: true,
},
"lba_strategy": {
Type: schema.TypeString,
Computed: true,
},
"monitor_status": {
Type: schema.TypeString,
Computed: true,
},
"monitor_config_id": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"update_time": {
Type: schema.TypeString,
Computed: true,
},
"update_timestamp": {
Type: schema.TypeString,
Computed: true,
},
"address": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"address": {
Type: schema.TypeString,
Computed: true,
},
"attribute_info": {
Type: schema.TypeString,
Computed: true,
},
"lba_weight": {
Type: schema.TypeInt,
Computed: true,
},
"mode": {
Type: schema.TypeString,
Computed: true,
},
"remark": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudAlidnsAddressPoolsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDnsGtmInstanceAddressPools"
request := make(map[string]interface{})
request["InstanceId"] = d.Get("instance_id")
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var addressPoolNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
addressPoolNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewAlidnsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_alidns_address_pools", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.AddrPools.AddrPool", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.AddrPools.AddrPool", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if addressPoolNameRegex != nil && !addressPoolNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["AddrPoolId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["AddrPoolId"]),
"instance_id": request["InstanceId"],
"address_pool_id": fmt.Sprint(object["AddrPoolId"]),
"address_pool_name": object["Name"],
"create_time": object["CreateTime"],
"create_timestamp": fmt.Sprint(object["CreateTimestamp"]),
"lba_strategy": object["LbaStrategy"],
"type": object["Type"],
"update_timestamp": fmt.Sprint(object["UpdateTimestamp"]),
"update_time": fmt.Sprint(object["UpdateTime"]),
"monitor_status": object["MonitorStatus"],
"monitor_config_id": object["MonitorConfigId"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["AddrPoolId"])
alidnsService := AlidnsService{client}
getResp, err := alidnsService.DescribeAlidnsAddressPool(id)
if err != nil {
return WrapError(err)
}
addressMaps := make([]map[string]interface{}, 0)
if v, ok := getResp["Addrs"]; ok {
addressList := v.(map[string]interface{})
if v, ok := addressList["Addr"]; ok {
addressSli := v.([]interface{})
for _, v := range addressSli {
if m1, ok := v.(map[string]interface{}); ok {
addressMap := make(map[string]interface{})
addressMap["attribute_info"] = m1["AttributeInfo"]
addressMap["remark"] = m1["Remark"]
if v, ok := m1["LbaWeight"]; ok {
addressMap["lba_weight"] = v
}
addressMap["address"] = m1["Addr"]
addressMap["mode"] = m1["Mode"]
addressMaps = append(addressMaps, addressMap)
}
}
}
}
mapping["address"] = addressMaps
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("pools", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudAlidnsCustomLines() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAlidnsCustomLinesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"domain_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"lang": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"lines": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"code": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"custom_line_id": {
Type: schema.TypeString,
Computed: true,
},
"custom_line_name": {
Type: schema.TypeString,
Computed: true,
},
"domain_name": {
Type: schema.TypeString,
Computed: true,
},
"ip_segment_list": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"end_ip": {
Type: schema.TypeString,
Computed: true,
},
"start_ip": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudAlidnsCustomLinesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeCustomLines"
request := make(map[string]interface{})
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
request["DomainName"] = d.Get("domain_name")
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var customLineNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
customLineNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewAlidnsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_alidns_custom_lines", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.CustomLines", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.CustomLines", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if customLineNameRegex != nil && !customLineNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Id"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"code": object["Code"],
"id": fmt.Sprint(object["Id"]),
"custom_line_id": fmt.Sprint(object["Id"]),
"custom_line_name": object["Name"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["Id"])
alidnsService := AlidnsService{client}
getResp, err := alidnsService.DescribeAlidnsCustomLine(id)
if err != nil {
return WrapError(err)
}
mapping["domain_name"] = getResp["DomainName"]
if ipSegmentList, ok := object["IpSegmentList"]; ok {
ipSegments := make([]map[string]interface{}, 0)
for _, ipSegmentListItem := range ipSegmentList.([]interface{}) {
ipSegmentMap := ipSegmentListItem.(map[string]interface{})
ipSegmentArg := make(map[string]interface{}, 0)
ipSegmentArg["end_ip"] = ipSegmentMap["EndIp"]
ipSegmentArg["start_ip"] = ipSegmentMap["StartIp"]
ipSegments = append(ipSegments, ipSegmentArg)
}
mapping["ip_segment_list"] = ipSegments
}
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("lines", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/alidns"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudAlidnsDomainGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAlidnsDomainGroupsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"domain_count": {
Type: schema.TypeInt,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"group_id": {
Type: schema.TypeString,
Computed: true,
},
"group_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudAlidnsDomainGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := alidns.CreateDescribeDomainGroupsRequest()
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var objects []alidns.DomainGroup
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
nameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
for {
raw, err := client.WithAlidnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.DescribeDomainGroups(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_alidns_domain_groups", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ := raw.(*alidns.DescribeDomainGroupsResponse)
for _, item := range response.DomainGroups.DomainGroup {
if nameRegex != nil {
if !nameRegex.MatchString(item.GroupName) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[item.GroupId]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(response.DomainGroups.DomainGroup) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
ids := make([]string, len(objects))
names := make([]string, len(objects))
s := make([]map[string]interface{}, len(objects))
for i, object := range objects {
mapping := map[string]interface{}{
"domain_count": object.DomainCount,
"id": object.GroupId,
"group_id": object.GroupId,
"group_name": object.GroupName,
}
ids[i] = object.GroupId
names[i] = object.GroupName
s[i] = mapping
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/alidns"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudAlidnsDomains() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAlidnsDomainsRead,
Schema: map[string]*schema.Schema{
"ali_domain": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"domain_name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"group_name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"version_code": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"key_word": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"lang": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"search_mode": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"starmark": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"tags": tagsSchema(),
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"domains": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ali_domain": {
Type: schema.TypeBool,
Computed: true,
},
"available_ttls": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeInt},
},
"dns_servers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"domain_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"domain_name": {
Type: schema.TypeString,
Computed: true,
},
"group_id": {
Type: schema.TypeString,
Computed: true,
},
"group_name": {
Type: schema.TypeString,
Computed: true,
},
"in_black_hole": {
Type: schema.TypeBool,
Computed: true,
},
"in_clean": {
Type: schema.TypeBool,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"line_type": {
Type: schema.TypeString,
Computed: true,
},
"min_ttl": {
Type: schema.TypeInt,
Computed: true,
},
"puny_code": {
Type: schema.TypeString,
Computed: true,
},
"record_line_tree_json": {
Type: schema.TypeString,
Computed: true,
},
"record_lines": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"father_code": {
Type: schema.TypeString,
Computed: true,
},
"line_code": {
Type: schema.TypeString,
Computed: true,
},
"line_display_name": {
Type: schema.TypeString,
Computed: true,
},
"line_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"region_lines": {
Type: schema.TypeBool,
Computed: true,
},
"remark": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"slave_dns": {
Type: schema.TypeBool,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"version_code": {
Type: schema.TypeString,
Computed: true,
},
"version_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudAlidnsDomainsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := alidns.CreateDescribeDomainsRequest()
if v, ok := d.GetOk("group_id"); ok {
request.GroupId = v.(string)
}
if v, ok := d.GetOk("key_word"); ok {
request.KeyWord = v.(string)
}
if v, ok := d.GetOk("lang"); ok {
request.Lang = v.(string)
}
if v, ok := d.GetOk("resource_group_id"); ok {
request.ResourceGroupId = v.(string)
}
if v, ok := d.GetOk("search_mode"); ok {
request.SearchMode = v.(string)
}
if v, ok := d.GetOkExists("starmark"); ok {
request.Starmark = requests.NewBoolean(v.(bool))
}
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var objects []alidns.DomainInDescribeDomains
var domainNameRegex *regexp.Regexp
if v, ok := d.GetOk("domain_name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
domainNameRegex = r
}
var groupNameRegex *regexp.Regexp
if v, ok := d.GetOk("group_name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
groupNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
tagsMap := make(map[string]interface{})
if v, ok := d.GetOk("tags"); ok && len(v.(map[string]interface{})) > 0 {
tagsMap = v.(map[string]interface{})
}
var response *alidns.DescribeDomainsResponse
for {
raw, err := client.WithAlidnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.DescribeDomains(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_alidns_domains", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ = raw.(*alidns.DescribeDomainsResponse)
for _, item := range response.Domains.Domain {
if v, ok := d.GetOk("ali_domain"); ok && item.AliDomain != v.(bool) {
continue
}
if domainNameRegex != nil {
if !domainNameRegex.MatchString(item.DomainName) {
continue
}
}
if groupNameRegex != nil {
if !groupNameRegex.MatchString(item.GroupName) {
continue
}
}
if v, ok := d.GetOk("instance_id"); ok && v.(string) != "" && item.InstanceId != v.(string) {
continue
}
if v, ok := d.GetOk("version_code"); ok && v.(string) != "" && item.VersionCode != v.(string) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[item.DomainName]; !ok {
continue
}
}
if len(tagsMap) > 0 {
if len(item.Tags.Tag) != len(tagsMap) {
continue
}
match := true
for _, tag := range item.Tags.Tag {
if v, ok := tagsMap[tag.Key]; !ok || v.(string) != tag.Value {
match = false
break
}
}
if !match {
continue
}
}
objects = append(objects, item)
}
if len(response.Domains.Domain) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
ids := make([]string, 0)
names := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"ali_domain": object.AliDomain,
"domain_id": object.DomainId,
"id": object.DomainName,
"domain_name": object.DomainName,
"group_id": object.GroupId,
"group_name": object.GroupName,
"instance_id": object.InstanceId,
"puny_code": object.PunyCode,
"remark": object.Remark,
"resource_group_id": object.ResourceGroupId,
"version_code": object.VersionCode,
"version_name": object.VersionName,
}
ids = append(ids, object.DomainName)
tags := make(map[string]string)
for _, t := range object.Tags.Tag {
tags[t.Key] = t.Value
}
mapping["tags"] = tags
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
names = append(names, object.DomainName)
s = append(s, mapping)
continue
}
request := alidns.CreateDescribeDomainInfoRequest()
request.RegionId = client.RegionId
request.DomainName = object.DomainName
raw, err := client.WithAlidnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.DescribeDomainInfo(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_alidns_domains", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
responseGet, _ := raw.(*alidns.DescribeDomainInfoResponse)
mapping["available_ttls"] = responseGet.AvailableTtls.AvailableTtl
mapping["dns_servers"] = responseGet.DnsServers.DnsServer
mapping["in_black_hole"] = responseGet.InBlackHole
mapping["in_clean"] = responseGet.InClean
mapping["line_type"] = responseGet.LineType
mapping["min_ttl"] = responseGet.MinTtl
mapping["record_line_tree_json"] = responseGet.RecordLineTreeJson
recordLines := make([]map[string]interface{}, len(responseGet.RecordLines.RecordLine))
for i, v := range responseGet.RecordLines.RecordLine {
mapping1 := map[string]interface{}{
"father_code": v.FatherCode,
"line_code": v.LineCode,
"line_display_name": v.LineDisplayName,
"line_name": v.LineName,
}
recordLines[i] = mapping1
}
mapping["record_lines"] = recordLines
mapping["region_lines"] = responseGet.RegionLines
mapping["slave_dns"] = responseGet.SlaveDns
names = append(names, object.DomainName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("domains", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudAlidnsGtmInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAlidnsGtmInstancesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"lang": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Computed: true,
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"alert_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"dingtalk_notice": {
Type: schema.TypeBool,
Computed: true,
},
"email_notice": {
Type: schema.TypeBool,
Computed: true,
},
"notice_type": {
Type: schema.TypeString,
Computed: true,
},
"sms_notice": {
Type: schema.TypeBool,
Computed: true,
},
},
},
},
"alert_group": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"cname_type": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"expire_time": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_name": {
Type: schema.TypeString,
Computed: true,
},
"strategy_mode": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"public_cname_mode": {
Type: schema.TypeString,
Computed: true,
},
"public_rr": {
Type: schema.TypeString,
Computed: true,
},
"public_user_domain_name": {
Type: schema.TypeString,
Computed: true,
},
"public_zone_name": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"ttl": {
Type: schema.TypeInt,
Computed: true,
},
"package_edition": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudAlidnsGtmInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDnsGtmInstances"
request := make(map[string]interface{})
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewAlidnsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_alidns_gtm_instances", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.GtmInstances", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.GtmInstances", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["InstanceId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"payment_type": object["PaymentType"],
"create_time": object["CreateTime"],
"expire_time": object["ExpireTime"],
"id": fmt.Sprint(object["InstanceId"]),
"instance_id": fmt.Sprint(object["InstanceId"]),
"resource_group_id": object["ResourceGroupId"],
"package_edition": object["VersionCode"],
}
if config, ok := object["Config"].(map[string]interface{}); ok {
mapping["public_zone_name"] = config["PublicZoneName"]
mapping["cname_type"] = config["CnameType"]
mapping["instance_name"] = config["InstanceName"]
mapping["strategy_mode"] = config["StrategyMode"]
mapping["public_cname_mode"] = config["PublicCnameMode"]
mapping["public_rr"] = config["PublicRr"]
mapping["public_user_domain_name"] = config["PublicUserDomainName"]
if v, ok := config["Ttl"]; ok {
mapping["ttl"] = formatInt(v)
}
if v, ok := config["AlertGroup"].(string); ok {
vv, err := convertJsonStringToList(v)
if err != nil {
return WrapError(err)
} else {
mapping["alert_group"] = vv
}
}
if alertConfigsList, ok := config["AlertConfig"]; ok {
alertConfigConfigArgs := alertConfigsList.([]interface{})
alertConfigsMaps := make([]map[string]interface{}, 0)
for _, alertConfigMapArgitem := range alertConfigConfigArgs {
alertConfigMapArg := alertConfigMapArgitem.(map[string]interface{})
alertConfigsMap := map[string]interface{}{}
alertConfigsMap["sms_notice"] = alertConfigMapArg["SmsNotice"]
alertConfigsMap["notice_type"] = alertConfigMapArg["NoticeType"]
alertConfigsMap["email_notice"] = alertConfigMapArg["EmailNotice"]
alertConfigsMap["dingtalk_notice"] = alertConfigMapArg["DingtalkNotice"]
alertConfigsMaps = append(alertConfigsMaps, alertConfigsMap)
}
mapping["alert_config"] = alertConfigsMaps
}
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudAlidnsInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAlidnsInstancesRead,
Schema: map[string]*schema.Schema{
"domain_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"lang": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"user_client_ip": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"dns_security": {
Type: schema.TypeString,
Computed: true,
},
"domain": {
Type: schema.TypeString,
Computed: true,
},
"domain_numbers": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"version_code": {
Type: schema.TypeString,
Computed: true,
},
"version_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudAlidnsInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDnsProductInstances"
request := make(map[string]interface{})
if v, ok := d.GetOk("domain_type"); ok {
request["DomainType"] = v
}
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
if v, ok := d.GetOk("user_client_ip"); ok {
request["UserClientIp"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewAlidnsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_alidns_instances", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.DnsProducts.DnsProduct", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.DnsProducts.DnsProduct", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["InstanceId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"dns_security": convertDnsSecurityResponse(object["DnsSecurity"].(string)),
"domain": object["Domain"],
"domain_numbers": fmt.Sprint(object["BindDomainCount"]),
"id": fmt.Sprint(object["InstanceId"]),
"instance_id": fmt.Sprint(object["InstanceId"]),
"payment_type": object["PaymentType"],
"version_code": object["VersionCode"],
"version_name": object["VersionName"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/alidns"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudAlidnsRecords() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAlidnsRecordsRead,
Schema: map[string]*schema.Schema{
"direction": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"domain_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"group_id": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"key_word": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"lang": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"line": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "default",
},
"order_by": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"rr_key_word": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"search_mode": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ENABLE", "DISABLE"}, false),
Default: "ENABLE",
},
"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"A", "NS", "MX", "TXT", "CNAME", "SRV", "AAAA", "CAA", "REDIRECT_URL", "FORWORD_URL"}, false),
},
"type_key_word": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"value_key_word": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"rr_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"value_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"records": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"domain_name": {
Type: schema.TypeString,
Computed: true,
},
"line": {
Type: schema.TypeString,
Computed: true,
},
"locked": {
Type: schema.TypeBool,
Computed: true,
},
"priority": {
Type: schema.TypeInt,
Computed: true,
},
"rr": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"record_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"ttl": {
Type: schema.TypeInt,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"value": {
Type: schema.TypeString,
Computed: true,
},
"remark": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudAlidnsRecordsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := alidns.CreateDescribeDomainRecordsRequest()
if v, ok := d.GetOk("direction"); ok {
request.Direction = v.(string)
}
request.DomainName = d.Get("domain_name").(string)
if v, ok := d.GetOk("group_id"); ok {
request.GroupId = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("key_word"); ok {
request.KeyWord = v.(string)
}
if v, ok := d.GetOk("lang"); ok {
request.Lang = v.(string)
}
if v, ok := d.GetOk("line"); ok {
request.Line = v.(string)
}
if v, ok := d.GetOk("order_by"); ok {
request.OrderBy = v.(string)
}
if v, ok := d.GetOk("rr_key_word"); ok {
request.RRKeyWord = v.(string)
}
if v, ok := d.GetOk("search_mode"); ok {
request.SearchMode = v.(string)
}
if v, ok := d.GetOk("status"); ok {
request.Status = v.(string)
}
if v, ok := d.GetOk("type"); ok {
request.Type = v.(string)
}
if v, ok := d.GetOk("type_key_word"); ok {
request.TypeKeyWord = v.(string)
}
if v, ok := d.GetOk("value_key_word"); ok {
request.ValueKeyWord = v.(string)
}
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var objects []alidns.Record
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var rrRegex *regexp.Regexp
if v, ok := d.GetOk("rr_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
rrRegex = r
}
var valueRegex *regexp.Regexp
if v, ok := d.GetOk("value_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
valueRegex = r
}
for {
raw, err := client.WithAlidnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.DescribeDomainRecords(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_alidns_records", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ := raw.(*alidns.DescribeDomainRecordsResponse)
for _, item := range response.DomainRecords.Record {
if rrRegex != nil {
if !rrRegex.MatchString(item.RR) {
continue
}
}
if valueRegex != nil {
if !valueRegex.MatchString(item.Value) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[item.RecordId]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(response.DomainRecords.Record) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
ids := make([]string, len(objects))
s := make([]map[string]interface{}, len(objects))
for i, object := range objects {
mapping := map[string]interface{}{
"domain_name": object.DomainName,
"line": object.Line,
"locked": object.Locked,
"priority": object.Priority,
"rr": object.RR,
"id": object.RecordId,
"record_id": object.RecordId,
"status": object.Status,
"ttl": object.TTL,
"type": object.Type,
"value": object.Value,
"remark": object.Remark,
}
ids[i] = object.RecordId
s[i] = mapping
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("records", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/services/alikafka"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudAlikafkaConsumerGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAlikafkaConsumerGroupsRead,
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"consumer_id_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
// Computed values
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"consumer_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"consumer_id": {
Type: schema.TypeString,
Computed: true,
},
"remark": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
},
},
},
},
}
}
func dataSourceAlicloudAlikafkaConsumerGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alikafkaService := AlikafkaService{client}
request := alikafka.CreateGetConsumerListRequest()
request.InstanceId = d.Get("instance_id").(string)
request.RegionId = client.RegionId
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
raw, err := alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.GetConsumerList(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_alikafka_consumer_groups", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*alikafka.GetConsumerListResponse)
var filteredConsumerGroups []alikafka.ConsumerVO
nameRegex, ok := d.GetOk("consumer_id_regex")
for _, consumer := range response.ConsumerList.ConsumerVO {
var r *regexp.Regexp
if ok && nameRegex.(string) != "" {
if nameRegex != "" {
r, err = regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
}
}
if r != nil && !r.MatchString(consumer.ConsumerId) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(consumer.InstanceId, ":", consumer.ConsumerId)]; !ok {
continue
}
}
filteredConsumerGroups = append(filteredConsumerGroups, consumer)
}
return alikafkaConsumerGroupsDecriptionAttributes(d, filteredConsumerGroups, meta)
}
func alikafkaConsumerGroupsDecriptionAttributes(d *schema.ResourceData, consumerGroupsInfo []alikafka.ConsumerVO, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alikafkaService := AlikafkaService{client}
var ids []string
var names []string
var s []map[string]interface{}
for _, item := range consumerGroupsInfo {
mapping := map[string]interface{}{
"id": fmt.Sprint(item.InstanceId, ":", item.ConsumerId),
"instance_id": item.InstanceId,
"consumer_id": item.ConsumerId,
"remark": item.Remark,
"tags": alikafkaService.tagVOTagsToMap(item.Tags.TagVO),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, item.ConsumerId)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), ids)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudAlikafkaInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAlikafkaInstancesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"service_status": {
Type: schema.TypeInt,
Computed: true,
},
"deploy_type": {
Type: schema.TypeInt,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"io_max": {
Type: schema.TypeInt,
Computed: true,
},
"eip_max": {
Type: schema.TypeInt,
Computed: true,
},
"disk_type": {
Type: schema.TypeInt,
Computed: true,
},
"disk_size": {
Type: schema.TypeInt,
Computed: true,
},
"topic_quota": {
Type: schema.TypeInt,
Computed: true,
},
"paid_type": {
Type: schema.TypeString,
Computed: true,
},
"spec_type": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
"end_point": {
Type: schema.TypeString,
Computed: true,
},
"security_group": {
Type: schema.TypeString,
Computed: true,
},
"service_version": {
Type: schema.TypeString,
Computed: true,
},
"config": {
Type: schema.TypeString,
Computed: true,
},
"expired_time": {
Type: schema.TypeInt,
Computed: true,
},
"msg_retain": {
Type: schema.TypeInt,
Computed: true,
},
"ssl_end_point": {
Type: schema.TypeString,
Computed: true,
},
"upgrade_service_detail_info": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"current2_open_source_version": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"allowed_list": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"deploy_type": {
Type: schema.TypeString,
Computed: true,
},
"vpc_list": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"allowed_ip_list": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"port_range": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"internet_list": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"allowed_ip_list": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"port_range": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
"domain_endpoint": {
Type: schema.TypeString,
Computed: true,
},
"ssl_domain_endpoint": {
Type: schema.TypeString,
Computed: true,
},
"sasl_domain_endpoint": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
},
},
},
},
}
}
func dataSourceAlicloudAlikafkaInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "GetInstanceList"
request := make(map[string]interface{})
conn, err := client.NewAlikafkaClient()
if err != nil {
return WrapError(err)
}
request["RegionId"] = client.RegionId
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
nameRegex = regexp.MustCompile(v.(string))
}
var response map[string]interface{}
pageNo, pageSize := 1, PageSizeLarge
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_alikafka_instances", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.InstanceList.InstanceVO", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.InstanceList.InstanceVO", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if nameRegex != nil && !nameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["InstanceId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < pageSize {
break
}
pageNo++
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
paidType := PostPaid
if object["PaidType"] == 0 {
paidType = PrePaid
}
mapping := map[string]interface{}{
"id": object["InstanceId"],
"name": object["Name"],
"create_time": object["CreateTime"],
"service_status": object["ServiceStatus"],
"deploy_type": object["DeployType"],
"vpc_id": object["VpcId"],
"vswitch_id": object["VSwitchId"],
"io_max": object["IoMax"],
"eip_max": object["EipMax"],
"disk_type": object["DiskType"],
"disk_size": object["DiskSize"],
"topic_quota": object["TopicNumLimit"],
"paid_type": paidType,
"service_version": object["UpgradeServiceDetailInfo"].(map[string]interface{})["Current2OpenSourceVersion"],
"spec_type": object["SpecType"],
"zone_id": object["ZoneId"],
"end_point": object["EndPoint"],
"security_group": object["SecurityGroup"],
"config": object["AllConfig"],
"expired_time": object["ExpiredTime"],
"msg_retain": object["MsgRetain"],
"ssl_end_point": object["SslEndPoint"],
"domain_endpoint": object["DomainEndpoint"],
"ssl_domain_endpoint": object["SslDomainEndpoint"],
"sasl_domain_endpoint": object["SaslDomainEndpoint"],
}
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags.TagVO", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["Key"].(string)
value := t.(map[string]interface{})["Value"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
DetailInfoMaps := make([]map[string]interface{}, 0)
if _, ok := object["UpgradeServiceDetailInfo"].(map[string]interface{}); ok {
UpgradeServiceDetailInfoMap := map[string]interface{}{}
UpgradeServiceDetailInfoMap["current2_open_source_version"] = object["UpgradeServiceDetailInfo"].(map[string]interface{})["Current2OpenSourceVersion"]
DetailInfoMaps = append(DetailInfoMaps, UpgradeServiceDetailInfoMap)
}
mapping["upgrade_service_detail_info"] = DetailInfoMaps
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, mapping["name"])
id := fmt.Sprint(object["InstanceId"])
AlikaService := AlikafkaService{client}
if d.Get("enable_details").(bool) {
getResp, err := AlikaService.GetAllowedIpList(id)
if err != nil {
return WrapError(err)
}
allowedListMaps := make([]map[string]interface{}, 0)
if defaultActionsList, ok := getResp["AllowedList"].(map[string]interface{}); ok {
defaultActionsMap := map[string]interface{}{}
defaultActionsMap["deploy_type"] = defaultActionsList["DeployType"]
if forwardGroupConfigArg, ok := defaultActionsList["VpcList"].([]interface{}); ok {
serverGroupTuplesMaps := make([]map[string]interface{}, 0)
for _, serverGroupTuples := range forwardGroupConfigArg {
serverGroupTuplesArg := serverGroupTuples.(map[string]interface{})
serverGroupTuplesMap := map[string]interface{}{}
serverGroupTuplesMap["port_range"] = serverGroupTuplesArg["PortRange"]
serverGroupTuplesMap["allowed_ip_list"] = serverGroupTuplesArg["AllowedIpList"]
serverGroupTuplesMaps = append(serverGroupTuplesMaps, serverGroupTuplesMap)
}
defaultActionsMap["vpc_list"] = serverGroupTuplesMaps
}
if forwardGroupConfigArg, ok := defaultActionsList["InternetList"].([]interface{}); ok {
serverGroupTuplesMaps := make([]map[string]interface{}, 0)
for _, serverGroupTuples := range forwardGroupConfigArg {
serverGroupTuplesArg := serverGroupTuples.(map[string]interface{})
serverGroupTuplesMap := map[string]interface{}{}
serverGroupTuplesMap["port_range"] = serverGroupTuplesArg["PortRange"]
serverGroupTuplesMap["allowed_ip_list"] = serverGroupTuplesArg["AllowedIpList"]
serverGroupTuplesMaps = append(serverGroupTuplesMaps, serverGroupTuplesMap)
}
defaultActionsMap["internet_list"] = serverGroupTuplesMaps
}
allowedListMaps = append(allowedListMaps, defaultActionsMap)
}
mapping["allowed_list"] = allowedListMaps
}
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"github.com/aliyun/alibaba-cloud-sdk-go/services/alikafka"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudAlikafkaSaslAcls() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAlikafkaSaslAclsRead,
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"username": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"acl_resource_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Group", "Topic"}, false),
},
"acl_resource_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.ValidateRegexp,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"acls": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"username": {
Type: schema.TypeString,
Computed: true,
},
"acl_resource_type": {
Type: schema.TypeString,
Computed: true,
},
"acl_resource_name": {
Type: schema.TypeString,
Computed: true,
},
"acl_resource_pattern_type": {
Type: schema.TypeString,
Computed: true,
},
"host": {
Type: schema.TypeString,
Computed: true,
},
"acl_operation_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudAlikafkaSaslAclsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alikafkaService := AlikafkaService{client}
request := alikafka.CreateDescribeAclsRequest()
request.InstanceId = d.Get("instance_id").(string)
request.RegionId = client.RegionId
request.Username = d.Get("username").(string)
request.AclResourceType = d.Get("acl_resource_type").(string)
request.AclResourceName = d.Get("acl_resource_name").(string)
raw, err := alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.DescribeAcls(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"BIZ_SUBSCRIPTION_NOT_FOUND", "BIZ_TOPIC_NOT_FOUND"}) {
var emptyValue []alikafka.KafkaAclVO
return alikafkaSaslAclsDecriptionAttributes(d, emptyValue, meta)
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_alikafka_sasl_acls", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*alikafka.DescribeAclsResponse)
return alikafkaSaslAclsDecriptionAttributes(d, response.KafkaAclList.KafkaAclVO, meta)
}
func alikafkaSaslAclsDecriptionAttributes(d *schema.ResourceData, kafkaAclsInfo []alikafka.KafkaAclVO, meta interface{}) error {
var names []string
var s []map[string]interface{}
for _, item := range kafkaAclsInfo {
mapping := map[string]interface{}{
"username": item.Username,
"acl_resource_type": item.AclResourceType,
"acl_resource_name": item.AclResourceName,
"acl_resource_pattern_type": item.AclResourcePatternType,
"host": item.Host,
"acl_operation_type": item.AclOperationType,
}
name := fmt.Sprintf("%s:%s:%s:%s:%s", item.Username, item.AclResourceType, item.AclResourceName, item.AclResourcePatternType, item.AclOperationType)
names = append(names, name)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(names))
if err := d.Set("acls", s); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/services/alikafka"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudAlikafkaSaslUsers() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAlikafkaSaslUsersRead,
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"users": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"username": {
Type: schema.TypeString,
Computed: true,
},
"password": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudAlikafkaSaslUsersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alikafkaService := AlikafkaService{client}
request := alikafka.CreateDescribeSaslUsersRequest()
request.InstanceId = d.Get("instance_id").(string)
request.RegionId = client.RegionId
raw, err := alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.DescribeSaslUsers(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_alikafka_sasl_users", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*alikafka.DescribeSaslUsersResponse)
var filteredSaslUsers []alikafka.SaslUserVO
nameRegex, ok := d.GetOk("name_regex")
if ok && nameRegex.(string) != "" {
var r *regexp.Regexp
if nameRegex != "" {
r, err = regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
}
for _, saslUser := range response.SaslUserList.SaslUserVO {
if r != nil && !r.MatchString(saslUser.Username) {
continue
}
filteredSaslUsers = append(filteredSaslUsers, saslUser)
}
} else {
filteredSaslUsers = response.SaslUserList.SaslUserVO
}
return alikafkaSaslUsersDecriptionAttributes(d, filteredSaslUsers, meta)
}
func alikafkaSaslUsersDecriptionAttributes(d *schema.ResourceData, saslUsersInfo []alikafka.SaslUserVO, meta interface{}) error {
var names []string
var s []map[string]interface{}
for _, item := range saslUsersInfo {
mapping := map[string]interface{}{
"username": item.Username,
"password": item.Password,
}
names = append(names, item.Username)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(names))
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("users", s); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudAlikafkaTopics() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAlikafkaTopicsRead,
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
// Computed values
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"topic": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"page_number": {
Type: schema.TypeInt,
Optional: true,
},
"page_size": {
Type: schema.TypeInt,
Optional: true,
Default: 50,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"topics": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"topic": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"local_topic": {
Type: schema.TypeBool,
Computed: true,
},
"compact_topic": {
Type: schema.TypeBool,
Computed: true,
},
"partition_num": {
Type: schema.TypeInt,
Computed: true,
},
"remark": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeInt,
Computed: true,
},
"status_name": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
},
},
},
"total_count": {
Type: schema.TypeInt,
Computed: true,
},
},
}
}
func dataSourceAlicloudAlikafkaTopicsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "GetTopicList"
request := make(map[string]interface{})
conn, err := client.NewAlikafkaClient()
if err != nil {
return WrapError(err)
}
request["RegionId"] = client.RegionId
request["InstanceId"] = d.Get("instance_id").(string)
if v, ok := d.GetOk("topic"); ok {
request["Topic"] = v
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
nameRegex = regexp.MustCompile(v.(string))
}
var response map[string]interface{}
if v, ok := d.GetOk("page_number"); ok && v.(int) > 0 {
request["CurrentPage"] = v.(int)
} else {
request["CurrentPage"] = 1
}
if v, ok := d.GetOk("page_size"); ok && v.(int) > 0 {
request["PageSize"] = v.(int)
} else {
request["PageSize"] = PageSizeLarge
}
var objects []interface{}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_alikafka_topics", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.TopicList.TopicVO", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.TopicList.TopicVO", response)
}
result, _ := resp.([]interface{})
if isPagingRequest(d) {
objects = result
break
}
for _, v := range result {
item := v.(map[string]interface{})
if nameRegex != nil && !nameRegex.MatchString(fmt.Sprint(item["Topic"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["InstanceId"], ":", item["Topic"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < request["PageSize"].(int) {
break
}
request["CurrentPage"] = request["CurrentPage"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, v := range objects {
object := v.(map[string]interface{})
mapping := map[string]interface{}{
"id": fmt.Sprint(object["InstanceId"], ":", object["Topic"]),
"topic": object["Topic"],
"create_time": object["CreateTime"],
"local_topic": object["LocalTopic"],
"compact_topic": object["CompactTopic"],
"partition_num": object["PartitionNum"],
"remark": object["Remark"],
"status": object["Status"],
"status_name": object["StatusName"],
"instance_id": object["InstanceId"],
}
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags.TagVO", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["Key"].(string)
value := t.(map[string]interface{})["Value"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, mapping["name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("topics", s); err != nil {
return WrapError(err)
}
if err := d.Set("total_count", formatInt(response["Total"])); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudAmqpBindings() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAmqpBindingsRead,
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"virtual_host_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"bindings": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"argument": {
Type: schema.TypeString,
Computed: true,
},
"binding_key": {
Type: schema.TypeString,
Computed: true,
},
"binding_type": {
Type: schema.TypeString,
Computed: true,
},
"destination_name": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"source_exchange": {
Type: schema.TypeString,
Computed: true,
},
"virtual_host_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudAmqpBindingsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListBindings"
request := make(map[string]interface{})
request["InstanceId"] = d.Get("instance_id")
request["VirtualHost"] = d.Get("virtual_host_name")
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var response map[string]interface{}
conn, err := client.NewOnsproxyClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-12-12"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_amqp_bindings", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Data.Bindings", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Data.Bindings", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(request["InstanceId"], ":", request["VirtualHost"], ":", object["SourceExchange"], ":", object["DestinationName"]),
"argument": object["Argument"],
"binding_key": object["BindingKey"],
"binding_type": object["BindingType"],
"destination_name": object["DestinationName"],
"instance_id": request["InstanceId"],
"source_exchange": object["SourceExchange"],
"virtual_host_name": request["VirtualHost"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("bindings", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudAmqpExchanges() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAmqpExchangesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"virtual_host_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"exchanges": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"attributes": {
Type: schema.TypeMap,
Computed: true,
},
"auto_delete_state": {
Type: schema.TypeBool,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"exchange_name": {
Type: schema.TypeString,
Computed: true,
},
"exchange_type": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"virtual_host_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudAmqpExchangesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListExchanges"
request := make(map[string]interface{})
request["InstanceId"] = d.Get("instance_id")
request["VirtualHost"] = d.Get("virtual_host_name")
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var exchangeNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
exchangeNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewOnsproxyClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-12-12"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_amqp_exchanges", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Data.Exchanges", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Data.Exchanges", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if exchangeNameRegex != nil && !exchangeNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Name"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"auto_delete_state": object["AutoDeleteState"],
"create_time": fmt.Sprint(object["CreateTime"]),
"id": fmt.Sprint(object["Name"]),
"exchange_name": fmt.Sprint(object["Name"]),
"exchange_type": object["ExchangeType"],
"instance_id": request["InstanceId"],
"virtual_host_name": object["VHostName"],
}
attributesMap := make(map[string]string)
if object["Attributes"] != nil {
for key, value := range object["Attributes"].(map[string]interface{}) {
attributesMap[key] = fmt.Sprint(value)
}
}
mapping["attributes"] = attributesMap
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("exchanges", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudAmqpInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAmqpInstancesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"DEPLOYING", "EXPIRED", "RELEASED", "SERVING"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"expire_time": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_name": {
Type: schema.TypeString,
Computed: true,
},
"instance_type": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"private_end_point": {
Type: schema.TypeString,
Computed: true,
},
"public_endpoint": {
Type: schema.TypeString,
Computed: true,
},
"renewal_duration": {
Type: schema.TypeInt,
Computed: true,
},
"renewal_duration_unit": {
Type: schema.TypeString,
Computed: true,
},
"renewal_status": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"support_eip": {
Type: schema.TypeBool,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudAmqpInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListInstances"
request := make(map[string]interface{})
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var instanceNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
instanceNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewOnsproxyClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-12-12"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_amqp_instances", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Data.Instances", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Data.Instances", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if instanceNameRegex != nil && !instanceNameRegex.MatchString(fmt.Sprint(item["InstanceName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["InstanceId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": fmt.Sprint(object["OrderCreateTime"]),
"expire_time": fmt.Sprint(object["ExpireTime"]),
"id": fmt.Sprint(object["InstanceId"]),
"instance_id": fmt.Sprint(object["InstanceId"]),
"instance_name": object["InstanceName"],
"instance_type": convertAmqpInstanceInstanceTypeResponse(object["InstanceType"]),
"private_end_point": object["PrivateEndpoint"],
"public_endpoint": object["PublicEndpoint"],
"status": object["Status"],
"support_eip": object["SupportEIP"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["InstanceName"])
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["InstanceId"])
bssOpenApiService := BssOpenApiService{client}
getResp, err := bssOpenApiService.QueryAvailableInstances(id, "ons", "ons_onsproxy_pre", "ons_onsproxy_public_intl")
if err != nil {
return WrapError(err)
}
mapping["payment_type"] = getResp["SubscriptionType"]
if v, ok := getResp["RenewalDuration"]; ok && fmt.Sprint(v) != "0" {
mapping["renewal_duration"] = formatInt(v)
}
mapping["renewal_duration_unit"] = convertAmqpInstanceRenewalDurationUnitResponse(getResp["RenewalDurationUnit"])
mapping["renewal_status"] = getResp["RenewStatus"]
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudAmqpQueues() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAmqpQueuesRead,
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"virtual_host_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"queues": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"attributes": {
Type: schema.TypeMap,
Computed: true,
},
"auto_delete_state": {
Type: schema.TypeBool,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"exclusive_state": {
Type: schema.TypeBool,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"last_consume_time": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"queue_name": {
Type: schema.TypeString,
Computed: true,
},
"virtual_host_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudAmqpQueuesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListQueues"
request := make(map[string]interface{})
request["InstanceId"] = d.Get("instance_id")
request["VirtualHost"] = d.Get("virtual_host_name")
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var queueNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
queueNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewOnsproxyClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-12-12"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_amqp_queues", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Data.Queues", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Data.Queues", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if queueNameRegex != nil && !queueNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Name"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"auto_delete_state": object["AutoDeleteState"],
"create_time": fmt.Sprint(object["CreateTime"]),
"exclusive_state": object["ExclusiveState"],
"instance_id": request["InstanceId"],
"last_consume_time": fmt.Sprint(object["LastConsumeTime"]),
"id": fmt.Sprint(object["Name"]),
"queue_name": fmt.Sprint(object["Name"]),
"virtual_host_name": request["VirtualHost"],
}
attributesMap := make(map[string]string)
if object["Attributes"] != nil {
for key, value := range object["Attributes"].(map[string]interface{}) {
attributesMap[key] = fmt.Sprint(value)
}
}
mapping["attributes"] = attributesMap
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("queues", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudAmqpVirtualHosts() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAmqpVirtualHostsRead,
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"hosts": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"virtual_host_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudAmqpVirtualHostsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListVirtualHosts"
request := make(map[string]interface{})
request["InstanceId"] = d.Get("instance_id")
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var virtualHostNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
virtualHostNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewOnsproxyClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-12-12"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_amqp_virtual_hosts", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Data.VirtualHosts", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Data.VirtualHosts", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if virtualHostNameRegex != nil && !virtualHostNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Name"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"instance_id": request["InstanceId"],
"id": fmt.Sprint(object["Name"]),
"virtual_host_name": fmt.Sprint(object["Name"]),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("hosts", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cloudapi"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudApiGatewayApis() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudApigatewayApisRead,
Schema: map[string]*schema.Schema{
"group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"api_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Deprecated: "Field 'api_id' has been deprecated from provider version 1.52.2. New field 'ids' replaces it.",
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.ValidateRegexp,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"apis": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"group_id": {
Type: schema.TypeString,
Computed: true,
},
"group_name": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudApigatewayApisRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cloudapi.CreateDescribeApisRequest()
request.RegionId = client.RegionId
if groupId, ok := d.GetOk("group_id"); ok {
request.GroupId = groupId.(string)
}
if apiId, ok := d.GetOk("api_id"); ok {
request.ApiId = apiId.(string)
}
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var allapis []cloudapi.ApiSummary
for {
raw, err := client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.DescribeApis(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_api_gateway_apis", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cloudapi.DescribeApisResponse)
allapis = append(allapis, response.ApiSummarys.ApiSummary...)
if len(allapis) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
var filteredApisTemp []cloudapi.ApiSummary
// ids
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
for _, api := range allapis {
if v, ok := d.GetOk("name_regex"); ok && v.(string) != "" {
r := regexp.MustCompile(v.(string))
if !r.MatchString(api.ApiName) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[api.ApiId]; !ok {
continue
}
}
filteredApisTemp = append(filteredApisTemp, api)
}
return apiGatewayApisDescribeSummarys(d, filteredApisTemp, meta)
}
func apiGatewayApisDescribeSummarys(d *schema.ResourceData, apis []cloudapi.ApiSummary, meta interface{}) error {
var ids []string
var names []string
var s []map[string]interface{}
for _, api := range apis {
mapping := map[string]interface{}{
"id": api.ApiId,
"name": api.ApiName,
"region_id": api.RegionId,
"group_id": api.GroupId,
"group_name": api.GroupName,
"description": api.Description,
}
ids = append(ids, api.ApiId)
s = append(s, mapping)
names = append(names, api.ApiName)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("apis", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"strconv"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cloudapi"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudApiGatewayApps() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudApigatewayAppsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.ValidateRegexp,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"tags": tagsSchema(),
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"apps": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeInt,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"created_time": {
Type: schema.TypeString,
Computed: true,
},
"modified_time": {
Type: schema.TypeString,
Computed: true,
},
"app_code": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudApigatewayAppsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudApiService := CloudApiService{client}
request := cloudapi.CreateDescribeAppAttributesRequest()
request.RegionId = client.RegionId
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var apps []cloudapi.AppAttribute
for {
raw, err := client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.DescribeAppAttributes(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_api_gateway_apps", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cloudapi.DescribeAppAttributesResponse)
apps = append(apps, response.Apps.AppAttribute...)
if len(apps) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
var filteredAppsTemp []cloudapi.AppAttribute
nameRegex, ok := d.GetOk("name_regex")
var gatewayAppNameRegex *regexp.Regexp
if ok && nameRegex.(string) != "" {
r, err := regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
gatewayAppNameRegex = r
}
// ids
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
for _, app := range apps {
if gatewayAppNameRegex != nil && !gatewayAppNameRegex.MatchString(app.AppName) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[strconv.FormatInt(app.AppId, 10)]; !ok {
continue
}
}
if value, ok := d.GetOk("tags"); ok {
tags, err := cloudApiService.DescribeTags(strconv.FormatInt(app.AppId, 10), value.(map[string]interface{}), TagResourceApp)
if err != nil {
return WrapError(err)
}
if len(tags) < 1 {
continue
}
}
filteredAppsTemp = append(filteredAppsTemp, app)
}
return apigatewayAppsDecriptionAttributes(d, filteredAppsTemp, meta)
}
func apigatewayAppsDecriptionAttributes(d *schema.ResourceData, apps []cloudapi.AppAttribute, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var ids []string
var s []map[string]interface{}
var names []string
for _, app := range apps {
request := cloudapi.CreateDescribeAppSecurityRequest()
request.RegionId = client.RegionId
request.AppId = requests.NewInteger64(app.AppId)
raw, err := client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.DescribeAppSecurity(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_api_gateway_apps", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cloudapi.DescribeAppSecurityResponse)
mapping := map[string]interface{}{
"id": app.AppId,
"name": app.AppName,
"description": app.Description,
"created_time": app.CreatedTime,
"modified_time": app.ModifiedTime,
"app_code": response.AppCode,
}
ids = append(ids, strconv.FormatInt(app.AppId, 10))
s = append(s, mapping)
names = append(names, app.AppName)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("apps", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cloudapi"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudApiGatewayGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudApigatewayGroupsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.ValidateRegexp,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"sub_domain": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"created_time": {
Type: schema.TypeString,
Computed: true,
},
"modified_time": {
Type: schema.TypeString,
Computed: true,
},
"traffic_limit": {
Type: schema.TypeInt,
Computed: true,
},
"billing_status": {
Type: schema.TypeString,
Computed: true,
},
"illegal_status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudApigatewayGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cloudapi.CreateDescribeApiGroupsRequest()
request.RegionId = client.RegionId
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var allGroups []cloudapi.ApiGroupAttribute
for {
raw, err := client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.DescribeApiGroups(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_api_gateway_groups", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cloudapi.DescribeApiGroupsResponse)
allGroups = append(allGroups, response.ApiGroupAttributes.ApiGroupAttribute...)
if len(allGroups) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
var filteredGroups []cloudapi.ApiGroupAttribute
var gatewayGroupNameRegex *regexp.Regexp
if nameRegex, ok := d.GetOk("name_regex"); ok && nameRegex.(string) != "" {
r, err := regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
gatewayGroupNameRegex = r
}
// ids
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
for _, group := range allGroups {
if gatewayGroupNameRegex != nil && !gatewayGroupNameRegex.MatchString(group.GroupName) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[group.GroupId]; !ok {
continue
}
}
filteredGroups = append(filteredGroups, group)
}
return apigatewayGroupsDecriptionAttributes(d, filteredGroups, meta)
}
func apigatewayGroupsDecriptionAttributes(d *schema.ResourceData, groupsSetTypes []cloudapi.ApiGroupAttribute, meta interface{}) error {
var ids []string
var s []map[string]interface{}
var names []string
for _, group := range groupsSetTypes {
mapping := map[string]interface{}{
"id": group.GroupId,
"name": group.GroupName,
"region_id": group.RegionId,
"sub_domain": group.SubDomain,
"description": group.Description,
"created_time": group.CreatedTime,
"modified_time": group.ModifiedTime,
"traffic_limit": group.TrafficLimit,
"billing_status": group.BillingStatus,
"illegal_status": group.IllegalStatus,
}
ids = append(ids, group.GroupId)
s = append(s, mapping)
names = append(names, group.GroupName)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudApiGatewayService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudApigatewayServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudApigatewayServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("ApiGatewayServicHasNotBeenOpened")
d.Set("status", "")
return nil
}
conn, err := meta.(*connectivity.AliyunClient).NewTeaCommonClient(connectivity.OpenApiGatewayService)
if err != nil {
return WrapError(err)
}
response, err := conn.DoRequest(StringPointer("OpenApiGatewayService"), nil, StringPointer("POST"), StringPointer("2016-07-14"), StringPointer("AK"), nil, nil, &util.RuntimeOptions{})
addDebug("OpenApiGatewayService", response, nil)
if err != nil {
if IsExpectedErrors(err, []string{"ORDER.OPEND"}) {
d.SetId("ApiGatewayServicHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_api_gateway_service", "OpenApiGatewayService", AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprintf("%v", response["OrderId"]))
d.Set("status", "Opened")
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudArmsAlertContactGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudArmsAlertContactGroupsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"alert_contact_group_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"contact_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"contact_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"alert_contact_group_id": {
Type: schema.TypeString,
Computed: true,
},
"alert_contact_group_name": {
Type: schema.TypeString,
Computed: true,
},
"contact_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudArmsAlertContactGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "SearchAlertContactGroup"
request := make(map[string]interface{})
if v, ok := d.GetOk("alert_contact_group_name"); ok {
request["ContactGroupName"] = v
}
if v, ok := d.GetOk("contact_id"); ok {
request["ContactId"] = v
}
if v, ok := d.GetOk("contact_name"); ok {
request["ContactName"] = v
}
request["IsDetail"] = true
request["RegionId"] = client.RegionId
var objects []map[string]interface{}
var alertContactGroupNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
alertContactGroupNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewArmsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_arms_alert_contact_groups", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.ContactGroups", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.ContactGroups", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if alertContactGroupNameRegex != nil && !alertContactGroupNameRegex.MatchString(fmt.Sprint(item["ContactGroupName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ContactGroupId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["ContactGroupId"]),
"alert_contact_group_id": fmt.Sprint(object["ContactGroupId"]),
"alert_contact_group_name": object["ContactGroupName"],
"create_time": fmt.Sprint(object["CreateTime"]),
}
contactIdsItems := make([]string, 0)
if contacts, ok := object["Contacts"]; ok && contacts != nil {
for _, contactsItem := range contacts.([]interface{}) {
if contactId, ok := contactsItem.(map[string]interface{})["ContactId"]; ok && contactId != nil {
contactIdsItems = append(contactIdsItems, fmt.Sprint(contactId))
}
}
}
mapping["contact_ids"] = contactIdsItems
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["ContactGroupName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudArmsAlertContacts() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudArmsAlertContactsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"alert_contact_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"email": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"phone_num": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"contacts": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"alert_contact_id": {
Type: schema.TypeString,
Computed: true,
},
"alert_contact_name": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"ding_robot_webhook_url": {
Type: schema.TypeString,
Computed: true,
},
"email": {
Type: schema.TypeString,
Computed: true,
},
"phone_num": {
Type: schema.TypeString,
Computed: true,
},
"system_noc": {
Type: schema.TypeBool,
Computed: true,
},
"webhook": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudArmsAlertContactsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "SearchAlertContact"
request := make(map[string]interface{})
if v, ok := d.GetOk("alert_contact_name"); ok {
request["ContactName"] = v
}
if v, ok := d.GetOk("email"); ok {
request["Email"] = v
}
if v, ok := d.GetOk("phone_num"); ok {
request["Phone"] = v
}
request["RegionId"] = client.RegionId
request["PageSize"] = PageSizeLarge
request["CurrentPage"] = 1
var objects []map[string]interface{}
var alertContactNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
alertContactNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewArmsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_arms_alert_contacts", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.PageBean.Contacts", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.PageBean.Contacts", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if alertContactNameRegex != nil && !alertContactNameRegex.MatchString(fmt.Sprint(item["ContactName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ContactId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["CurrentPage"] = request["CurrentPage"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["ContactId"]),
"alert_contact_id": fmt.Sprint(object["ContactId"]),
"alert_contact_name": object["ContactName"],
"create_time": fmt.Sprint(object["CreateTime"]),
"ding_robot_webhook_url": object["DingRobot"],
"email": object["Email"],
"phone_num": object["Phone"],
"system_noc": object["SystemNoc"],
"webhook": object["Webhook"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["ContactName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("contacts", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudArmsDispatchRules() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudArmsDispatchRulesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"dispatch_rule_name": {
Type: schema.TypeString,
Optional: true,
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"dispatch_rule_id": {
Type: schema.TypeString,
Computed: true,
},
"group_rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"group_id": {
Type: schema.TypeInt,
Computed: true,
},
"group_wait_time": {
Type: schema.TypeInt,
Computed: true,
},
"group_interval": {
Type: schema.TypeInt,
Computed: true,
},
"grouping_fields": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"repeat_interval": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"dispatch_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"label_match_expression_grid": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"label_match_expression_groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"label_match_expressions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Computed: true,
},
"value": {
Type: schema.TypeString,
Computed: true,
},
"operator": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
},
},
"notify_rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"notify_objects": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"notify_object_id": {
Type: schema.TypeString,
Computed: true,
},
"notify_type": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"notify_channels": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"dispatch_rule_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudArmsDispatchRulesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListDispatchRule"
request := make(map[string]interface{})
if v, ok := d.GetOk("dispatch_rule_name"); ok {
request["Name"] = v
}
request["RegionId"] = client.RegionId
var objects []map[string]interface{}
var dispatchRuleNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
dispatchRuleNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewArmsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_arms_dispatch_rules", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.DispatchRules", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.DispatchRules", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if dispatchRuleNameRegex != nil && !dispatchRuleNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["RuleId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["RuleId"]),
"dispatch_rule_id": fmt.Sprint(object["RuleId"]),
"dispatch_rule_name": object["Name"],
"status": object["State"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["RuleId"])
armsService := ArmsService{client}
getResp, err := armsService.DescribeArmsDispatchRule(id)
if err != nil {
return WrapError(err)
}
if groupRulesList, ok := getResp["GroupRules"]; ok && groupRulesList != nil {
groupRulesMaps := make([]map[string]interface{}, 0)
for _, groupRulesListItem := range groupRulesList.([]interface{}) {
if groupRulesItemMap, ok := groupRulesListItem.(map[string]interface{}); ok {
groupRulesMap := make(map[string]interface{}, 0)
groupRulesMap["group_interval"] = groupRulesItemMap["GroupInterval"]
groupRulesMap["group_wait_time"] = groupRulesItemMap["GroupWaitTime"]
groupRulesMap["group_id"] = groupRulesItemMap["GroupId"]
groupRulesMap["grouping_fields"] = groupRulesItemMap["GroupingFields"]
groupRulesMap["repeat_interval"] = groupRulesItemMap["RepeatInterval"]
groupRulesMaps = append(groupRulesMaps, groupRulesMap)
}
}
mapping["group_rules"] = groupRulesMaps
}
if labelMatchExpressionGrid, ok := getResp["LabelMatchExpressionGrid"]; ok && labelMatchExpressionGrid != nil {
labelMatchExpressionGridMaps := make([]map[string]interface{}, 0)
labelMatchExpressionGridMap := make(map[string]interface{})
labelMatchExpressionGroupsMaps := make([]map[string]interface{}, 0)
if v, ok := labelMatchExpressionGrid.(map[string]interface{})["LabelMatchExpressionGroups"]; ok && v != nil {
for _, labelMatchExpressionGroups := range v.([]interface{}) {
labelMatchExpressionGroupsMap := make(map[string]interface{})
labelMatchExpressionsMaps := make([]map[string]interface{}, 0)
if v, ok := labelMatchExpressionGroups.(map[string]interface{})["LabelMatchExpressions"]; ok && v != nil {
for _, labelMatchExpressions := range v.([]interface{}) {
labelMatchExpressionsArg := labelMatchExpressions.(map[string]interface{})
labelMatchExpressionsMap := make(map[string]interface{}, 0)
labelMatchExpressionsMap["operator"] = labelMatchExpressionsArg["Operator"]
labelMatchExpressionsMap["key"] = labelMatchExpressionsArg["Key"]
labelMatchExpressionsMap["value"] = labelMatchExpressionsArg["Value"]
labelMatchExpressionsMaps = append(labelMatchExpressionsMaps, labelMatchExpressionsMap)
}
}
labelMatchExpressionGroupsMap["label_match_expressions"] = labelMatchExpressionsMaps
labelMatchExpressionGroupsMaps = append(labelMatchExpressionGroupsMaps, labelMatchExpressionGroupsMap)
}
}
labelMatchExpressionGridMap["label_match_expression_groups"] = labelMatchExpressionGroupsMaps
labelMatchExpressionGridMaps = append(labelMatchExpressionGridMaps, labelMatchExpressionGridMap)
mapping["label_match_expression_grid"] = labelMatchExpressionGridMaps
}
if notifyRulesList, ok := getResp["NotifyRules"]; ok && notifyRulesList != nil {
notifyRulesMaps := make([]map[string]interface{}, 0)
for _, notifyRulesListItem := range notifyRulesList.([]interface{}) {
if notifyRulesItemMap, ok := notifyRulesListItem.(map[string]interface{}); ok {
notifyRulesMap := make(map[string]interface{}, 0)
notifyObjectsMaps := make([]map[string]interface{}, 0)
for _, notifyObjects := range notifyRulesItemMap["NotifyObjects"].([]interface{}) {
notifyObjectsArg := notifyObjects.(map[string]interface{})
notifyObjectsMap := make(map[string]interface{}, 0)
notifyObjectsMap["notify_type"] = convertArmsDispatchRuleNotifyTypeResponse(notifyObjectsArg["NotifyType"])
notifyObjectsMap["notify_object_id"] = notifyObjectsArg["NotifyObjectId"]
notifyObjectsMap["name"] = notifyObjectsArg["Name"]
notifyObjectsMaps = append(notifyObjectsMaps, notifyObjectsMap)
}
notifyRulesMap["notify_objects"] = notifyObjectsMaps
notifyRulesMap["notify_channels"] = notifyRulesItemMap["NotifyChannels"]
notifyRulesMaps = append(notifyRulesMaps, notifyRulesMap)
}
}
mapping["notify_rules"] = notifyRulesMaps
}
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("rules", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudArmsPrometheusAlertRules() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudArmsPrometheusAlertRulesRead,
Schema: map[string]*schema.Schema{
"cluster_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"match_expressions": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IntInSlice([]int{0, 1}),
},
"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"annotations": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Computed: true,
},
"value": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"cluster_id": {
Type: schema.TypeString,
Computed: true,
},
"dispatch_rule_id": {
Type: schema.TypeString,
Computed: true,
},
"duration": {
Type: schema.TypeString,
Computed: true,
},
"expression": {
Type: schema.TypeString,
Computed: true,
},
"labels": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Computed: true,
},
"value": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"message": {
Type: schema.TypeString,
Computed: true,
},
"notify_type": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"prometheus_alert_rule_id": {
Type: schema.TypeString,
Computed: true,
},
"prometheus_alert_rule_name": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeInt,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudArmsPrometheusAlertRulesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListPrometheusAlertRules"
request := make(map[string]interface{})
request["ClusterId"] = d.Get("cluster_id")
if v, ok := d.GetOk("match_expressions"); ok {
request["MatchExpressions"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
if v, ok := d.GetOk("type"); ok {
request["Type"] = v
}
var objects []map[string]interface{}
var prometheusAlertRuleNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
prometheusAlertRuleNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewArmsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_arms_prometheus_alert_rules", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.PrometheusAlertRules", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.PrometheusAlertRules", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if prometheusAlertRuleNameRegex != nil && !prometheusAlertRuleNameRegex.MatchString(fmt.Sprint(item["AlertName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ClusterId"], ":", item["AlertId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"cluster_id": object["ClusterId"],
"dispatch_rule_id": fmt.Sprint(object["DispatchRuleId"]),
"duration": object["Duration"],
"expression": object["Expression"],
"message": object["Message"],
"notify_type": object["NotifyType"],
"id": fmt.Sprint(object["ClusterId"], ":", object["AlertId"]),
"prometheus_alert_rule_id": fmt.Sprint(object["AlertId"]),
"prometheus_alert_rule_name": object["AlertName"],
"status": formatInt(object["Status"]),
"type": object["Type"],
}
if v, ok := object["Annotations"].([]interface{}); ok {
annotations := make([]map[string]interface{}, 0)
for _, val := range v {
item := val.(map[string]interface{})
temp := map[string]interface{}{
"name": item["Name"],
"value": item["Value"],
}
annotations = append(annotations, temp)
}
mapping["annotations"] = annotations
}
if v, ok := object["Labels"].([]interface{}); ok {
labels := make([]map[string]interface{}, 0)
for _, val := range v {
item := val.(map[string]interface{})
temp := map[string]interface{}{
"name": item["Name"],
"value": item["Value"],
}
labels = append(labels, temp)
}
mapping["labels"] = labels
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["AlertName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("rules", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudBastionhostHostAccounts() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudBastionhostHostAccountsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"host_account_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"host_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"protocol_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"RDP", "SSH"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"accounts": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"has_password": {
Type: schema.TypeBool,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"host_account_id": {
Type: schema.TypeString,
Computed: true,
},
"host_account_name": {
Type: schema.TypeString,
Computed: true,
},
"host_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"private_key_fingerprint": {
Type: schema.TypeString,
Computed: true,
},
"protocol_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudBastionhostHostAccountsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListHostAccounts"
request := make(map[string]interface{})
if v, ok := d.GetOk("host_account_name"); ok {
request["HostAccountName"] = v
}
request["HostId"] = d.Get("host_id")
request["InstanceId"] = d.Get("instance_id")
if v, ok := d.GetOk("protocol_name"); ok {
request["ProtocolName"] = v
}
request["RegionId"] = client.RegionId
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var hostAccountNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
hostAccountNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_bastionhost_host_accounts", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.HostAccounts", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.HostAccounts", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if hostAccountNameRegex != nil && !hostAccountNameRegex.MatchString(fmt.Sprint(item["HostAccountName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["HostAccountId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"has_password": object["HasPassword"],
"id": fmt.Sprint(object["HostAccountId"]),
"host_account_id": fmt.Sprint(object["HostAccountId"]),
"host_account_name": object["HostAccountName"],
"host_id": object["HostId"],
"instance_id": request["InstanceId"],
"private_key_fingerprint": object["PrivateKeyFingerprint"],
"protocol_name": object["ProtocolName"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["HostAccountName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("accounts", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudBastionhostHostGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudBastionhostHostGroupsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"host_group_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"comment": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"host_group_id": {
Type: schema.TypeString,
Computed: true,
},
"host_group_name": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudBastionhostHostGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListHostGroups"
request := make(map[string]interface{})
if v, ok := d.GetOk("host_group_name"); ok {
request["HostGroupName"] = v
}
request["InstanceId"] = d.Get("instance_id")
request["RegionId"] = client.RegionId
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var hostGroupNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
hostGroupNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_bastionhost_host_groups", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.HostGroups", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.HostGroups", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if hostGroupNameRegex != nil && !hostGroupNameRegex.MatchString(fmt.Sprint(item["HostGroupName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["HostGroupId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"comment": object["Comment"],
"id": fmt.Sprint(object["HostGroupId"]),
"host_group_id": fmt.Sprint(object["HostGroupId"]),
"host_group_name": object["HostGroupName"],
"instance_id": request["InstanceId"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["HostGroupName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudBastionhostHosts() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudBastionhostHostsRead,
Schema: map[string]*schema.Schema{
"host_address": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"host_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"os_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Linux", "Windows"}, false),
},
"source": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Ecs", "Local", "Rds"}, false),
},
"source_instance_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"source_instance_state": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"hosts": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"active_address_type": {
Type: schema.TypeString,
Computed: true,
},
"comment": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"host_id": {
Type: schema.TypeString,
Computed: true,
},
"host_name": {
Type: schema.TypeString,
Computed: true,
},
"host_private_address": {
Type: schema.TypeString,
Computed: true,
},
"host_public_address": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"os_type": {
Type: schema.TypeString,
Computed: true,
},
"protocols": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"host_finger_print": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeInt,
Computed: true,
},
"protocol_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"source": {
Type: schema.TypeString,
Computed: true,
},
"source_instance_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudBastionhostHostsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListHosts"
request := make(map[string]interface{})
if v, ok := d.GetOk("host_address"); ok {
request["HostAddress"] = v
}
if v, ok := d.GetOk("host_name"); ok {
request["HostName"] = v
}
request["InstanceId"] = d.Get("instance_id")
if v, ok := d.GetOk("os_type"); ok {
request["OSType"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("source"); ok {
request["Source"] = v
}
if v, ok := d.GetOk("source_instance_id"); ok {
request["SourceInstanceId"] = v
}
if v, ok := d.GetOk("source_instance_state"); ok {
request["SourceInstanceState"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var hostNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
hostNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_bastionhost_hosts", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Hosts", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Hosts", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if hostNameRegex != nil && !hostNameRegex.MatchString(fmt.Sprint(item["HostName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["HostId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"active_address_type": object["ActiveAddressType"],
"comment": object["Comment"],
"id": fmt.Sprint(object["HostId"]),
"host_id": fmt.Sprint(object["HostId"]),
"host_name": object["HostName"],
"host_private_address": object["HostPrivateAddress"],
"host_public_address": object["HostPublicAddress"],
"instance_id": request["InstanceId"],
"os_type": object["OSType"],
"source": object["Source"],
"source_instance_id": object["SourceInstanceId"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["HostName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("hosts", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/yundun_bastionhost"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudBastionhostInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudBastionhostInstancesRead,
Schema: map[string]*schema.Schema{
"description_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
},
"descriptions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"user_vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"private_domain": {
Type: schema.TypeString,
Computed: true,
},
"public_domain": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"instance_status": {
Type: schema.TypeString,
Computed: true,
},
"license_code": {
Type: schema.TypeString,
Computed: true,
},
"public_network_access": {
Type: schema.TypeBool,
Computed: true,
},
"security_group_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"tags": tagsSchema(),
},
},
},
"tags": tagsSchema(),
},
}
}
func dataSourceAlicloudBastionhostInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := yundun_bastionhost.CreateDescribeInstanceBastionhostRequest()
request.PageSize = requests.NewInteger(PageSizeLarge)
request.CurrentPage = requests.NewInteger(1)
var instances []yundun_bastionhost.Instance
// get name Regex
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("description_regex"); ok {
if r, err := regexp.Compile(v.(string)); err == nil {
nameRegex = r
}
}
if v, ok := d.GetOk("ids"); ok {
ids, _ := v.([]interface{})
var ids_str []string
for _, v_instance_id := range ids {
if v_instance_id == nil {
continue
}
ids_str = append(ids_str, v_instance_id.(string))
}
request.InstanceId = &ids_str
}
if v, ok := d.GetOk("tags"); ok {
var tags []yundun_bastionhost.DescribeInstanceBastionhostTag
for key, value := range v.(map[string]interface{}) {
tags = append(tags, yundun_bastionhost.DescribeInstanceBastionhostTag{
Key: key,
Value: value.(string),
})
}
request.Tag = &tags
}
for {
raw, err := client.WithBastionhostClient(func(bastionhostClient *yundun_bastionhost.Client) (interface{}, error) {
return bastionhostClient.DescribeInstanceBastionhost(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_bastionhost_instances", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*yundun_bastionhost.DescribeInstanceBastionhostResponse)
if len(response.Instances) < 1 {
break
}
for _, e := range response.Instances {
if nameRegex != nil && !nameRegex.MatchString(e.Description) {
continue
}
instances = append(instances, e)
}
if len(response.Instances) < PageSizeSmall {
break
}
currentPageNo := request.CurrentPage
if page, err := getNextpageNumber(currentPageNo); err != nil {
return WrapError(err)
} else {
request.CurrentPage = page
}
}
var instanceIds []string
for _, instance := range instances {
instanceIds = append(instanceIds, instance.InstanceId)
}
if len(instanceIds) < 1 {
return WrapError(extractBastionhostInstance(d, nil, nil))
}
specs := make([]map[string]interface{}, 0)
var tags []yundun_bastionhost.TagResources
BastionhostService := YundunBastionhostService{client}
for _, instanceId := range instanceIds {
object, err := BastionhostService.DescribeBastionhostInstance(instanceId)
if err != nil {
return WrapError(err)
}
specs = append(specs, object)
{
request := yundun_bastionhost.CreateListTagResourcesRequest()
request.RegionId = client.RegionId
request.ResourceType = strings.ToUpper(string(TagResourceInstance))
request.ResourceId = &[]string{instanceId}
raw, err := client.WithBastionhostClient(func(client *yundun_bastionhost.Client) (interface{}, error) {
return client.ListTagResources(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_yundun_bastionhost_tags ", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
res, _ := raw.(*yundun_bastionhost.ListTagResourcesResponse)
tags = append(tags, res.TagResources)
}
}
return WrapError(extractBastionhostInstance(d, specs, tags))
}
func extractBastionhostInstance(d *schema.ResourceData, specs []map[string]interface{}, tags []yundun_bastionhost.TagResources) error {
var instanceIds []string
var descriptions []string
var instances []map[string]interface{}
for i := 0; i < len(specs); i++ {
instanceMap := map[string]interface{}{
"id": specs[i]["InstanceId"],
"description": specs[i]["Description"],
"user_vswitch_id": specs[i]["VswitchId"],
"private_domain": specs[i]["IntranetEndpoint"],
"public_domain": specs[i]["InternetEndpoint"],
"instance_status": specs[i]["InstanceStatus"],
"license_code": specs[i]["LicenseCode"],
"public_network_access": specs[i]["PublicNetworkAccess"],
"security_group_ids": specs[i]["AuthorizedSecurityGroups"],
"tags": bastionhostTagsToMap(tags[i].TagResource),
}
instanceIds = append(instanceIds, fmt.Sprint(specs[i]["InstanceId"]))
descriptions = append(descriptions, fmt.Sprint(specs[i]["Description"]))
instances = append(instances, instanceMap)
}
d.SetId(dataResourceIdHash(instanceIds))
if err := d.Set("ids", instanceIds); err != nil {
return WrapError(err)
}
if err := d.Set("descriptions", descriptions); err != nil {
return WrapError(err)
}
if err := d.Set("instances", instances); err != nil {
return WrapError(err)
}
// storage locally
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), instances)
}
return nil
}
func bastionhostTagsToMap(tags []yundun_bastionhost.TagResource) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !bastionhostTagIgnored(t) {
result[t.TagKey] = t.TagValue
}
}
return result
}
func bastionhostTagIgnored(t yundun_bastionhost.TagResource) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, t.TagKey)
ok, _ := regexp.MatchString(v, t.TagKey)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific tag %s (val: %s), ignoring.\n", t.TagKey, t.TagValue)
return true
}
}
return false
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudBastionhostUserGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudBastionhostUserGroupsRead,
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"user_group_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"comment": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"user_group_id": {
Type: schema.TypeString,
Computed: true,
},
"user_group_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudBastionhostUserGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListUserGroups"
request := make(map[string]interface{})
request["InstanceId"] = d.Get("instance_id")
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("user_group_name"); ok {
request["UserGroupName"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var userGroupNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
userGroupNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_bastionhost_user_groups", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.UserGroups", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.UserGroups", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if userGroupNameRegex != nil && !userGroupNameRegex.MatchString(fmt.Sprint(item["UserGroupName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["UserGroupId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"comment": object["Comment"],
"instance_id": request["InstanceId"],
"id": fmt.Sprint(object["UserGroupId"]),
"user_group_id": fmt.Sprint(object["UserGroupId"]),
"user_group_name": object["UserGroupName"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["UserGroupName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudBastionhostUsers() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudBastionhostUsersRead,
Schema: map[string]*schema.Schema{
"display_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"mobile": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"source": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Local", "Ram"}, false),
},
"source_user_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Expired", "Frozen", "Normal"}, false),
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"user_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"users": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"comment": {
Type: schema.TypeString,
Computed: true,
},
"display_name": {
Type: schema.TypeString,
Computed: true,
},
"email": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"mobile": {
Type: schema.TypeString,
Computed: true,
},
"mobile_country_code": {
Type: schema.TypeString,
Computed: true,
},
"source": {
Type: schema.TypeString,
Computed: true,
},
"source_user_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"user_id": {
Type: schema.TypeString,
Computed: true,
},
"user_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudBastionhostUsersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListUsers"
request := make(map[string]interface{})
if v, ok := d.GetOk("display_name"); ok {
request["DisplayName"] = v
}
request["InstanceId"] = d.Get("instance_id")
if v, ok := d.GetOk("mobile"); ok {
request["Mobile"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("source"); ok {
request["Source"] = v
}
if v, ok := d.GetOk("source_user_id"); ok {
request["SourceUserId"] = v
}
if v, ok := d.GetOk("status"); ok {
request["UserState"] = v
}
if v, ok := d.GetOk("user_name"); ok {
request["UserName"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var userNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
userNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_bastionhost_users", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Users", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Users", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if userNameRegex != nil && !userNameRegex.MatchString(fmt.Sprint(item["UserName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["UserId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"comment": object["Comment"],
"display_name": object["DisplayName"],
"email": object["Email"],
"instance_id": request["InstanceId"],
"mobile": object["Mobile"],
"mobile_country_code": object["MobileCountryCode"],
"source": object["Source"],
"source_user_id": object["SourceUserId"],
"id": fmt.Sprint(object["UserId"]),
"user_id": fmt.Sprint(object["UserId"]),
"user_name": object["UserName"],
}
if object["UserState"] != nil {
for _, userState := range object["UserState"].([]interface{}) {
mapping["status"] = fmt.Sprint(userState)
}
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["UserName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("users", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudBrainIndustrialPidLoops() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudBrainIndustrialPidLoopsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"pid_loop_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"pid_project_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"0", "1"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"loops": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"pid_loop_configuration": {
Type: schema.TypeString,
Computed: true,
},
"pid_loop_dcs_type": {
Type: schema.TypeString,
Computed: true,
},
"pid_loop_desc": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"pid_loop_id": {
Type: schema.TypeString,
Computed: true,
},
"pid_loop_is_crucial": {
Type: schema.TypeBool,
Computed: true,
},
"pid_loop_name": {
Type: schema.TypeString,
Computed: true,
},
"pid_loop_type": {
Type: schema.TypeString,
Computed: true,
},
"pid_project_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudBrainIndustrialPidLoopsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListPidLoops"
request := make(map[string]interface{})
if v, ok := d.GetOk("pid_loop_name"); ok {
request["PidLoopName"] = v
}
request["PidProjectId"] = d.Get("pid_project_id")
request["PageSize"] = PageSizeLarge
request["CurrentPage"] = 1
var objects []map[string]interface{}
var pidLoopNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
pidLoopNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewAistudioClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_brain_industrial_pid_loops", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.PidLoopList", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.PidLoopList", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if pidLoopNameRegex != nil {
if !pidLoopNameRegex.MatchString(fmt.Sprint(item["PidLoopName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["PidLoopId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["ReleaseStatus"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["CurrentPage"] = request["CurrentPage"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"pid_loop_dcs_type": object["PidLoopDcsType"],
"id": fmt.Sprint(object["PidLoopId"]),
"pid_loop_id": fmt.Sprint(object["PidLoopId"]),
"pid_loop_name": object["PidLoopName"],
"pid_loop_type": object["PidLoopType"],
"status": object["ReleaseStatus"],
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["PidLoopId"]))
names = append(names, object["PidLoopName"])
s = append(s, mapping)
continue
}
brain_industrialService := Brain_industrialService{client}
id := fmt.Sprint(object["PidLoopId"])
getResp, err := brain_industrialService.DescribeBrainIndustrialPidLoop(id)
if err != nil {
return WrapError(err)
}
mapping["pid_loop_configuration"] = getResp["PidLoopConfiguration"]
mapping["pid_loop_desc"] = getResp["PidLoopDesc"]
mapping["pid_loop_is_crucial"] = getResp["PidLoopIsCrucial"]
mapping["pid_project_id"] = getResp["PidProjectId"]
ids = append(ids, fmt.Sprint(object["PidLoopId"]))
names = append(names, object["PidLoopName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("loops", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudBrainIndustrialPidOrganizations() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudBrainIndustrialPidOrganizationsRead,
Schema: map[string]*schema.Schema{
"parent_organization_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"organizations": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"parent_pid_organization_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"pid_organization_id": {
Type: schema.TypeString,
Computed: true,
},
"pid_organization_level": {
Type: schema.TypeInt,
Computed: true,
},
"pid_organization_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudBrainIndustrialPidOrganizationsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListPidOrganizations"
request := make(map[string]interface{})
if v, ok := d.GetOk("parent_organization_id"); ok {
request["ParentOrganizationId"] = v
}
var objects []map[string]interface{}
var pidOrganizationNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
pidOrganizationNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewAistudioClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_brain_industrial_pid_organizations", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.OrganizationList", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.OrganizationList", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if pidOrganizationNameRegex != nil {
if !pidOrganizationNameRegex.MatchString(fmt.Sprint(item["OrganizationName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["OrganizationId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"parent_pid_organization_id": object["ParentOrganizationId"],
"id": fmt.Sprint(object["OrganizationId"]),
"pid_organization_id": fmt.Sprint(object["OrganizationId"]),
"pid_organization_level": formatInt(object["OrganizationLevel"]),
"pid_organization_name": object["OrganizationName"],
}
ids = append(ids, fmt.Sprint(object["OrganizationId"]))
names = append(names, object["OrganizationName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("organizations", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudBrainIndustrialPidProjects() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudBrainIndustrialPidProjectsRead,
Schema: map[string]*schema.Schema{
"pid_organization_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"pid_project_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"projects": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"pid_organization_id": {
Type: schema.TypeString,
Computed: true,
},
"pid_project_desc": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"pid_project_id": {
Type: schema.TypeString,
Computed: true,
},
"pid_project_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudBrainIndustrialPidProjectsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListPidProjects"
request := make(map[string]interface{})
if v, ok := d.GetOk("pid_organization_id"); ok {
request["PidOrganisationId"] = v
}
if v, ok := d.GetOk("pid_project_name"); ok {
request["PidProjectName"] = v
}
request["PageSize"] = PageSizeLarge
request["CurrentPage"] = 1
var objects []map[string]interface{}
var pidProjectNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
pidProjectNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewAistudioClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_brain_industrial_pid_projects", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.PidProjectList", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.PidProjectList", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if pidProjectNameRegex != nil {
if !pidProjectNameRegex.MatchString(fmt.Sprint(item["PidProjectName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["PidProjectId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["CurrentPage"] = request["CurrentPage"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"pid_organization_id": object["PidOrganisationId"],
"pid_project_desc": object["PidProjectDesc"],
"id": fmt.Sprint(object["PidProjectId"]),
"pid_project_id": fmt.Sprint(object["PidProjectId"]),
"pid_project_name": object["PidProjectName"],
}
ids = append(ids, fmt.Sprint(object["PidProjectId"]))
names = append(names, object["PidProjectName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("projects", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudBrainIndustrialService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudBrainIndustrialServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudBrainIndustrialServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("BrainIndustrialServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
action := "OpenCloudPidService"
request := map[string]interface{}{}
conn, err := meta.(*connectivity.AliyunClient).NewTeaCommonClient(connectivity.OpenBrainIndustrialService)
if err != nil {
return WrapError(err)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"QPS Limit Exceeded"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
addDebug(action, response, nil)
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ORDER.OPEND"}) {
d.SetId("BrainIndustrialServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_brain_industrial_service", action, AlibabaCloudSdkGoERROR)
}
d.SetId("BrainIndustrialServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
package alicloud
import (
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudCallerIdentity() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCallerIdentityRead,
Schema: map[string]*schema.Schema{
"account_id": {
Type: schema.TypeString,
Computed: true,
},
"arn": {
Type: schema.TypeString,
Computed: true,
},
"identity_type": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudCallerIdentityRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
resp, err := client.GetCallerIdentity()
if err != nil {
return err
}
d.SetId(resp.PrincipalId)
if err := d.Set("account_id", resp.AccountId); err != nil {
return err
}
if err := d.Set("arn", resp.Arn); err != nil {
return err
}
if err := d.Set("identity_type", resp.IdentityType); err != nil {
return err
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudCassandraBackupPlans() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCassandraBackupPlansRead,
Schema: map[string]*schema.Schema{
"cluster_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"plans": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"active": {
Type: schema.TypeBool,
Computed: true,
},
"backup_period": {
Type: schema.TypeString,
Computed: true,
},
"backup_time": {
Type: schema.TypeString,
Computed: true,
},
"cluster_id": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"data_center_id": {
Type: schema.TypeString,
Computed: true,
},
"retention_period": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCassandraBackupPlansRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeBackupPlans"
request := make(map[string]interface{})
request["ClusterId"] = d.Get("cluster_id")
var objects []map[string]interface{}
var response map[string]interface{}
conn, err := client.NewCdsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cassandra_backup_plans", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.BackupPlans.BackupPlan", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.BackupPlans.BackupPlan", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
objects = append(objects, item)
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["ClusterId"], ":", object["DataCenterId"]),
"active": object["Active"],
"backup_period": object["BackupPeriod"],
"backup_time": object["BackupTime"],
"cluster_id": object["ClusterId"],
"create_time": object["CreatedTime"],
"data_center_id": object["DataCenterId"],
"retention_period": formatInt(object["RetentionPeriod"]),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("plans", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cassandra"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCassandraClusters() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCassandraClustersRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"tags": tagsSchema(),
"clusters": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"cluster_id": {
Type: schema.TypeString,
Computed: true,
},
"cluster_name": {
Type: schema.TypeString,
Computed: true,
},
"created_time": {
Type: schema.TypeString,
Computed: true,
},
"data_center_count": {
Type: schema.TypeInt,
Computed: true,
},
"expire_time": {
Type: schema.TypeString,
Computed: true,
},
"lock_mode": {
Type: schema.TypeString,
Computed: true,
},
"major_version": {
Type: schema.TypeString,
Computed: true,
},
"minor_version": {
Type: schema.TypeString,
Computed: true,
},
"pay_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
},
},
},
},
}
}
func dataSourceAlicloudCassandraClustersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cassandraService := CassandraService{client}
request := cassandra.CreateDescribeClustersRequest()
if v, ok := d.GetOk("cluster_name"); ok {
request.ClusterName = v.(string)
}
request.RegionId = client.RegionId
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var objects []cassandra.Cluster
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
nameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
if v, ok := d.GetOk("tags"); ok {
var reqTags []cassandra.DescribeClustersTag
for key, value := range v.(map[string]interface{}) {
reqTags = append(reqTags, cassandra.DescribeClustersTag{
Key: key,
Value: value.(string),
})
}
request.Tag = &reqTags
}
for {
raw, err := client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.DescribeClusters(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cassandra_clusters", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ := raw.(*cassandra.DescribeClustersResponse)
for _, item := range response.Clusters.Cluster {
if nameRegex != nil {
if !nameRegex.MatchString(item.ClusterName) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[item.ClusterId]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(response.Clusters.Cluster) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
ids := make([]string, len(objects))
names := make([]string, len(objects))
s := make([]map[string]interface{}, len(objects))
for i, object := range objects {
mapping := map[string]interface{}{
"id": object.ClusterId,
"cluster_id": object.ClusterId,
"cluster_name": object.ClusterName,
"created_time": object.CreatedTime,
"data_center_count": object.DataCenterCount,
"expire_time": object.ExpireTime,
"lock_mode": object.LockMode,
"major_version": object.MajorVersion,
"minor_version": object.MinorVersion,
"pay_type": object.PayType,
"status": object.Status,
"tags": cassandraService.tagsToMap(object.Tags.Tag),
}
ids[i] = object.ClusterId
names[i] = object.ClusterName
s[i] = mapping
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("clusters", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cassandra"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCassandraDataCenters() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCassandraDataCentersRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"cluster_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"centers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cluster_id": {
Type: schema.TypeString,
Computed: true,
},
"commodity_instance": {
Type: schema.TypeString,
Computed: true,
},
"created_time": {
Type: schema.TypeString,
Computed: true,
},
"data_center_id": {
Type: schema.TypeString,
Computed: true,
},
"data_center_name": {
Type: schema.TypeString,
Computed: true,
},
"disk_size": {
Type: schema.TypeInt,
Computed: true,
},
"disk_type": {
Type: schema.TypeString,
Computed: true,
},
"expire_time": {
Type: schema.TypeString,
Computed: true,
},
"instance_type": {
Type: schema.TypeString,
Computed: true,
},
"lock_mode": {
Type: schema.TypeString,
Computed: true,
},
"node_count": {
Type: schema.TypeInt,
Computed: true,
},
"pay_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCassandraDataCentersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cassandra.CreateDescribeDataCentersRequest()
request.RegionId = client.RegionId
request.ClusterId = d.Get("cluster_id").(string)
var objects []cassandra.DataCenter
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
nameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
raw, err := client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.DescribeDataCenters(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cassandra_data_centers", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ := raw.(*cassandra.DescribeDataCentersResponse)
for _, item := range response.DataCenters.DataCenter {
if nameRegex != nil {
if !nameRegex.MatchString(item.DataCenterName) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprintf("%v:%v", item.DataCenterId, item.ClusterId)]; !ok {
continue
}
}
if item.ClusterId == item.CommodityInstance {
continue
}
objects = append(objects, item)
}
ids := make([]string, len(objects))
names := make([]string, len(objects))
s := make([]map[string]interface{}, len(objects))
for i, object := range objects {
mapping := map[string]interface{}{
"cluster_id": object.ClusterId,
"commodity_instance": object.CommodityInstance,
"created_time": object.CreatedTime,
"data_center_id": object.DataCenterId,
"data_center_name": object.DataCenterName,
"disk_size": object.DiskSize,
"disk_type": object.DiskType,
"expire_time": object.ExpireTime,
"instance_type": object.InstanceType,
"lock_mode": object.LockMode,
"node_count": object.NodeCount,
"pay_type": object.PayType,
"status": object.Status,
"vpc_id": object.VpcId,
"vswitch_id": object.VswitchId,
"zone_id": object.ZoneId,
}
ids[i] = fmt.Sprintf("%v:%v", object.DataCenterId, object.ClusterId)
names[i] = object.DataCenterName
s[i] = mapping
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("centers", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"sort"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cassandra"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudCassandraZones() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudZonesCassandraRead,
Schema: map[string]*schema.Schema{
"multi": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"zones": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"multi_zone_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
},
}
}
func dataSourceAlicloudZonesCassandraRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
multi := false
if v, ok := d.GetOk("multi"); ok {
multi = v.(bool)
}
var zoneIds []string
request := cassandra.CreateDescribeRegionsRequest()
request.RegionId = client.RegionId
raw, err := client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.DescribeRegions(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cassandra_zones", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
regions, _ := raw.(*cassandra.DescribeRegionsResponse)
if len(regions.Regions.Region) <= 0 {
return WrapError(fmt.Errorf("[ERROR] There is no available region for Cassandra."))
}
for _, r := range regions.Regions.Region {
for _, zone := range r.Zones.Zone {
if multi && strings.Contains(zone.Id, MULTI_IZ_SYMBOL) && r.RegionId == string(client.Region) {
zoneIds = append(zoneIds, zone.Id)
continue
}
if !multi && !strings.Contains(zone.Id, MULTI_IZ_SYMBOL) && r.RegionId == string(client.Region) {
zoneIds = append(zoneIds, zone.Id)
continue
}
}
}
if len(zoneIds) > 0 {
sort.Strings(zoneIds)
}
var s []map[string]interface{}
if !multi {
for _, zoneId := range zoneIds {
mapping := map[string]interface{}{"id": zoneId}
s = append(s, mapping)
}
} else {
for _, zoneId := range zoneIds {
mapping := map[string]interface{}{
"id": zoneId,
"multi_zone_ids": splitMultiZoneId(zoneId),
}
s = append(s, mapping)
}
}
d.SetId(dataResourceIdHash(zoneIds))
if err := d.Set("zones", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", zoneIds); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudCddcDedicatedHostAccounts() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCddcDedicatedHostAccountsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"dedicated_host_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"page_number": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"page_size": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"accounts": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"account_name": {
Type: schema.TypeString,
Computed: true,
},
"dedicated_host_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCddcDedicatedHostAccountsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDedicatedHosts"
request := make(map[string]interface{})
if v, ok := d.GetOk("dedicated_host_id"); ok {
request["DedicatedHostId"] = v
}
if v, ok := d.GetOk("page_number"); ok {
request["PageNumbers"] = v
} else {
request["PageNumbers"] = 1
}
if v, ok := d.GetOk("page_size"); ok {
request["PageSize"] = v
} else {
request["PageSize"] = PageSizeMedium
}
request["RegionId"] = client.RegionId
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var accountNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
accountNameRegex = r
}
var response map[string]interface{}
conn, err := client.NewCddcClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cddc_dedicated_host_accounts", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.DedicatedHosts.DedicatedHosts", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.DedicatedHosts.DedicatedHosts", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if accountNameRegex != nil && !accountNameRegex.MatchString(fmt.Sprint(item["AccountName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DedicatedHostId"], ":", item["AccountName"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["DedicatedHostId"], ":", object["AccountName"]),
"account_name": fmt.Sprint(object["AccountName"]),
"dedicated_host_id": object["DedicatedHostId"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["AccountName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("accounts", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudCddcDedicatedHostGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCddcDedicatedHostGroupsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"engine": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"allocation_policy": {
Type: schema.TypeString,
Computed: true,
},
"bastion_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"cpu_allocate_ration": {
Type: schema.TypeFloat,
Computed: true,
},
"cpu_allocated_amount": {
Type: schema.TypeFloat,
Computed: true,
},
"cpu_allocation_ratio": {
Type: schema.TypeInt,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"dedicated_host_count_group_by_host_type": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"place_holder": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"dedicated_host_group_desc": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"dedicated_host_group_id": {
Type: schema.TypeString,
Computed: true,
},
"deploy_type": {
Type: schema.TypeString,
Computed: true,
},
"disk_allocate_ration": {
Type: schema.TypeFloat,
Computed: true,
},
"disk_allocated_amount": {
Type: schema.TypeFloat,
Computed: true,
},
"disk_allocation_ratio": {
Type: schema.TypeInt,
Computed: true,
},
"disk_used_amount": {
Type: schema.TypeFloat,
Computed: true,
},
"disk_utility": {
Type: schema.TypeFloat,
Computed: true,
},
"engine": {
Type: schema.TypeString,
Computed: true,
},
"host_number": {
Type: schema.TypeInt,
Computed: true,
},
"host_replace_policy": {
Type: schema.TypeString,
Computed: true,
},
"instance_number": {
Type: schema.TypeInt,
Computed: true,
},
"mem_allocate_ration": {
Type: schema.TypeFloat,
Computed: true,
},
"mem_allocated_amount": {
Type: schema.TypeFloat,
Computed: true,
},
"mem_allocation_ratio": {
Type: schema.TypeInt,
Computed: true,
},
"mem_used_amount": {
Type: schema.TypeFloat,
Computed: true,
},
"mem_utility": {
Type: schema.TypeFloat,
Computed: true,
},
"text": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id_list": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"zone_id_list": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudCddcDedicatedHostGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDedicatedHostGroups"
request := make(map[string]interface{})
if v, ok := d.GetOk("engine"); ok {
request["Engine"] = v
}
request["RegionId"] = client.RegionId
var objects []map[string]interface{}
var userNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
userNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewCddcClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cddc_dedicated_host_groups", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.DedicatedHostGroups.DedicatedHostGroups", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.DedicatedHostGroups.DedicatedHostGroups", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if userNameRegex != nil && !userNameRegex.MatchString(fmt.Sprint(item["DedicatedHostGroupDesc"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DedicatedHostGroupId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"allocation_policy": object["AllocationPolicy"],
"bastion_instance_id": object["BastionInstanceId"],
"cpu_allocate_ration": object["CpuAllocateRation"],
"cpu_allocated_amount": object["CpuAllocatedAmount"],
"cpu_allocation_ratio": formatInt(object["CpuAllocationRatio"]),
"create_time": object["CreateTime"],
"dedicated_host_group_desc": object["DedicatedHostGroupDesc"],
"id": fmt.Sprint(object["DedicatedHostGroupId"]),
"dedicated_host_group_id": fmt.Sprint(object["DedicatedHostGroupId"]),
"deploy_type": object["DeployType"],
"disk_allocate_ration": object["DiskAllocateRation"],
"disk_allocated_amount": object["DiskAllocatedAmount"],
"disk_allocation_ratio": formatInt(object["DiskAllocationRatio"]),
"disk_used_amount": object["DiskUsedAmount"],
"disk_utility": object["DiskUtility"],
"engine": object["Engine"],
"host_number": formatInt(object["HostNumber"]),
"host_replace_policy": object["HostReplacePolicy"],
"instance_number": formatInt(object["InstanceNumber"]),
"mem_allocate_ration": object["MemAllocateRation"],
"mem_allocated_amount": object["MemAllocatedAmount"],
"mem_allocation_ratio": formatInt(object["MemAllocationRatio"]),
"mem_used_amount": object["MemUsedAmount"],
"mem_utility": object["MemUtility"],
"text": object["Text"],
"vpc_id": object["VPCId"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["DedicatedHostGroupDesc"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCddcDedicatedHosts() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCddcDedicatedHostsRead,
Schema: map[string]*schema.Schema{
"allocation_status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Allocatable", "Suspended"}, false),
},
"dedicated_host_group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"host_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"dhg_local_ssd", "dhg_cloud_ssd"}, false),
},
"order_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"0", "1", "2", "3", "4", "5", "6", "7"}, false),
},
"tags": tagsSchema(),
"zone_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"hosts": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"bastion_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"cpu_allocation_ratio": {
Type: schema.TypeString,
Computed: true,
},
"cpu_used": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"dedicated_host_group_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"dedicated_host_id": {
Type: schema.TypeString,
Computed: true,
},
"disk_allocation_ratio": {
Type: schema.TypeString,
Computed: true,
},
"ecs_class_code": {
Type: schema.TypeString,
Computed: true,
},
"end_time": {
Type: schema.TypeString,
Computed: true,
},
"engine": {
Type: schema.TypeString,
Computed: true,
},
"expired_time": {
Type: schema.TypeString,
Computed: true,
},
"host_class": {
Type: schema.TypeString,
Computed: true,
},
"host_cpu": {
Type: schema.TypeString,
Computed: true,
},
"host_mem": {
Type: schema.TypeString,
Computed: true,
},
"host_name": {
Type: schema.TypeString,
Computed: true,
},
"host_storage": {
Type: schema.TypeString,
Computed: true,
},
"host_type": {
Type: schema.TypeString,
Computed: true,
},
"image_category": {
Type: schema.TypeString,
Computed: true,
},
"ip_address": {
Type: schema.TypeString,
Computed: true,
},
"mem_allocation_ratio": {
Type: schema.TypeString,
Computed: true,
},
"memory_used": {
Type: schema.TypeString,
Computed: true,
},
"open_permission": {
Type: schema.TypeString,
Computed: true,
},
"allocation_status": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"storage_used": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudCddcDedicatedHostsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDedicatedHosts"
request := make(map[string]interface{})
if v, ok := d.GetOk("allocation_status"); ok {
request["AllocationStatus"] = v
}
request["DedicatedHostGroupId"] = d.Get("dedicated_host_group_id")
if v, ok := d.GetOk("status"); ok {
request["HostStatus"] = v
}
if v, ok := d.GetOk("host_type"); ok {
request["HostType"] = v
}
if v, ok := d.GetOk("tags"); ok {
respJson, err := convertMaptoJsonString(v.(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request["Tags"] = respJson
}
if v, ok := d.GetOk("order_id"); ok {
request["OrderId"] = v
}
request["PageNumbers"] = 1
request["PageSize"] = PageSizeLarge
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("zone_id"); ok {
request["ZoneId"] = v
}
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewCddcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cddc_dedicated_hosts", action, AlibabaCloudSdkGoERROR)
}
if _, ok := response["DedicatedHosts"]; !ok {
break
}
resp, err := jsonpath.Get("$.DedicatedHosts.DedicatedHosts", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.DedicatedHosts.DedicatedHosts", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DedicatedHostGroupId"], ":", item["DedicatedHostId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"bastion_instance_id": object["BastionInstanceId"],
"cpu_allocation_ratio": object["CPUAllocationRatio"],
"cpu_used": object["CpuUsed"],
"create_time": object["CreatedTime"],
"dedicated_host_group_id": object["DedicatedHostGroupId"],
"id": fmt.Sprint(object["DedicatedHostGroupId"], ":", object["DedicatedHostId"]),
"dedicated_host_id": fmt.Sprint(object["DedicatedHostId"]),
"disk_allocation_ratio": object["DiskAllocationRatio"],
"ecs_class_code": object["EcsClassCode"],
"end_time": object["EndTime"],
"engine": object["Engine"],
"host_class": object["HostClass"],
"host_cpu": object["HostCPU"],
"host_mem": object["HostMem"],
"host_name": object["HostName"],
"host_storage": object["HostStorage"],
"host_type": object["HostType"],
"image_category": object["ImageCategory"],
"ip_address": object["IPAddress"],
"mem_allocation_ratio": object["MemAllocationRatio"],
"memory_used": object["MemoryUsed"],
"open_permission": object["OpenPermission"],
"allocation_status": convertCddcAllocationStatusResponse(object["AllocationStatus"].(string)),
"status": object["HostStatus"],
"storage_used": object["StorageUsed"],
"vswitch_id": object["VSwitchId"],
"vpc_id": object["VPCId"],
"zone_id": object["ZoneId"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["DedicatedHostGroupId"], ":", object["DedicatedHostId"])
cddcService := CddcService{client}
getResp, err := cddcService.DescribeCddcDedicatedHost(id)
if err != nil {
return WrapError(err)
}
mapping["expired_time"] = getResp["ExpiredTime"]
getResp1, err := cddcService.ListTagResources(id, "DEDICATEDHOST")
if err != nil {
return WrapError(err)
}
mapping["tags"] = tagsToMap(getResp1)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("hosts", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"strconv"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudCddcHostEcsLevelInfos() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCddcHostEcsLevelInfosRead,
Schema: map[string]*schema.Schema{
"db_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"mysql", "mssql", "pgsql", "redis"}, false),
},
"zone_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"storage_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"local_ssd", "cloud_essd", "cloud_essd2", "cloud_essd3"}, false),
},
"image_category": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"WindowsWithMssqlEntAlwaysonLicense", "WindowsWithMssqlStdLicense", "WindowsWithMssqlEntLicense", "WindowsWithMssqlWebLicense", "AliLinux"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"infos": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"res_class_code": {
Type: schema.TypeString,
Computed: true,
},
"ecs_class_code": {
Type: schema.TypeString,
Computed: true,
},
"ecs_class": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCddcHostEcsLevelInfosRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeHostEcsLevelInfo"
request := make(map[string]interface{})
request["DbType"] = d.Get("db_type")
request["RegionId"] = client.RegionId
request["ZoneId"] = d.Get("zone_id")
request["StorageType"] = d.Get("storage_type")
if v, ok := d.GetOk("image_category"); ok {
request["ImageCategory"] = v
}
var objects []map[string]interface{}
var response map[string]interface{}
conn, err := client.NewCddcClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cddc_host_ecs_level_infos", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.HostEcsLevelInfos", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.HostEcsLevelInfos", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
objects = append(objects, item)
}
s := make([]map[string]interface{}, 0)
for _, object := range objects {
for _, item := range object["Items"].([]interface{}) {
itemArr := item.(map[string]interface{})
mapping := map[string]interface{}{
"description": itemArr["Description"],
"res_class_code": itemArr["RdsClassCode"],
"ecs_class_code": itemArr["EcsClassCode"],
"ecs_class": itemArr["EcsClass"],
}
s = append(s, mapping)
}
}
d.SetId(strconv.FormatInt(time.Now().Unix(), 16))
if err := d.Set("infos", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"strings"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudCddcZones() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCddcZonesRead,
Schema: map[string]*schema.Schema{
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"zones": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCddcZonesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ids := make([]string, 0)
action := "DescribeRegions"
request := make(map[string]interface{})
var objects []map[string]interface{}
var response map[string]interface{}
conn, err := client.NewCddcClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cddc_zones", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Regions.RDSRegion", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Regions.RDSRegion", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if client.RegionId != item["RegionId"].(string) {
continue
}
if strings.Contains(strings.ToLower(item["ZoneId"].(string)), strings.ToLower("MAZ")) {
continue
}
objects = append(objects, item)
}
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"region_id": object["RegionId"],
"zone_id": object["ZoneId"],
"id": fmt.Sprint(object["ZoneId"]),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("zones", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudCdnIpInfo() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCdnIpInfoRead,
Schema: map[string]*schema.Schema{
"ip": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"cdn_ip": {
Type: schema.TypeString,
Computed: true,
},
"isp": {
Type: schema.TypeString,
Computed: true,
},
"isp_ename": {
Type: schema.TypeString,
Computed: true,
},
"region": {
Type: schema.TypeString,
Computed: true,
},
"region_ename": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudCdnIpInfoRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeIpInfo"
request := make(map[string]interface{})
id := ""
if v, ok := d.GetOk("ip"); ok {
request["IP"] = v.(string)
id = v.(string)
}
var response map[string]interface{}
conn, err := client.NewCdnClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2018-05-10"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cdn_ip_info", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "", response)
}
object := resp.(map[string]interface{})
d.SetId(id)
d.Set("cdn_ip", object["CdnIp"])
d.Set("isp", object["ISP"])
d.Set("isp_ename", object["IspEname"])
d.Set("region", object["Region"])
d.Set("region_ename", object["RegionEname"])
d.Set("ip", id)
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCdnRealTimeLogDeliveries() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCdnRealTimeLogDeliveriesRead,
Schema: map[string]*schema.Schema{
"domain": {
Type: schema.TypeString,
Required: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"offline", "online"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"deliveries": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"domain": {
Type: schema.TypeString,
Computed: true,
},
"logstore": {
Type: schema.TypeString,
Computed: true,
},
"project": {
Type: schema.TypeString,
Computed: true,
},
"sls_region": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCdnRealTimeLogDeliveriesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDomainRealtimeLogDelivery"
request := map[string]interface{}{}
if v, ok := d.GetOk("domain"); ok {
request["Domain"] = v
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewCdnClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2018-05-10"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cdn_real_time_log_deliveries", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$", response)
}
s := make([]map[string]interface{}, 0)
if object, ok := resp.(map[string]interface{}); ok {
if statusOk && status.(string) != "" && status.(string) == object["Status"].(string) {
mapping := map[string]interface{}{
"id": fmt.Sprint(request["Domain"]),
"domain": fmt.Sprint(request["Domain"]),
"logstore": object["Logstore"],
"project": object["Project"],
"sls_region": object["Region"],
"status": object["Status"],
}
s = append(s, mapping)
}
}
d.SetId(fmt.Sprint(request["Domain"]))
if err := d.Set("deliveries", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCdnService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCdnServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"internet_charge_type": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"PayByTraffic", "PayByBandwidth"}, false),
Optional: true,
Default: "PayByTraffic",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"opening_time": {
Type: schema.TypeString,
Computed: true,
},
"changing_charge_type": {
Type: schema.TypeString,
Computed: true,
},
"changing_affect_time": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudCdnServiceRead(d *schema.ResourceData, meta interface{}) error {
opened := false
enable := ""
if v, ok := d.GetOk("enable"); ok {
enable = v.(string)
}
conn, err := meta.(*connectivity.AliyunClient).NewTeaCommonClient(connectivity.OpenCdnService)
if err != nil {
return WrapError(err)
}
response, err := conn.DoRequest(StringPointer("DescribeCdnService"), nil, StringPointer("POST"), StringPointer("2018-05-10"), StringPointer("AK"), nil, nil, &util.RuntimeOptions{})
addDebug("DescribeCdnService", response, nil)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cdn_service", "DescribeCdnService", AlibabaCloudSdkGoERROR)
}
if response["OpeningTime"] != nil && response["OpeningTime"].(string) != "" {
opened = true
}
if enable == "On" {
chargeType := ""
if v, ok := d.GetOk("internet_charge_type"); ok {
chargeType = v.(string)
}
if chargeType == "" {
return WrapError(fmt.Errorf("Field 'internet_charge_type' is required when 'enable' is 'On'."))
}
requestBody := map[string]interface{}{"InternetChargeType": chargeType}
if opened && chargeType != response["ChangingChargeType"].(string) {
resp, err := conn.DoRequest(StringPointer("ModifyCdnService"), nil, StringPointer("POST"), StringPointer("2018-05-10"), StringPointer("AK"), nil, requestBody, &util.RuntimeOptions{})
addDebug("ModifyCdnService", resp, nil)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cdn_service", "ModifyCdnService", AlibabaCloudSdkGoERROR)
}
}
if !opened {
resp, err := conn.DoRequest(StringPointer("OpenCdnService"), nil, StringPointer("POST"), StringPointer("2018-05-10"), StringPointer("AK"), nil, requestBody, &util.RuntimeOptions{})
addDebug("OpenCdnService", resp, nil)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cdn_service", "OpenCdnService", AlibabaCloudSdkGoERROR)
}
}
response, err = conn.DoRequest(StringPointer("DescribeCdnService"), nil, StringPointer("POST"), StringPointer("2018-05-10"), StringPointer("AK"), nil, nil, &util.RuntimeOptions{})
addDebug("DescribeCdnService", response, nil)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cdn_service", "DescribeCdnService", AlibabaCloudSdkGoERROR)
}
}
if opened {
d.SetId("CdnServiceHasBeenOpened")
d.Set("status", "Opened")
} else {
d.SetId("CdnServiceHasNotBeenOpened")
d.Set("status", "")
}
d.Set("internet_charge_type", response["InternetChargeType"])
d.Set("opening_time", response["OpeningTime"])
d.Set("changing_charge_type", response["ChangingChargeType"])
d.Set("changing_affect_time", response["ChangingAffectTime"])
return nil
}
package alicloud
import (
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cbn"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudCenBandwidthLimits() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCenBandwidthLimitsRead,
Schema: map[string]*schema.Schema{
"instance_ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"limits": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"local_region_id": {
Type: schema.TypeString,
Computed: true,
},
"opposite_region_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"bandwidth_limit": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCenBandwidthLimitsRead(d *schema.ResourceData, meta interface{}) error {
var allCenBwLimits []cbn.CenInterRegionBandwidthLimit
instanceIds := make([]string, 0)
if v, ok := d.GetOk("instance_ids"); ok {
for _, vv := range v.([]interface{}) {
instanceIds = append(instanceIds, Trim(vv.(string)))
}
} else {
instanceIds = append(instanceIds, "")
}
for _, instanceId := range instanceIds {
tmpAllCenBwLimits, err := getCenBandwidthLimits(instanceId, meta)
if err != nil {
return WrapError(err)
}
allCenBwLimits = append(allCenBwLimits, tmpAllCenBwLimits...)
}
return cenInterRegionBandwidthLimitsAttributes(d, allCenBwLimits)
}
func getCenBandwidthLimits(instanceId string, meta interface{}) ([]cbn.CenInterRegionBandwidthLimit, error) {
client := meta.(*connectivity.AliyunClient)
request := cbn.CreateDescribeCenInterRegionBandwidthLimitsRequest()
request.RegionId = client.RegionId
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
if instanceId != "" {
request.CenId = instanceId
}
var allCenBwLimits []cbn.CenInterRegionBandwidthLimit
deadline := time.Now().Add(10 * time.Minute)
for {
raw, err := client.WithCenClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DescribeCenInterRegionBandwidthLimits(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"Throttling.User"}) {
if time.Now().After(deadline) {
return nil, WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cen_bandwidth_limits", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
time.Sleep(10 * time.Second)
continue
}
return allCenBwLimits, WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cen_bandwidth_limits", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cbn.DescribeCenInterRegionBandwidthLimitsResponse)
if len(response.CenInterRegionBandwidthLimits.CenInterRegionBandwidthLimit) < 1 {
break
}
allCenBwLimits = append(allCenBwLimits, response.CenInterRegionBandwidthLimits.CenInterRegionBandwidthLimit...)
if len(response.CenInterRegionBandwidthLimits.CenInterRegionBandwidthLimit) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return allCenBwLimits, WrapError(err)
}
request.PageNumber = page
}
return allCenBwLimits, nil
}
func cenInterRegionBandwidthLimitsAttributes(d *schema.ResourceData, allCenBwLimits []cbn.CenInterRegionBandwidthLimit) error {
var ids []string
var s []map[string]interface{}
for _, cenBwLimit := range allCenBwLimits {
mapping := map[string]interface{}{
"instance_id": cenBwLimit.CenId,
"local_region_id": cenBwLimit.LocalRegionId,
"opposite_region_id": cenBwLimit.OppositeRegionId,
"status": cenBwLimit.Status,
"bandwidth_limit": cenBwLimit.BandwidthLimit,
}
id := cenBwLimit.CenId + COLON_SEPARATED + cenBwLimit.LocalRegionId + COLON_SEPARATED + cenBwLimit.OppositeRegionId
ids = append(ids, id)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("limits", s); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cbn"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCenBandwidthPackages() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCenBandwidthPackagesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"include_reservation_data": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Idle", "InUse"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"packages": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"bandwidth": {
Type: schema.TypeInt,
Computed: true,
},
"business_status": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"cen_bandwidth_package_id": {
Type: schema.TypeString,
Computed: true,
},
"cen_bandwidth_package_name": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"cen_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"expired_time": {
Type: schema.TypeString,
Computed: true,
},
"geographic_region_a_id": {
Type: schema.TypeString,
Computed: true,
},
"geographic_region_b_id": {
Type: schema.TypeString,
Computed: true,
},
"geographic_span_id": {
Type: schema.TypeString,
Computed: true,
},
"has_reservation_data": {
Type: schema.TypeString,
Computed: true,
},
"is_cross_border": {
Type: schema.TypeBool,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"bandwidth_package_charge_type": {
Type: schema.TypeString,
Computed: true,
},
"reservation_active_time": {
Type: schema.TypeString,
Computed: true,
},
"reservation_bandwidth": {
Type: schema.TypeString,
Computed: true,
},
"reservation_internet_charge_type": {
Type: schema.TypeString,
Computed: true,
},
"reservation_order_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCenBandwidthPackagesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cbn.CreateDescribeCenBandwidthPackagesRequest()
filters := make([]cbn.DescribeCenBandwidthPackagesFilter, 0)
if v, ok := d.GetOk("instance_id"); ok {
filter := cbn.DescribeCenBandwidthPackagesFilter{
Key: "CenId",
Value: &[]string{v.(string)},
}
filters = append(filters, filter)
request.Filter = &filters
}
if v, ok := d.GetOkExists("include_reservation_data"); ok {
request.IncludeReservationData = requests.NewBoolean(v.(bool))
}
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var objects []cbn.CenBandwidthPackage
var cenBandwidthPackageNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
cenBandwidthPackageNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response *cbn.DescribeCenBandwidthPackagesResponse
for {
wait := incrementalWait(3*time.Second, 5*time.Second)
err := resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DescribeCenBandwidthPackages(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"AliyunGoClientFailure", "ServiceUnavailable", "Throttling", "Throttling.User"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw)
response, _ = raw.(*cbn.DescribeCenBandwidthPackagesResponse)
return nil
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cen_bandwidth_packages", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
for _, item := range response.CenBandwidthPackages.CenBandwidthPackage {
if cenBandwidthPackageNameRegex != nil {
if !cenBandwidthPackageNameRegex.MatchString(item.Name) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[item.CenBandwidthPackageId]; !ok {
continue
}
}
if statusOk && status != "" && status != item.Status {
continue
}
objects = append(objects, item)
}
if len(response.CenBandwidthPackages.CenBandwidthPackage) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
ids := make([]string, 0)
names := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"bandwidth": object.Bandwidth,
"business_status": object.BusinessStatus,
"id": object.CenBandwidthPackageId,
"cen_bandwidth_package_id": object.CenBandwidthPackageId,
"cen_bandwidth_package_name": object.Name,
"name": object.Name,
"cen_ids": object.CenIds.CenId,
"description": object.Description,
"expired_time": object.ExpiredTime,
"geographic_region_a_id": convertGeographicRegionAIdResponse(object.GeographicRegionAId),
"geographic_region_b_id": convertGeographicRegionBIdResponse(object.GeographicRegionBId),
"geographic_span_id": object.GeographicSpanId,
"has_reservation_data": object.HasReservationData,
"is_cross_border": object.IsCrossBorder,
"payment_type": object.BandwidthPackageChargeType,
"bandwidth_package_charge_type": object.BandwidthPackageChargeType,
"reservation_active_time": object.ReservationActiveTime,
"reservation_bandwidth": object.ReservationBandwidth,
"reservation_internet_charge_type": object.ReservationInternetChargeType,
"reservation_order_type": object.ReservationOrderType,
"status": object.Status,
}
if len(object.CenIds.CenId) > 0 {
mapping["instance_id"] = object.CenIds.CenId[0]
}
ids = append(ids, object.CenBandwidthPackageId)
names = append(names, object.Name)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("packages", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cbn"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCenFlowlogs() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCenFlowlogsRead,
Schema: map[string]*schema.Schema{
"cen_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"log_store_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"project_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Inactive"}, false),
Default: "Active",
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"flowlogs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cen_id": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"flow_log_id": {
Type: schema.TypeString,
Computed: true,
},
"flow_log_name": {
Type: schema.TypeString,
Computed: true,
},
"log_store_name": {
Type: schema.TypeString,
Computed: true,
},
"project_name": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCenFlowlogsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cbn.CreateDescribeFlowlogsRequest()
if v, ok := d.GetOk("cen_id"); ok {
request.CenId = v.(string)
}
if v, ok := d.GetOk("description"); ok {
request.Description = v.(string)
}
if v, ok := d.GetOk("flow_log_name"); ok {
request.FlowLogName = v.(string)
}
if v, ok := d.GetOk("log_store_name"); ok {
request.LogStoreName = v.(string)
}
if v, ok := d.GetOk("project_name"); ok {
request.ProjectName = v.(string)
}
request.RegionId = client.RegionId
if v, ok := d.GetOk("status"); ok {
request.Status = v.(string)
}
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var objects []cbn.FlowLog
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
nameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
for {
request.ClientToken = buildClientToken(request.GetActionName())
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DescribeFlowlogs(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cen_flowlogs", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ := raw.(*cbn.DescribeFlowlogsResponse)
for _, item := range response.FlowLogs.FlowLog {
if nameRegex != nil {
if !nameRegex.MatchString(item.FlowLogName) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[item.FlowLogId]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(response.FlowLogs.FlowLog) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
ids := make([]string, len(objects))
names := make([]string, len(objects))
s := make([]map[string]interface{}, len(objects))
for i, object := range objects {
mapping := map[string]interface{}{
"cen_id": object.CenId,
"description": object.Description,
"id": object.FlowLogId,
"flow_log_id": object.FlowLogId,
"flow_log_name": object.FlowLogName,
"log_store_name": object.LogStoreName,
"project_name": object.ProjectName,
"status": object.Status,
}
ids[i] = object.FlowLogId
names[i] = object.FlowLogName
s[i] = mapping
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("flowlogs", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cbn"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCenInstanceAttachments() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCenInstanceAttachmentsRead,
Schema: map[string]*schema.Schema{
"child_instance_region_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"child_instance_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"VPC", "VBR", "CCN"}, false),
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Aetaching", "Attached", "Attaching"}, false),
},
"ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"attachments": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"child_instance_attach_time": {
Type: schema.TypeString,
Computed: true,
},
"child_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"child_instance_owner_id": {
Type: schema.TypeInt,
Computed: true,
},
"child_instance_region_id": {
Type: schema.TypeString,
Computed: true,
},
"child_instance_type": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCenInstanceAttachmentsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cbn.CreateDescribeCenAttachedChildInstancesRequest()
if v, ok := d.GetOk("child_instance_region_id"); ok {
request.ChildInstanceRegionId = v.(string)
}
if v, ok := d.GetOk("child_instance_type"); ok {
request.ChildInstanceType = v.(string)
}
request.CenId = d.Get("instance_id").(string)
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var objects []cbn.ChildInstance
status, statusOk := d.GetOk("status")
var response *cbn.DescribeCenAttachedChildInstancesResponse
for {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DescribeCenAttachedChildInstances(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cen_instance_attachments", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ = raw.(*cbn.DescribeCenAttachedChildInstancesResponse)
for _, item := range response.ChildInstances.ChildInstance {
if statusOk && status != "" && status != item.Status {
continue
}
objects = append(objects, item)
}
if len(response.ChildInstances.ChildInstance) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprintf("%v:%v:%v:%v", request.CenId, object.ChildInstanceId, object.ChildInstanceType, object.ChildInstanceRegionId),
"child_instance_attach_time": object.ChildInstanceAttachTime,
"child_instance_id": object.ChildInstanceId,
"child_instance_owner_id": object.ChildInstanceOwnerId,
"child_instance_region_id": object.ChildInstanceRegionId,
"child_instance_type": object.ChildInstanceType,
"instance_id": request.CenId,
"status": object.Status,
}
ids = append(ids, fmt.Sprintf("%v:%v:%v:%v", request.CenId, object.ChildInstanceId, object.ChildInstanceType, object.ChildInstanceRegionId))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("attachments", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cbn"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCenInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCenInstancesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Creating", "Deleting"}, false),
},
"tags": tagsSchema(),
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cen_bandwidth_package_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"cen_id": {
Type: schema.TypeString,
Computed: true,
},
"cen_instance_name": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"protection_level": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCenInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cbn.CreateDescribeCensRequest()
if v, ok := d.GetOk("tags"); ok {
tags := make([]cbn.DescribeCensTag, len(v.(map[string]interface{})))
i := 0
for key, value := range v.(map[string]interface{}) {
tags[i] = cbn.DescribeCensTag{
Key: key,
Value: value.(string),
}
i++
}
request.Tag = &tags
}
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var objects []cbn.Cen
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
nameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response *cbn.DescribeCensResponse
for {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DescribeCens(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cen_instances", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ = raw.(*cbn.DescribeCensResponse)
for _, item := range response.Cens.Cen {
if nameRegex != nil {
if !nameRegex.MatchString(item.Name) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[item.CenId]; !ok {
continue
}
}
if statusOk && status != "" && status != item.Status {
continue
}
objects = append(objects, item)
}
if len(response.Cens.Cen) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
ids := make([]string, 0)
names := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"cen_bandwidth_package_ids": object.CenBandwidthPackageIds.CenBandwidthPackageId,
"id": object.CenId,
"cen_id": object.CenId,
"cen_instance_name": object.Name,
"name": object.Name,
"description": object.Description,
"protection_level": object.ProtectionLevel,
"status": object.Status,
"create_time": object.CreationTime,
}
ids = append(ids, object.CenId)
tags := make(map[string]string)
for _, t := range object.Tags.Tag {
tags[t.Key] = t.Value
}
mapping["tags"] = tags
names = append(names, object.Name)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cbn"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCenPrivateZones() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCenPrivateZonesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"cen_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"host_region_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Creating", "Deleting"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"zones": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"access_region_id": {
Type: schema.TypeString,
Computed: true,
},
"cen_id": {
Type: schema.TypeString,
Computed: true,
},
"host_region_id": {
Type: schema.TypeString,
Computed: true,
},
"host_vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"private_zone_dns_servers": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCenPrivateZonesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cbn.CreateDescribeCenPrivateZoneRoutesRequest()
request.CenId = d.Get("cen_id").(string)
if v, ok := d.GetOk("host_region_id"); ok {
request.HostRegionId = v.(string)
}
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var objects []cbn.PrivateZoneInfo
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response *cbn.DescribeCenPrivateZoneRoutesResponse
for {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DescribeCenPrivateZoneRoutes(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cen_private_zones", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ = raw.(*cbn.DescribeCenPrivateZoneRoutesResponse)
for _, item := range response.PrivateZoneInfos.PrivateZoneInfo {
if len(idsMap) > 0 {
if _, ok := idsMap[item.AccessRegionId]; !ok {
continue
}
}
if statusOk && status != "" && status != item.Status {
continue
}
objects = append(objects, item)
}
if len(response.PrivateZoneInfos.PrivateZoneInfo) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
ids := make([]string, len(objects))
s := make([]map[string]interface{}, len(objects))
for i, object := range objects {
mapping := map[string]interface{}{
"access_region_id": object.AccessRegionId,
"cen_id": response.CenId,
"host_region_id": object.HostRegionId,
"host_vpc_id": object.HostVpcId,
"private_zone_dns_servers": response.PrivateZoneDnsServers,
"status": object.Status,
}
ids[i] = object.AccessRegionId
s[i] = mapping
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("zones", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cbn"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudCenRegionRouteEntries() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCenRegionDomainRouteEntriesRead,
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"region_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"entries": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cidr_block": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"next_hop_id": {
Type: schema.TypeString,
Computed: true,
},
"next_hop_type": {
Type: schema.TypeString,
Computed: true,
},
"next_hop_region_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCenRegionDomainRouteEntriesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cbn.CreateDescribeCenRegionDomainRouteEntriesRequest()
request.RegionId = client.RegionId
request.CenId = d.Get("instance_id").(string)
request.CenRegionId = d.Get("region_id").(string)
request.PageSize = requests.NewInteger(PageSizeLarge)
var allCenRouteEntries []cbn.CenRouteEntry
for pageNumber := 1; ; pageNumber++ {
raw, err := client.WithCenClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DescribeCenRegionDomainRouteEntries(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cen_region_route_entries", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cbn.DescribeCenRegionDomainRouteEntriesResponse)
if len(response.CenRouteEntries.CenRouteEntry) < 1 {
break
}
allCenRouteEntries = append(allCenRouteEntries, response.CenRouteEntries.CenRouteEntry...)
if len(response.CenRouteEntries.CenRouteEntry) < PageSizeLarge {
break
}
request.PageNumber = requests.NewInteger(pageNumber)
}
return cenRegionDomainRouteEntriesAttributes(d, allCenRouteEntries)
}
func cenRegionDomainRouteEntriesAttributes(d *schema.ResourceData, allCenRouteEntries []cbn.CenRouteEntry) error {
var s []map[string]interface{}
for _, cenRouteEntry := range allCenRouteEntries {
mapping := map[string]interface{}{
"cidr_block": cenRouteEntry.DestinationCidrBlock,
"type": cenRouteEntry.Type,
"next_hop_id": cenRouteEntry.NextHopInstanceId,
"next_hop_type": cenRouteEntry.NextHopType,
"next_hop_region_id": cenRouteEntry.NextHopRegionId,
}
s = append(s, mapping)
}
id := d.Get("instance_id").(string) + COLON_SEPARATED + d.Get("region_id").(string)
d.SetId(id)
if err := d.Set("entries", s); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cbn"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudCenRouteEntries() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCenPublishedRouteEntriesRead,
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"route_table_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"cidr_block": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"entries": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"route_table_id": {
Type: schema.TypeString,
Computed: true,
},
"cidr_block": {
Type: schema.TypeString,
Computed: true,
},
"next_hop_id": {
Type: schema.TypeString,
Computed: true,
},
"next_hop_type": {
Type: schema.TypeString,
Computed: true,
},
"route_type": {
Type: schema.TypeString,
Computed: true,
},
"operational_mode": {
Type: schema.TypeBool,
Computed: true,
},
"publish_status": {
Type: schema.TypeString,
Computed: true,
},
// Complex computed value
"conflicts": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cidr_block": {
Type: schema.TypeString,
Computed: true,
},
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudCenPublishedRouteEntriesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cenService := CenService{client}
request := cbn.CreateDescribePublishedRouteEntriesRequest()
request.RegionId = client.RegionId
request.CenId = d.Get("instance_id").(string)
request.ChildInstanceRouteTableId = d.Get("route_table_id").(string)
if v, ok := d.GetOk("cidr_block"); ok {
request.DestinationCidrBlock = v.(string)
}
childInstanceId, childInstanceType, err := cenService.CreateCenRouteEntryParas(request.ChildInstanceRouteTableId)
if err != nil {
return WrapError(err)
}
request.ChildInstanceId = childInstanceId
request.ChildInstanceType = childInstanceType
request.ChildInstanceRegionId = client.RegionId
request.PageSize = requests.NewInteger(PageSizeLarge)
var allPublishedRouteEntries []cbn.PublishedRouteEntry
for pageNumber := 1; ; pageNumber++ {
request.PageNumber = requests.NewInteger(pageNumber)
raw, err := client.WithCenClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DescribePublishedRouteEntries(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cen_route_entries", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cbn.DescribePublishedRouteEntriesResponse)
if len(response.PublishedRouteEntries.PublishedRouteEntry) < 1 {
break
}
allPublishedRouteEntries = append(allPublishedRouteEntries, response.PublishedRouteEntries.PublishedRouteEntry...)
if len(response.PublishedRouteEntries.PublishedRouteEntry) < PageSizeLarge {
break
}
}
return cenPublishedRouteEntriesAttributes(d, allPublishedRouteEntries)
}
func cenPublishedRouteEntriesAttributes(d *schema.ResourceData, allPublishedRouteEntries []cbn.PublishedRouteEntry) error {
var ids []string
var s []map[string]interface{}
for _, routeEntry := range allPublishedRouteEntries {
mapping := map[string]interface{}{
"route_table_id": routeEntry.ChildInstanceRouteTableId,
"cidr_block": routeEntry.DestinationCidrBlock,
"next_hop_type": routeEntry.NextHopType,
"next_hop_id": routeEntry.NextHopId,
"operational_mode": routeEntry.OperationalMode,
"publish_status": routeEntry.PublishStatus,
"route_type": routeEntry.RouteType,
// Complex types get their own functions
"conflicts": routeConflictsMappings(routeEntry.Conflicts.Conflict),
}
id := routeEntry.ChildInstanceRouteTableId + COLON_SEPARATED + routeEntry.DestinationCidrBlock
ids = append(ids, id)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("entries", s); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
// Returns a set of route conflicts mappings.
func routeConflictsMappings(m []cbn.Conflict) []map[string]interface{} {
var s []map[string]interface{}
for _, v := range m {
mapping := map[string]interface{}{
"cidr_block": v.DestinationCidrBlock,
"region_id": v.RegionId,
"instance_id": v.InstanceId,
"instance_type": v.InstanceType,
"status": v.Status,
}
s = append(s, mapping)
}
return s
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cbn"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCenRouteMaps() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCenRouteMapsRead,
Schema: map[string]*schema.Schema{
"cen_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"cen_region_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Creating", "Deleting"}, false),
},
"transmit_direction": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"RegionIn", "RegionOut"}, false),
},
"description_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"maps": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"as_path_match_mode": {
Type: schema.TypeString,
Computed: true,
},
"cen_id": {
Type: schema.TypeString,
Computed: true,
},
"cen_region_id": {
Type: schema.TypeString,
Computed: true,
},
"cidr_match_mode": {
Type: schema.TypeString,
Computed: true,
},
"community_match_mode": {
Type: schema.TypeString,
Computed: true,
},
"community_operate_mode": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"destination_child_instance_types": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"destination_cidr_blocks": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"destination_instance_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"destination_instance_ids_reverse_match": {
Type: schema.TypeBool,
Computed: true,
},
"destination_route_table_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"map_result": {
Type: schema.TypeString,
Computed: true,
},
"match_asns": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"match_community_set": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"next_priority": {
Type: schema.TypeInt,
Computed: true,
},
"operate_community_set": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"preference": {
Type: schema.TypeInt,
Computed: true,
},
"prepend_as_path": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"priority": {
Type: schema.TypeInt,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"route_map_id": {
Type: schema.TypeString,
Computed: true,
},
"route_types": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"source_child_instance_types": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"source_instance_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"source_instance_ids_reverse_match": {
Type: schema.TypeBool,
Computed: true,
},
"source_region_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"source_route_table_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"transmit_direction": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCenRouteMapsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cbn.CreateDescribeCenRouteMapsRequest()
request.CenId = d.Get("cen_id").(string)
if v, ok := d.GetOk("cen_region_id"); ok {
request.CenRegionId = v.(string)
}
if v, ok := d.GetOk("transmit_direction"); ok {
request.TransmitDirection = v.(string)
}
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var objects []cbn.RouteMap
var descriptionRegex *regexp.Regexp
if v, ok := d.GetOk("description_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
descriptionRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
for {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DescribeCenRouteMaps(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cen_route_maps", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ := raw.(*cbn.DescribeCenRouteMapsResponse)
for _, item := range response.RouteMaps.RouteMap {
if descriptionRegex != nil {
if !descriptionRegex.MatchString(item.Description) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[item.RouteMapId]; !ok {
continue
}
}
if statusOk && status != "" && status != item.Status {
continue
}
objects = append(objects, item)
}
if len(response.RouteMaps.RouteMap) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
ids := make([]string, len(objects))
s := make([]map[string]interface{}, len(objects))
for i, object := range objects {
mapping := map[string]interface{}{
"as_path_match_mode": object.AsPathMatchMode,
"cen_id": object.CenId,
"cen_region_id": object.CenRegionId,
"cidr_match_mode": object.CidrMatchMode,
"community_match_mode": object.CommunityMatchMode,
"community_operate_mode": object.CommunityOperateMode,
"description": object.Description,
"destination_child_instance_types": object.DestinationChildInstanceTypes.DestinationChildInstanceType,
"destination_cidr_blocks": object.DestinationCidrBlocks.DestinationCidrBlock,
"destination_instance_ids": object.DestinationInstanceIds.DestinationInstanceId,
"destination_instance_ids_reverse_match": object.DestinationInstanceIdsReverseMatch,
"destination_route_table_ids": object.DestinationRouteTableIds.DestinationRouteTableId,
"map_result": object.MapResult,
"match_asns": object.MatchAsns.MatchAsn,
"match_community_set": object.MatchCommunitySet.MatchCommunity,
"next_priority": object.NextPriority,
"operate_community_set": object.OperateCommunitySet.OperateCommunity,
"preference": object.Preference,
"prepend_as_path": object.PrependAsPath.AsPath,
"priority": object.Priority,
"id": object.RouteMapId,
"route_map_id": object.RouteMapId,
"route_types": object.RouteTypes.RouteType,
"source_child_instance_types": object.SourceChildInstanceTypes.SourceChildInstanceType,
"source_instance_ids": object.SourceInstanceIds.SourceInstanceId,
"source_instance_ids_reverse_match": object.SourceInstanceIdsReverseMatch,
"source_region_ids": object.SourceRegionIds.SourceRegionId,
"source_route_table_ids": object.SourceRouteTableIds.SourceRouteTableId,
"status": object.Status,
"transmit_direction": object.TransmitDirection,
}
ids[i] = object.RouteMapId
s[i] = mapping
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("maps", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cbn"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCenRouteServices() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCenRouteServicesRead,
Schema: map[string]*schema.Schema{
"access_region_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"cen_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"host": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"host_region_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"host_vpc_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Creating", "Deleting"}, false),
},
"ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"services": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"access_region_id": {
Type: schema.TypeString,
Computed: true,
},
"cen_id": {
Type: schema.TypeString,
Computed: true,
},
"cidrs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"host": {
Type: schema.TypeString,
Computed: true,
},
"host_region_id": {
Type: schema.TypeString,
Computed: true,
},
"host_vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"update_interval": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCenRouteServicesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cbn.CreateDescribeRouteServicesInCenRequest()
if v, ok := d.GetOk("access_region_id"); ok {
request.AccessRegionId = v.(string)
}
request.CenId = d.Get("cen_id").(string)
if v, ok := d.GetOk("host"); ok {
request.Host = v.(string)
}
if v, ok := d.GetOk("host_region_id"); ok {
request.HostRegionId = v.(string)
}
if v, ok := d.GetOk("host_vpc_id"); ok {
request.HostVpcId = v.(string)
}
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var objects []cbn.RouteServiceEntry
status, statusOk := d.GetOk("status")
var response *cbn.DescribeRouteServicesInCenResponse
for {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DescribeRouteServicesInCen(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cen_route_services", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ = raw.(*cbn.DescribeRouteServicesInCenResponse)
for _, item := range response.RouteServiceEntries.RouteServiceEntry {
if statusOk && status != "" && status != item.Status {
continue
}
objects = append(objects, item)
}
if len(response.RouteServiceEntries.RouteServiceEntry) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprintf("%v:%v:%v:%v", object.CenId, object.HostRegionId, object.Host, object.AccessRegionId),
"access_region_id": object.AccessRegionId,
"cen_id": object.CenId,
"cidrs": object.Cidrs.Cidr,
"description": object.Description,
"host": object.Host,
"host_region_id": object.HostRegionId,
"host_vpc_id": object.HostVpcId,
"status": object.Status,
"update_interval": object.UpdateInterval,
}
ids = append(ids, fmt.Sprintf("%v:%v:%v:%v", object.CenId, object.HostRegionId, object.Host, object.AccessRegionId))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("services", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCenTransitRouterPeerAttachments() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCenTransitRouterPeerAttachmentsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"cen_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Attached", "Attaching", "Detaching"}, false),
},
"transit_router_attachment_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"transit_router_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"attachments": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"auto_publish_route_enabled": {
Type: schema.TypeBool,
Computed: true,
},
"bandwidth": {
Type: schema.TypeInt,
Computed: true,
},
"cen_bandwidth_package_id": {
Type: schema.TypeString,
Computed: true,
},
"geographic_span_id": {
Type: schema.TypeString,
Computed: true,
},
"peer_transit_router_id": {
Type: schema.TypeString,
Computed: true,
},
"peer_transit_router_owner_id": {
Type: schema.TypeString,
Computed: true,
},
"peer_transit_router_region_id": {
Type: schema.TypeString,
Computed: true,
},
"resource_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_attachment_description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_attachment_id": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_attachment_name": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCenTransitRouterPeerAttachmentsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListTransitRouterPeerAttachments"
request := make(map[string]interface{})
request["CenId"] = d.Get("cen_id")
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("transit_router_id"); ok {
request["TransitRouterId"] = v
}
if v, ok := d.GetOk("transit_router_attachment_id"); ok {
request["TransitRouterAttachmentId"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var transitRouterPeerAttachmentNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
transitRouterPeerAttachmentNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cen_transit_router_peer_attachments", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.TransitRouterAttachments", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.TransitRouterAttachments", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if transitRouterPeerAttachmentNameRegex != nil {
if !transitRouterPeerAttachmentNameRegex.MatchString(fmt.Sprint(item["TransitRouterAttachmentName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["TransitRouterAttachmentId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"auto_publish_route_enabled": object["AutoPublishRouteEnabled"],
"bandwidth": formatInt(object["Bandwidth"]),
"cen_bandwidth_package_id": object["CenBandwidthPackageId"],
"geographic_span_id": object["GeographicSpanId"],
"peer_transit_router_id": object["PeerTransitRouterId"],
"peer_transit_router_owner_id": fmt.Sprint(object["PeerTransitRouterOwnerId"]),
"peer_transit_router_region_id": object["PeerTransitRouterRegionId"],
"resource_type": object["ResourceType"],
"status": object["Status"],
"transit_router_attachment_description": object["TransitRouterAttachmentDescription"],
"id": fmt.Sprint(object["TransitRouterAttachmentId"]),
"transit_router_attachment_id": fmt.Sprint(object["TransitRouterAttachmentId"]),
"transit_router_attachment_name": object["TransitRouterAttachmentName"],
"transit_router_id": object["TransitRouterId"],
}
ids = append(ids, fmt.Sprint(object["TransitRouterAttachmentId"]))
names = append(names, object["TransitRouterAttachmentName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("attachments", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCenTransitRouterRouteEntries() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCenTransitRouterRouteEntriesRead,
Schema: map[string]*schema.Schema{
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Creating", "Deleting", "Updating"}, false),
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"transit_router_route_entry_ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"transit_router_route_entry_names": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"transit_router_route_entry_status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Creating", "Deleting", "Updating"}, false),
},
"transit_router_route_table_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"entries": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"status": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_route_entry_description": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_route_entry_destination_cidr_block": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_route_entry_id": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_route_entry_name": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_route_entry_next_hop_id": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_route_entry_next_hop_type": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_route_entry_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCenTransitRouterRouteEntriesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListTransitRouterRouteEntries"
request := make(map[string]interface{})
if v, ok := d.GetOk("transit_router_route_entry_ids"); ok {
request["TransitRouterRouteEntryIds"] = convertListToJsonString(v.([]interface{}))
}
if v, ok := d.GetOk("transit_router_route_entry_names"); ok {
request["TransitRouterRouteEntryNames"] = convertListToJsonString(v.([]interface{}))
}
if v, ok := d.GetOk("transit_router_route_entry_status"); ok {
request["TransitRouterRouteEntryStatus"] = v
}
request["TransitRouterRouteTableId"] = d.Get("transit_router_route_table_id")
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var transitRouterRouteEntryNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
transitRouterRouteEntryNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cen_transit_router_route_entries", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.TransitRouterRouteEntries", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.TransitRouterRouteEntries", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if transitRouterRouteEntryNameRegex != nil {
if !transitRouterRouteEntryNameRegex.MatchString(fmt.Sprint(item["TransitRouterRouteEntryName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["TransitRouterRouteEntryId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["TransitRouterRouteEntryStatus"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"status": object["TransitRouterRouteEntryStatus"],
"transit_router_route_entry_description": object["TransitRouterRouteEntryDescription"],
"transit_router_route_entry_destination_cidr_block": object["TransitRouterRouteEntryDestinationCidrBlock"],
"id": fmt.Sprint(object["TransitRouterRouteEntryId"]),
"transit_router_route_entry_id": fmt.Sprint(object["TransitRouterRouteEntryId"]),
"transit_router_route_entry_name": object["TransitRouterRouteEntryName"],
"transit_router_route_entry_next_hop_id": object["TransitRouterRouteEntryNextHopId"],
"transit_router_route_entry_next_hop_type": object["TransitRouterRouteEntryNextHopType"],
"transit_router_route_entry_type": object["TransitRouterRouteEntryType"],
}
ids = append(ids, fmt.Sprint(object["TransitRouterRouteEntryId"]))
names = append(names, object["TransitRouterRouteEntryName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("entries", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCenTransitRouterRouteTableAssociations() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCenTransitRouterRouteTableAssociationsRead,
Schema: map[string]*schema.Schema{
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Creating", "Deleting"}, false),
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"transit_router_route_table_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"associations": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"resource_id": {
Type: schema.TypeString,
Computed: true,
},
"resource_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_attachment_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCenTransitRouterRouteTableAssociationsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListTransitRouterRouteTableAssociations"
request := make(map[string]interface{})
request["TransitRouterRouteTableId"] = d.Get("transit_router_route_table_id")
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cen_transit_router_route_table_associations", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.TransitRouterAssociations", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.TransitRouterAssociations", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["TransitRouterAttachmentId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"resource_id": object["ResourceId"],
"resource_type": object["ResourceType"],
"status": object["Status"],
"id": fmt.Sprint(object["TransitRouterAttachmentId"]),
"transit_router_attachment_id": fmt.Sprint(object["TransitRouterAttachmentId"]),
}
ids = append(ids, fmt.Sprint(object["TransitRouterAttachmentId"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("associations", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCenTransitRouterRouteTablePropagations() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCenTransitRouterRouteTablePropagationsRead,
Schema: map[string]*schema.Schema{
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Creating", "Deleting"}, false),
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"transit_router_route_table_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"propagations": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"resource_id": {
Type: schema.TypeString,
Computed: true,
},
"resource_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_attachment_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCenTransitRouterRouteTablePropagationsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListTransitRouterRouteTablePropagations"
request := make(map[string]interface{})
request["TransitRouterRouteTableId"] = d.Get("transit_router_route_table_id")
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cen_transit_router_route_table_propagations", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.TransitRouterPropagations", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.TransitRouterPropagations", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["TransitRouterAttachmentId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"resource_id": object["ResourceId"],
"resource_type": object["ResourceType"],
"status": object["Status"],
"id": fmt.Sprint(object["TransitRouterAttachmentId"]),
"transit_router_attachment_id": fmt.Sprint(object["TransitRouterAttachmentId"]),
}
ids = append(ids, fmt.Sprint(object["TransitRouterAttachmentId"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("propagations", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCenTransitRouterRouteTables() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCenTransitRouterRouteTablesRead,
Schema: map[string]*schema.Schema{
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Creating", "Deleting", "Updating"}, false),
},
"transit_router_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"transit_router_route_table_ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"transit_router_route_table_names": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"transit_router_route_table_status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Creating", "Deleting", "Updating"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"tables": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"status": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_route_table_description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_route_table_id": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_route_table_name": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_route_table_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCenTransitRouterRouteTablesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListTransitRouterRouteTables"
request := make(map[string]interface{})
request["TransitRouterId"] = d.Get("transit_router_id")
if v, ok := d.GetOk("transit_router_route_table_ids"); ok {
request["TransitRouterRouteTableIds"] = convertListToJsonString(v.([]interface{}))
}
if v, ok := d.GetOk("transit_router_route_table_names"); ok {
request["TransitRouterRouteTableNames"] = convertListToJsonString(v.([]interface{}))
}
if v, ok := d.GetOk("transit_router_route_table_status"); ok {
request["TransitRouterRouteTableStatus"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var transitRouterRouteTableNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
transitRouterRouteTableNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cen_transit_router_route_tables", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.TransitRouterRouteTables", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.TransitRouterRouteTables", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if transitRouterRouteTableNameRegex != nil {
if !transitRouterRouteTableNameRegex.MatchString(fmt.Sprint(item["TransitRouterRouteTableName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["TransitRouterRouteTableId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["TransitRouterRouteTableStatus"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"status": object["TransitRouterRouteTableStatus"],
"transit_router_route_table_description": object["TransitRouterRouteTableDescription"],
"id": fmt.Sprint(object["TransitRouterRouteTableId"]),
"transit_router_route_table_id": fmt.Sprint(object["TransitRouterRouteTableId"]),
"transit_router_route_table_name": object["TransitRouterRouteTableName"],
"transit_router_route_table_type": object["TransitRouterRouteTableType"],
}
ids = append(ids, fmt.Sprint(object["TransitRouterRouteTableId"]))
names = append(names, object["TransitRouterRouteTableName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("tables", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCenTransitRouterService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCenTransitRouterServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudCenTransitRouterServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("CenTransitRouterServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
request := map[string]interface{}{}
action := "CheckTransitRouterService"
request["ClientToken"] = buildClientToken(action)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"USER_NOT_OPEN_TR_SERVICE"}) {
action = "OpenTransitRouterService"
request["ClientToken"] = buildClientToken(action)
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ORDER.OPEND"}) {
d.SetId("CenTransitRouterServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cen_transit_router_service", action, AlibabaCloudSdkGoERROR)
}
d.SetId("CenTransitRouterServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cen_transit_router_service", action, AlibabaCloudSdkGoERROR)
}
if v, ok := response["Enabled"]; ok && v.(bool) {
d.SetId("CenTransitRouterServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
d.SetId("CenTransitRouterServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCenTransitRouterVbrAttachments() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCenTransitRouterVbrAttachmentsRead,
Schema: map[string]*schema.Schema{
"cen_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Attached", "Attaching", "Detaching"}, false),
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"transit_router_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"attachments": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"auto_publish_route_enabled": {
Type: schema.TypeBool,
Computed: true,
},
"resource_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_attachment_description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_attachment_id": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_attachment_name": {
Type: schema.TypeString,
Computed: true,
},
"vbr_id": {
Type: schema.TypeString,
Computed: true,
},
"vbr_owner_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCenTransitRouterVbrAttachmentsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListTransitRouterVbrAttachments"
request := make(map[string]interface{})
request["CenId"] = d.Get("cen_id")
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("transit_router_id"); ok {
request["TransitRouterId"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cen_transit_router_vbr_attachments", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.TransitRouterAttachments", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.TransitRouterAttachments", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["TransitRouterAttachmentId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"auto_publish_route_enabled": object["AutoPublishRouteEnabled"],
"resource_type": object["ResourceType"],
"status": object["Status"],
"transit_router_attachment_description": object["TransitRouterAttachmentDescription"],
"id": fmt.Sprint(object["TransitRouterAttachmentId"]),
"transit_router_attachment_id": fmt.Sprint(object["TransitRouterAttachmentId"]),
"transit_router_attachment_name": object["TransitRouterAttachmentName"],
"vbr_id": object["VbrId"],
"vbr_owner_id": fmt.Sprint(object["VbrOwnerId"]),
}
ids = append(ids, fmt.Sprint(object["TransitRouterAttachmentId"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("attachments", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCenTransitRouterVpcAttachments() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCenTransitRouterVpcAttachmentsRead,
Schema: map[string]*schema.Schema{
"cen_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Attached", "Attaching", "Detaching"}, false),
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"transit_router_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"attachments": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"resource_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_attachment_description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_attachment_id": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_attachment_name": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_owner_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_mappings": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudCenTransitRouterVpcAttachmentsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListTransitRouterVpcAttachments"
request := make(map[string]interface{})
request["CenId"] = d.Get("cen_id")
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("transit_router_id"); ok {
request["TransitRouterId"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cen_transit_router_vpc_attachments", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.TransitRouterAttachments", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.TransitRouterAttachments", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["TransitRouterAttachmentId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"status": object["Status"],
"transit_router_attachment_description": object["TransitRouterAttachmentDescription"],
"id": fmt.Sprint(object["TransitRouterAttachmentId"]),
"transit_router_attachment_id": fmt.Sprint(object["TransitRouterAttachmentId"]),
"transit_router_attachment_name": object["TransitRouterAttachmentName"],
"vpc_id": object["VpcId"],
"vpc_owner_id": fmt.Sprint(object["VpcOwnerId"]),
"resource_type": object["ResourceType"],
}
zoneMappings := make([]map[string]interface{}, 0)
if zoneMappingsList, ok := object["ZoneMappings"].([]interface{}); ok {
for _, v := range zoneMappingsList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"vswitch_id": m1["VSwitchId"],
"zone_id": m1["ZoneId"],
}
zoneMappings = append(zoneMappings, temp1)
}
}
}
mapping["zone_mappings"] = zoneMappings
ids = append(ids, fmt.Sprint(object["TransitRouterAttachmentId"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("attachments", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCenTransitRouters() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCenTransitRoutersRead,
Schema: map[string]*schema.Schema{
"cen_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Creating", "Deleting", "Updating"}, false),
},
"transit_router_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"transit_router_ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"transit_routers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ali_uid": {
Type: schema.TypeString,
Computed: true,
},
"cen_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_id": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_name": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"xgw_vip": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCenTransitRoutersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListTransitRouters"
request := make(map[string]interface{})
request["CenId"] = d.Get("cen_id")
request["RegionId"] = client.RegionId
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
if v, ok := d.GetOk("transit_router_id"); ok {
request["TransitRouterId"] = v
}
var objects []map[string]interface{}
var transitRouterNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
transitRouterNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
transitRouterIdsMap := make(map[string]string)
if v, ok := d.GetOk("transit_router_ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
transitRouterIdsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cen_transit_routers", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.TransitRouters", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.TransitRouters", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if transitRouterNameRegex != nil {
if !transitRouterNameRegex.MatchString(fmt.Sprint(item["TransitRouterName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["CenId"], ":", item["TransitRouterId"])]; !ok {
continue
}
}
if len(transitRouterIdsMap) > 0 {
if _, ok := transitRouterIdsMap[fmt.Sprint(item["TransitRouterId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"ali_uid": fmt.Sprint(object["AliUid"]),
"cen_id": object["CenId"],
"status": object["Status"],
"transit_router_description": object["TransitRouterDescription"],
"id": fmt.Sprint(object["CenId"], ":", object["TransitRouterId"]),
"transit_router_id": fmt.Sprint(object["TransitRouterId"]),
"transit_router_name": object["TransitRouterName"],
"type": object["Type"],
"xgw_vip": object["XgwVip"],
}
ids = append(ids, fmt.Sprint(object["TransitRouterId"]))
names = append(names, object["TransitRouterName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("transit_routers", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cbn"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudCenVbrHealthChecks() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCenVbrHealthChecksRead,
Schema: map[string]*schema.Schema{
"cen_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vbr_instance_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vbr_instance_owner_id": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"vbr_instance_region_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"checks": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"cen_id": {
Type: schema.TypeString,
Computed: true,
},
"health_check_interval": {
Type: schema.TypeInt,
Computed: true,
},
"health_check_source_ip": {
Type: schema.TypeString,
Computed: true,
},
"health_check_target_ip": {
Type: schema.TypeString,
Computed: true,
},
"healthy_threshold": {
Type: schema.TypeInt,
Computed: true,
},
"vbr_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"vbr_instance_region_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCenVbrHealthChecksRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cbn.CreateDescribeCenVbrHealthCheckRequest()
if v, ok := d.GetOk("cen_id"); ok {
request.CenId = v.(string)
}
if v, ok := d.GetOk("vbr_instance_id"); ok {
request.VbrInstanceId = v.(string)
}
if v, ok := d.GetOk("vbr_instance_owner_id"); ok {
request.VbrInstanceOwnerId = requests.NewInteger(v.(int))
}
request.VbrInstanceRegionId = d.Get("vbr_instance_region_id").(string)
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var objects []cbn.VbrHealthCheck
var response *cbn.DescribeCenVbrHealthCheckResponse
for {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DescribeCenVbrHealthCheck(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cen_vbr_health_checks", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ = raw.(*cbn.DescribeCenVbrHealthCheckResponse)
for _, item := range response.VbrHealthChecks.VbrHealthCheck {
objects = append(objects, item)
}
if len(response.VbrHealthChecks.VbrHealthCheck) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprintf("%v:%v", object.VbrInstanceId, object.VbrInstanceRegionId),
"cen_id": object.CenId,
"health_check_interval": object.HealthCheckInterval,
"health_check_source_ip": object.HealthCheckSourceIp,
"health_check_target_ip": object.HealthCheckTargetIp,
"healthy_threshold": object.HealthyThreshold,
"vbr_instance_id": object.VbrInstanceId,
"vbr_instance_region_id": object.VbrInstanceRegionId,
}
ids = append(ids, fmt.Sprintf("%v:%v", object.VbrInstanceId, object.VbrInstanceRegionId))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("checks", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudClickHouseAccounts() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudClickHouseAccountsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"db_cluster_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Creating", "Available", "Deleting"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"accounts": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"account_name": {
Type: schema.TypeString,
Computed: true,
},
"account_type": {
Type: schema.TypeString,
Computed: true,
},
"db_cluster_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudClickHouseAccountsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeAccounts"
request := make(map[string]interface{})
request["DBClusterId"] = d.Get("db_cluster_id")
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var accountNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
accountNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewClickhouseClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_click_house_accounts", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Accounts.Account", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Accounts.Account", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if accountNameRegex != nil && !accountNameRegex.MatchString(fmt.Sprint(item["AccountName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprintf("%s:%s", request["DBClusterId"].(string), item["AccountName"].(string))]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["AccountStatus"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"account_description": object["AccountDescription"],
"id": fmt.Sprint(object["AccountName"]),
"account_name": fmt.Sprint(object["AccountName"]),
"account_type": object["AccountType"],
"db_cluster_id": request["DBClusterId"],
"status": object["AccountStatus"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["AccountName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("accounts", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudClickHouseBackupPolicies() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudClickHouseBackupPoliciesRead,
Schema: map[string]*schema.Schema{
"db_cluster_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"policies": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"backup_retention_period": {
Type: schema.TypeInt,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"db_cluster_id": {
Type: schema.TypeString,
Computed: true,
},
"preferred_backup_period": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"preferred_backup_time": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudClickHouseBackupPoliciesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dbClusterId := d.Get("db_cluster_id")
clickhouseService := ClickhouseService{client}
object, err := clickhouseService.DescribeClickHouseBackupPolicy(dbClusterId.(string))
if err != nil {
if NotFoundError(err) {
d.SetId("ClickHouseBackupPolicy")
return nil
}
return WrapError(err)
}
s := make([]map[string]interface{}, 0)
mapping := map[string]interface{}{
"backup_retention_period": formatInt(object["BackupRetentionPeriod"]),
"id": fmt.Sprint(dbClusterId),
"db_cluster_id": fmt.Sprint(dbClusterId),
"preferred_backup_period": strings.Split(object["PreferredBackupPeriod"].(string), ","),
"preferred_backup_time": object["PreferredBackupTime"],
"status": fmt.Sprint(object["Switch"]),
}
s = append(s, mapping)
d.SetId(strconv.FormatInt(time.Now().Unix(), 16))
if err := d.Set("policies", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudClickHouseDbClusters() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudClickHouseDbClustersRead,
Schema: map[string]*schema.Schema{
"db_cluster_description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Creating", "Deleting", "Restarting", "Preparing", "Running"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"clusters": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ali_uid": {
Type: schema.TypeString,
Computed: true,
},
"bid": {
Type: schema.TypeString,
Computed: true,
},
"category": {
Type: schema.TypeString,
Computed: true,
},
"commodity_code": {
Type: schema.TypeString,
Computed: true,
},
"connection_string": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"db_cluster_access_white_list": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"db_cluster_ip_array_attribute": {
Type: schema.TypeString,
Computed: true,
},
"db_cluster_ip_array_name": {
Type: schema.TypeString,
Computed: true,
},
"security_ip_list": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"db_cluster_description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"db_cluster_id": {
Type: schema.TypeString,
Computed: true,
},
"db_cluster_network_type": {
Type: schema.TypeString,
Computed: true,
},
"db_cluster_type": {
Type: schema.TypeString,
Computed: true,
},
"db_node_class": {
Type: schema.TypeString,
Computed: true,
},
"db_node_count": {
Type: schema.TypeString,
Computed: true,
},
"db_node_storage": {
Type: schema.TypeString,
Computed: true,
},
"encryption_key": {
Type: schema.TypeString,
Computed: true,
},
"encryption_type": {
Type: schema.TypeString,
Computed: true,
},
"engine": {
Type: schema.TypeString,
Computed: true,
},
"engine_version": {
Type: schema.TypeString,
Computed: true,
},
"expire_time": {
Type: schema.TypeString,
Computed: true,
},
"is_expired": {
Type: schema.TypeString,
Computed: true,
},
"lock_mode": {
Type: schema.TypeString,
Computed: true,
},
"lock_reason": {
Type: schema.TypeString,
Computed: true,
},
"maintain_time": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeInt,
Computed: true,
},
"public_connection_string": {
Type: schema.TypeString,
Computed: true,
},
"public_port": {
Type: schema.TypeString,
Computed: true,
},
"scale_out_status": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"progress": {
Type: schema.TypeString,
Computed: true,
},
"ratio": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"storage_type": {
Type: schema.TypeString,
Computed: true,
},
"support_backup": {
Type: schema.TypeInt,
Computed: true,
},
"support_https_port": {
Type: schema.TypeBool,
Computed: true,
},
"support_mysql_port": {
Type: schema.TypeBool,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_cloud_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
"control_version": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudClickHouseDbClustersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDBClusters"
request := make(map[string]interface{})
if v, ok := d.GetOk("db_cluster_description"); ok {
request["DBClusterDescription"] = v
}
if v, ok := d.GetOk("status"); ok {
request["DBClusterStatus"] = v
}
request["RegionId"] = client.RegionId
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewClickhouseClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_click_house_db_clusters", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.DBClusters.DBCluster", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.DBClusters.DBCluster", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DBClusterId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"ali_uid": object["AliUid"],
"bid": object["Bid"],
"category": object["Category"],
"commodity_code": object["CommodityCode"],
"connection_string": object["ConnectionString"],
"create_time": object["CreateTime"],
"db_cluster_description": object["DBClusterDescription"],
"id": fmt.Sprint(object["DBClusterId"]),
"db_cluster_id": fmt.Sprint(object["DBClusterId"]),
"db_cluster_network_type": object["DBClusterNetworkType"],
"db_node_class": object["DBNodeClass"],
"db_node_count": fmt.Sprint(object["DBNodeCount"]),
"db_node_storage": fmt.Sprint(object["DBNodeStorage"]),
"expire_time": object["ExpireTime"],
"lock_mode": object["LockMode"],
"lock_reason": object["LockReason"],
"payment_type": convertClickHouseDbClusterPaymentTypeResponse(object["PayType"].(string)),
"port": formatInt(object["Port"]),
"storage_type": object["StorageType"],
"vswitch_id": object["VSwitchId"],
"vpc_cloud_instance_id": object["VpcCloudInstanceId"],
"vpc_id": object["VpcId"],
"zone_id": object["ZoneId"],
"control_version": object["ControlVersion"],
"status": object["DBClusterStatus"],
}
if val, exist := object["IsExpired"]; exist {
object["is_expired"] = val.(bool)
}
ids = append(ids, fmt.Sprint(mapping["id"]))
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["DBClusterId"])
clickhouseService := ClickhouseService{client}
getResp1, err := clickhouseService.DescribeDBClusterAccessWhiteList(id)
if err != nil {
return WrapError(err)
}
iPArray := make([]map[string]interface{}, 0)
if iPArrayList, ok := getResp1["DBClusterAccessWhiteList"].(map[string]interface{})["IPArray"].([]interface{}); ok {
for _, v := range iPArrayList {
if m1, ok := v.(map[string]interface{}); ok {
if m1["DBClusterIPArrayName"].(string) == "default" {
continue
}
temp1 := map[string]interface{}{
"db_cluster_ip_array_attribute": m1["DBClusterIPArrayAttribute"],
"db_cluster_ip_array_name": m1["DBClusterIPArrayName"],
"security_ip_list": m1["SecurityIPList"],
}
iPArray = append(iPArray, temp1)
}
}
}
mapping["db_cluster_access_white_list"] = iPArray
getResp, err := clickhouseService.DescribeClickHouseDbCluster(id)
if err != nil {
return WrapError(err)
}
mapping["db_cluster_type"] = getResp["DBClusterType"]
mapping["encryption_key"] = getResp["EncryptionKey"]
mapping["encryption_type"] = getResp["EncryptionType"]
mapping["engine"] = getResp["Engine"]
mapping["engine_version"] = getResp["EngineVersion"]
mapping["maintain_time"] = getResp["MaintainTime"]
mapping["public_connection_string"] = getResp["PublicConnectionString"]
mapping["public_port"] = getResp["PublicPort"]
if v, ok := getResp["SupportBackup"]; ok && fmt.Sprint(v) != "0" {
mapping["support_backup"] = formatInt(v)
}
mapping["support_https_port"] = getResp["SupportHttpsPort"]
mapping["support_mysql_port"] = getResp["SupportMysqlPort"]
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("clusters", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"strconv"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudClickHouseRegions() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudClickHouseRegionsRead,
Schema: map[string]*schema.Schema{
"region_id": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"current"},
},
"current": {
Type: schema.TypeBool,
Optional: true,
ConflictsWith: []string{"region_id"},
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"regions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"vpc_enabled": {
Type: schema.TypeBool,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudClickHouseRegionsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeRegions"
request := make(map[string]interface{})
var objects []map[string]interface{}
var response map[string]interface{}
update := false
conn, err := client.NewClickhouseClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_click_house_regions", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Regions.Region", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Accounts.Account", response)
}
result, _ := resp.([]interface{})
if v, exist := d.GetOk("current"); exist {
update = v.(bool)
}
for _, v := range result {
obj := v.(map[string]interface{})
if update {
if client.RegionId != obj["RegionId"].(string) {
continue
}
}
if v, exist := d.GetOk("region_id"); exist {
if v.(string) != obj["RegionId"].(string) {
continue
}
}
objects = append(objects, obj)
}
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"region_id": fmt.Sprint(object["RegionId"]),
}
zoneRes := make([]interface{}, 0)
if _, exist := object["Zones"]; exist {
for _, zonesmapslicSli := range object["Zones"].(map[string]interface{}) {
for _, obj := range zonesmapslicSli.([]interface{}) {
objMap := obj.(map[string]interface{})
singleObj := make(map[string]interface{}, 0)
singleObj["vpc_enabled"] = objMap["VpcEnabled"].(bool)
singleObj["zone_id"] = fmt.Sprint(objMap["ZoneId"])
zoneRes = append(zoneRes, singleObj)
}
}
}
mapping["zone_ids"] = zoneRes
s = append(s, mapping)
}
d.SetId(strconv.FormatInt(time.Now().Unix(), 16))
if err := d.Set("regions", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/smartag"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCloudConnectNetworks() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCloudConnectNetworkRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.ValidateRegexp,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"networks": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"cidr_block": {
Type: schema.TypeString,
Computed: true,
},
"is_default": {
Type: schema.TypeBool,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCloudConnectNetworkRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := smartag.CreateDescribeCloudConnectNetworksRequest()
var allCcnInstances []smartag.CloudConnectNetwork
request.RegionId = client.RegionId
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
for {
raw, err := client.WithSagClient(func(ccnClient *smartag.Client) (interface{}, error) {
return ccnClient.DescribeCloudConnectNetworks(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cloud_connect_networks", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*smartag.DescribeCloudConnectNetworksResponse)
cloudConnectNetworks := response.CloudConnectNetworks.CloudConnectNetwork
for _, cloudConnectNetwork := range cloudConnectNetworks {
allCcnInstances = append(allCcnInstances, cloudConnectNetwork)
}
if len(cloudConnectNetworks) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
var filteredCcnInstancesTemp []smartag.CloudConnectNetwork
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
for _, ccnInstance := range allCcnInstances {
if v, ok := d.GetOk("id"); ok && v.(string) != "" && ccnInstance.CcnId != v.(string) {
continue
}
if v, ok := d.GetOk("name_regex"); ok && v.(string) != "" {
r := regexp.MustCompile(v.(string))
if !r.MatchString(ccnInstance.Name) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[ccnInstance.CcnId]; !ok {
continue
}
}
filteredCcnInstancesTemp = append(filteredCcnInstancesTemp, ccnInstance)
}
return cloudConnectNetworkAttributes(d, filteredCcnInstancesTemp, meta)
}
func cloudConnectNetworkAttributes(d *schema.ResourceData, ccnInstances []smartag.CloudConnectNetwork, meta interface{}) error {
var ids []string
var names []string
var s []map[string]interface{}
for _, ccnInstance := range ccnInstances {
mapping := map[string]interface{}{
"id": ccnInstance.CcnId,
"name": ccnInstance.Name,
"description": ccnInstance.Description,
"cidr_block": ccnInstance.CidrBlock,
"is_default": ccnInstance.IsDefault,
}
names = append(names, ccnInstance.Name)
ids = append(ids, ccnInstance.CcnId)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("networks", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCloudFirewallControlPolicies() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCloudFirewallControlPoliciesRead,
Schema: map[string]*schema.Schema{
"acl_action": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"accept", "drop", "log"}, false),
},
"acl_uuid": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"destination": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"direction": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"in", "out"}, false),
},
"ip_version": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"lang": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"en", "zh"}, false),
},
"proto": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{" TCP", " UDP", "ANY", "ICMP"}, false),
},
"source": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"source_ip": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"policies": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"acl_action": {
Type: schema.TypeString,
Computed: true,
},
"acl_uuid": {
Type: schema.TypeString,
Computed: true,
},
"application_id": {
Type: schema.TypeString,
Computed: true,
},
"application_name": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"dest_port": {
Type: schema.TypeString,
Computed: true,
},
"dest_port_group": {
Type: schema.TypeString,
Computed: true,
},
"dest_port_group_ports": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"dest_port_type": {
Type: schema.TypeString,
Computed: true,
},
"destination": {
Type: schema.TypeString,
Computed: true,
},
"destination_group_cidrs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"destination_group_type": {
Type: schema.TypeString,
Computed: true,
},
"destination_type": {
Type: schema.TypeString,
Computed: true,
},
"direction": {
Type: schema.TypeString,
Computed: true,
},
"dns_result": {
Type: schema.TypeString,
Computed: true,
},
"dns_result_time": {
Type: schema.TypeString,
Computed: true,
},
"hit_times": {
Type: schema.TypeString,
Computed: true,
},
"order": {
Type: schema.TypeInt,
Computed: true,
},
"proto": {
Type: schema.TypeString,
Computed: true,
},
"release": {
Type: schema.TypeBool,
Computed: true,
},
"source": {
Type: schema.TypeString,
Computed: true,
},
"source_group_cidrs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"source_group_type": {
Type: schema.TypeString,
Computed: true,
},
"source_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCloudFirewallControlPoliciesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeControlPolicy"
request := make(map[string]interface{})
if v, ok := d.GetOk("acl_action"); ok {
request["AclAction"] = v
}
if v, ok := d.GetOk("acl_uuid"); ok {
request["AclUuid"] = v
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("destination"); ok {
request["Destination"] = v
}
request["Direction"] = d.Get("direction")
if v, ok := d.GetOk("ip_version"); ok {
request["IpVersion"] = v
}
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
if v, ok := d.GetOk("proto"); ok {
request["Proto"] = v
}
if v, ok := d.GetOk("source"); ok {
request["Source"] = v
}
if v, ok := d.GetOk("source_ip"); ok {
request["SourceIp"] = v
}
request["PageSize"] = PageSizeLarge
request["CurrentPage"] = 1
var objects []map[string]interface{}
var response map[string]interface{}
conn, err := client.NewCloudfwClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-07"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cloud_firewall_control_policies", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Policys", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Policys", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["CurrentPage"] = request["CurrentPage"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["AclUuid"], ":", object["Direction"]),
"acl_action": object["AclAction"],
"acl_uuid": object["AclUuid"],
"application_id": object["ApplicationId"],
"application_name": object["ApplicationName"],
"description": object["Description"],
"dest_port": object["DestPort"],
"dest_port_group": object["DestPortGroup"],
"dest_port_group_ports": object["DestPortGroupPorts"],
"dest_port_type": object["DestPortType"],
"destination": object["Destination"],
"destination_group_cidrs": object["DestinationGroupCidrs"],
"destination_group_type": object["DestinationGroupType"],
"destination_type": object["DestinationType"],
"direction": object["Direction"],
"dns_result": object["DnsResult"],
"dns_result_time": fmt.Sprint(object["DnsResultTime"]),
"hit_times": fmt.Sprint(object["HitTimes"]),
"order": formatInt(object["Order"]),
"proto": object["Proto"],
"release": object["Release"],
"source": object["Source"],
"source_group_cidrs": object["SourceGroupCidrs"],
"source_group_type": object["SourceGroupType"],
"source_type": object["SourceType"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("policies", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"strconv"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudCloudFirewallInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCloudFirewallInstancesRead,
Schema: map[string]*schema.Schema{
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"status": {
Type: schema.TypeString,
Computed: true,
},
"renewal_status": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"end_time": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"renewal_duration_unit": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCloudFirewallInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "QueryAvailableInstances"
request := make(map[string]interface{})
request["ProductCode"] = "vipcloudfw"
request["ProductType"] = "vipcloudfw"
request["PageSize"] = PageSizeLarge
request["PageNum"] = 1
var objects []map[string]interface{}
var response map[string]interface{}
conn, err := client.NewBssopenapiClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-14"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"NotApplicable"}) {
conn.Endpoint = String(connectivity.BssOpenAPIEndpointInternational)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cloud_firewall_instances", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.Data.InstanceList", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Data.InstanceList", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNum"] = request["PageNum"].(int) + 1
}
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"status": object["Status"],
"end_time": object["EndTime"],
"create_time": object["CreateTime"],
"payment_type": object["SubscriptionType"],
"renewal_duration_unit": convertCloudFirewallInstanceRenewalDurationUnitResponse(object["RenewalDurationUnit"]),
"id": object["InstanceID"],
"renewal_status": object["RenewStatus"],
"instance_id": object["InstanceID"],
}
s = append(s, mapping)
}
d.SetId(strconv.FormatInt(time.Now().Unix(), 16))
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCloudSsoAccessConfigurations() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCloudSsoAccessConfigurationsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"directory_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"configurations": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"access_configuration_id": {
Type: schema.TypeString,
Computed: true,
},
"access_configuration_name": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"directory_id": {
Type: schema.TypeString,
Computed: true,
},
"permission_policies": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"add_time": {
Type: schema.TypeString,
Computed: true,
},
"permission_policy_document": {
Type: schema.TypeString,
Computed: true,
},
"permission_policy_name": {
Type: schema.TypeString,
Computed: true,
},
"permission_policy_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"relay_state": {
Type: schema.TypeString,
Computed: true,
},
"session_duration": {
Type: schema.TypeInt,
Computed: true,
},
"status_notifications": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudCloudSsoAccessConfigurationsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListAccessConfigurations"
request := make(map[string]interface{})
request["DirectoryId"] = d.Get("directory_id")
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var accessConfigurationNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
accessConfigurationNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cloud_sso_access_configurations", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.AccessConfigurations", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.AccessConfigurations", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if accessConfigurationNameRegex != nil && !accessConfigurationNameRegex.MatchString(fmt.Sprint(item["AccessConfigurationName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(request["DirectoryId"], ":", item["AccessConfigurationId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(request["DirectoryId"], ":", object["AccessConfigurationId"]),
"access_configuration_id": fmt.Sprint(object["AccessConfigurationId"]),
"access_configuration_name": object["AccessConfigurationName"],
"create_time": object["CreateTime"],
"description": object["Description"],
"directory_id": request["DirectoryId"],
"relay_state": object["RelayState"],
"session_duration": formatInt(object["SessionDuration"]),
"status_notifications": object["StatusNotifications"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["AccessConfigurationName"])
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(request["DirectoryId"], ":", object["AccessConfigurationId"])
cloudssoService := CloudssoService{client}
getResp, err := cloudssoService.ListPermissionPoliciesInAccessConfiguration(id)
if err != nil {
return WrapError(err)
}
permissionPolicies := make([]map[string]interface{}, 0)
if permissionPoliciesList, ok := getResp["PermissionPolicies"]; ok && permissionPoliciesList != nil {
for _, v := range permissionPoliciesList.([]interface{}) {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"add_time": m1["AddTime"],
"permission_policy_document": m1["PermissionPolicyDocument"],
"permission_policy_name": m1["PermissionPolicyName"],
"permission_policy_type": m1["PermissionPolicyType"],
}
permissionPolicies = append(permissionPolicies, temp1)
}
}
}
mapping["permission_policies"] = permissionPolicies
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("configurations", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCloudSsoDirectories() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCloudSsoDirectoriesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"directories": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"directory_id": {
Type: schema.TypeString,
Computed: true,
},
"directory_name": {
Type: schema.TypeString,
Computed: true,
},
"mfa_authentication_status": {
Type: schema.TypeString,
Computed: true,
},
"region": {
Type: schema.TypeString,
Computed: true,
},
"saml_identity_provider_configuration": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"encoded_metadata_document": {
Type: schema.TypeString,
Computed: true,
},
"entity_id": {
Type: schema.TypeString,
Computed: true,
},
"login_url": {
Type: schema.TypeString,
Computed: true,
},
"sso_status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"scim_synchronization_status": {
Type: schema.TypeString,
Computed: true,
},
"tasks": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"access_configuration_id": {
Type: schema.TypeString,
Computed: true,
},
"access_configuration_name": {
Type: schema.TypeString,
Computed: true,
},
"end_time": {
Type: schema.TypeString,
Computed: true,
},
"failure_reason": {
Type: schema.TypeString,
Computed: true,
},
"principal_id": {
Type: schema.TypeString,
Computed: true,
},
"principal_name": {
Type: schema.TypeString,
Computed: true,
},
"principal_type": {
Type: schema.TypeString,
Computed: true,
},
"start_time": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"target_id": {
Type: schema.TypeString,
Computed: true,
},
"target_name": {
Type: schema.TypeString,
Computed: true,
},
"target_path": {
Type: schema.TypeString,
Computed: true,
},
"target_type": {
Type: schema.TypeString,
Computed: true,
},
"task_id": {
Type: schema.TypeString,
Computed: true,
},
"task_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudCloudSsoDirectoriesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListDirectories"
request := make(map[string]interface{})
var objects []map[string]interface{}
var directoryNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
directoryNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cloud_sso_directories", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Directories", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Directories", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if directoryNameRegex != nil && !directoryNameRegex.MatchString(fmt.Sprint(item["DirectoryName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DirectoryId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": object["CreateTime"],
"id": fmt.Sprint(object["DirectoryId"]),
"directory_id": fmt.Sprint(object["DirectoryId"]),
"directory_name": object["DirectoryName"],
"region": object["Region"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["DirectoryName"])
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
cloudssoService := CloudssoService{client}
getDirectoryObject, err := cloudssoService.DescribeCloudSsoDirectory(fmt.Sprint(object["DirectoryId"]))
if err != nil {
return WrapError(err)
}
mapping["mfa_authentication_status"] = getDirectoryObject["MFAAuthenticationStatus"]
mapping["scim_synchronization_status"] = getDirectoryObject["SCIMSynchronizationStatus"]
if SAMLIdentityProviderConfiguration, ok := getDirectoryObject["SAMLIdentityProviderConfiguration"]; ok && len(SAMLIdentityProviderConfiguration.(map[string]interface{})) > 0 {
SAMLIdentityProviderConfigurationSli := make([]map[string]interface{}, 0)
SAMLIdentityProviderConfigurationMap := make(map[string]interface{})
SAMLIdentityProviderConfigurationMap["sso_status"] = SAMLIdentityProviderConfiguration.(map[string]interface{})["SSOStatus"]
SAMLIdentityProviderConfigurationMap["entity_id"] = SAMLIdentityProviderConfiguration.(map[string]interface{})["EntityId"]
SAMLIdentityProviderConfigurationMap["create_time"] = SAMLIdentityProviderConfiguration.(map[string]interface{})["CreateTime"]
SAMLIdentityProviderConfigurationMap["login_url"] = SAMLIdentityProviderConfiguration.(map[string]interface{})["LoginUrl"]
if v, ok := SAMLIdentityProviderConfiguration.(map[string]interface{})["EncodedMetadataDocument"]; ok {
SAMLIdentityProviderConfigurationMap["encoded_metadata_document"] = v
}
SAMLIdentityProviderConfigurationSli = append(SAMLIdentityProviderConfigurationSli, SAMLIdentityProviderConfigurationMap)
mapping["saml_identity_provider_configuration"] = SAMLIdentityProviderConfigurationSli
}
getResp, err := cloudssoService.GetDirectoryTasks(fmt.Sprint(object["DirectoryId"]))
if err != nil {
return WrapError(err)
}
if getDirectoryTasks, ok := getResp["Tasks"]; ok {
tasks := make([]map[string]interface{}, 0)
for _, v := range getDirectoryTasks.([]interface{}) {
if t, ok := v.(map[string]interface{}); ok {
temp := map[string]interface{}{
"access_configuration_id": t["AccessConfigurationId"],
"access_configuration_name": t["AccessConfigurationName"],
"end_time": t["EndTime"],
"failure_reason": t["FailureReason"],
"principal_id": t["PrincipalId"],
"principal_name": t["PrincipalName"],
"principal_type": t["PrincipalType"],
"start_time": t["StartTime"],
"status": t["Status"],
"target_id": t["TargetId"],
"target_name": t["TargetName"],
"target_path": t["TargetPath"],
"target_type": t["TargetType"],
"task_id": t["TaskId"],
"task_type": t["TaskType"],
}
tasks = append(tasks, temp)
}
}
mapping["tasks"] = tasks
}
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("directories", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCloudSsoGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCloudSsoGroupsRead,
Schema: map[string]*schema.Schema{
"directory_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"provision_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Manual", "Synchronized"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"directory_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"group_id": {
Type: schema.TypeString,
Computed: true,
},
"group_name": {
Type: schema.TypeString,
Computed: true,
},
"provision_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCloudSsoGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListGroups"
request := make(map[string]interface{})
request["DirectoryId"] = d.Get("directory_id")
if v, ok := d.GetOk("provision_type"); ok {
request["ProvisionType"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var groupNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
groupNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cloud_sso_groups", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Groups", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Groups", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if groupNameRegex != nil && !groupNameRegex.MatchString(fmt.Sprint(item["GroupName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(request["DirectoryId"], ":", item["GroupId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": object["CreateTime"],
"description": object["Description"],
"directory_id": request["DirectoryId"],
"id": fmt.Sprint(request["DirectoryId"], ":", object["GroupId"]),
"group_id": fmt.Sprint(object["GroupId"]),
"group_name": object["GroupName"],
"provision_type": object["ProvisionType"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["GroupName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCloudSsoScimServerCredentials() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCloudSsoScimServerCredentialsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"directory_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Disabled", "Enabled"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"credentials": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"credential_id": {
Type: schema.TypeString,
Computed: true,
},
"credential_secret": {
Type: schema.TypeString,
Computed: true,
},
"credential_type": {
Type: schema.TypeString,
Computed: true,
},
"directory_id": {
Type: schema.TypeString,
Computed: true,
},
"expire_time": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCloudSsoScimServerCredentialsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListSCIMServerCredentials"
request := make(map[string]interface{})
request["DirectoryId"] = d.Get("directory_id")
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cloud_sso_scim_server_credentials", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.SCIMServerCredentials", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.SCIMServerCredentials", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DirectoryId"], ":", item["CredentialId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": object["CreateTime"],
"id": fmt.Sprint(object["DirectoryId"], ":", object["CredentialId"]),
"credential_id": fmt.Sprint(object["CredentialId"]),
"credential_secret": object["CredentialSecret"],
"credential_type": object["CredentialType"],
"directory_id": object["DirectoryId"],
"expire_time": object["ExpireTime"],
"status": object["Status"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("credentials", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCloudSsoService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCloudSsoServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudCloudSsoServiceRead(d *schema.ResourceData, meta interface{}) error {
var response map[string]interface{}
request := map[string]interface{}{}
conn, err := meta.(*connectivity.AliyunClient).NewCloudssoClient()
if err != nil {
return WrapError(err)
}
enable := d.Get("enable").(string)
if enable == "On" {
action := "EnableService"
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cloud_sso_service", action, AlibabaCloudSdkGoERROR)
}
d.SetId("CloudSsoServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
if enable == "Off" {
action := "DisableService"
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cloud_sso_service", action, AlibabaCloudSdkGoERROR)
}
d.SetId("CloudSsoServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCloudSsoUsers() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCloudSsoUsersRead,
Schema: map[string]*schema.Schema{
"directory_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"provision_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Manual", "Synchronized"}, false),
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Disabled", "Enabled"}, false),
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"users": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"directory_id": {
Type: schema.TypeString,
Computed: true,
},
"display_name": {
Type: schema.TypeString,
Computed: true,
},
"email": {
Type: schema.TypeString,
Computed: true,
},
"first_name": {
Type: schema.TypeString,
Computed: true,
},
"last_name": {
Type: schema.TypeString,
Computed: true,
},
"mfa_devices": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"device_id": {
Type: schema.TypeString,
Computed: true,
},
"device_name": {
Type: schema.TypeString,
Computed: true,
},
"device_type": {
Type: schema.TypeString,
Computed: true,
},
"effective_time": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"provision_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"user_id": {
Type: schema.TypeString,
Computed: true,
},
"user_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudCloudSsoUsersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListUsers"
request := make(map[string]interface{})
request["DirectoryId"] = d.Get("directory_id")
if v, ok := d.GetOk("provision_type"); ok {
request["ProvisionType"] = v
}
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var userNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
userNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cloud_sso_users", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Users", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Users", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if userNameRegex != nil && !userNameRegex.MatchString(fmt.Sprint(item["UserName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprintf("%s:%s", request["DirectoryId"], item["UserId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": object["CreateTime"],
"description": object["Description"],
"directory_id": request["DirectoryId"],
"display_name": object["DisplayName"],
"email": object["Email"],
"first_name": object["FirstName"],
"last_name": object["LastName"],
"provision_type": object["ProvisionType"],
"status": object["Status"],
"id": fmt.Sprint(request["DirectoryId"], ":", object["UserId"]),
"user_id": fmt.Sprint(object["UserId"]),
"user_name": object["UserName"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["UserName"])
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(request["DirectoryId"], ":", object["UserId"])
cloudssoService := CloudssoService{client}
getResp, err := cloudssoService.ListMFADevicesForUser(id)
if err != nil {
return WrapError(err)
}
mFADevices := make([]map[string]interface{}, 0)
if mFADevicesList, ok := getResp["MFADevices"]; ok {
for _, v := range mFADevicesList.([]interface{}) {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"device_id": m1["DeviceId"],
"device_name": m1["DeviceName"],
"device_type": m1["DeviceType"],
"effective_time": m1["EffectiveTime"],
}
mFADevices = append(mFADevices, temp1)
}
}
}
mapping["mfa_devices"] = mFADevices
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("users", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCloudStorageGatewayExpressSyncs() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCloudStorageGatewayExpressSyncsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"syncs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"bucket_name": {
Type: schema.TypeString,
Computed: true,
},
"bucket_prefix": {
Type: schema.TypeString,
Computed: true,
},
"bucket_region": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"express_sync_id": {
Type: schema.TypeString,
Computed: true,
},
"express_sync_name": {
Type: schema.TypeString,
Computed: true,
},
"mns_topic": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCloudStorageGatewayExpressSyncsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeExpressSyncs"
request := make(map[string]interface{})
var objects []map[string]interface{}
var expressSyncNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
expressSyncNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cloud_storage_gateway_express_syncs", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.ExpressSyncs.ExpressSync", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.ExpressSyncs.ExpressSync", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if expressSyncNameRegex != nil && !expressSyncNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ExpressSyncId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"bucket_name": object["BucketName"],
"bucket_prefix": fmt.Sprint(object["BucketPrefix"]),
"bucket_region": object["BucketRegion"],
"description": object["Description"],
"id": fmt.Sprint(object["ExpressSyncId"]),
"express_sync_id": fmt.Sprint(object["ExpressSyncId"]),
"express_sync_name": object["Name"],
"mns_topic": object["MnsTopic"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("syncs", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCloudStorageGatewayGatewayBlockVolumes() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCloudStorageGatewayGatewayBlockVolumesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"gateway_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"status": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IntBetween(0, 8),
},
"volumes": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"address": {
Type: schema.TypeString,
Computed: true,
},
"cache_mode": {
Type: schema.TypeString,
Computed: true,
},
"chap_enabled": {
Type: schema.TypeBool,
Computed: true,
},
"chap_in_user": {
Type: schema.TypeString,
Computed: true,
},
"chunk_size": {
Type: schema.TypeInt,
Computed: true,
},
"disk_id": {
Type: schema.TypeString,
Computed: true,
},
"disk_type": {
Type: schema.TypeString,
Computed: true,
},
"enabled": {
Type: schema.TypeBool,
Computed: true,
},
"gateway_block_volume_name": {
Type: schema.TypeString,
Computed: true,
},
"gateway_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"index_id": {
Type: schema.TypeString,
Computed: true,
},
"local_path": {
Type: schema.TypeString,
Computed: true,
},
"lun_id": {
Type: schema.TypeInt,
Computed: true,
},
"oss_bucket_name": {
Type: schema.TypeString,
Computed: true,
},
"oss_bucket_ssl": {
Type: schema.TypeBool,
Computed: true,
},
"oss_endpoint": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeInt,
Computed: true,
},
"protocol": {
Type: schema.TypeString,
Computed: true,
},
"size": {
Type: schema.TypeInt,
Computed: true,
},
"state": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeInt,
Computed: true,
},
"target": {
Type: schema.TypeString,
Computed: true,
},
"total_download": {
Type: schema.TypeInt,
Computed: true,
},
"total_upload": {
Type: schema.TypeInt,
Computed: true,
},
"volume_state": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCloudStorageGatewayGatewayBlockVolumesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeGatewayBlockVolumes"
request := make(map[string]interface{})
request["GatewayId"] = d.Get("gateway_id")
var objects []map[string]interface{}
var gatewayBlockVolumeNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
gatewayBlockVolumeNameRegex = r
}
status, statusOk := d.GetOk("status")
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cloud_storage_gateway_gateway_block_volumes", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.BlockVolumes.BlockVolume", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.BlockVolumes.BlockVolume", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if gatewayBlockVolumeNameRegex != nil && !gatewayBlockVolumeNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(request["GatewayId"], ":", item["IndexId"])]; !ok {
continue
}
}
if statusOk && status.(int) != item["VolumeState"] {
continue
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"address": object["Address"],
"cache_mode": object["CacheMode"],
"chap_enabled": object["ChapEnabled"],
"chap_in_user": fmt.Sprint(object["ChapInUser"]),
"chunk_size": formatInt(object["ChunkSize"]),
"disk_id": object["DiskId"],
"disk_type": object["DiskType"],
"enabled": object["Enabled"],
"gateway_block_volume_name": object["Name"],
"gateway_id": request["GatewayId"],
"id": fmt.Sprint(request["GatewayId"], ":", object["IndexId"]),
"index_id": fmt.Sprint(object["IndexId"]),
"local_path": object["LocalPath"],
"lun_id": formatInt(object["LunId"]),
"oss_bucket_name": object["OssBucketName"],
"oss_bucket_ssl": object["OssBucketSsl"],
"oss_endpoint": object["OssEndpoint"],
"port": formatInt(object["Port"]),
"protocol": object["Protocol"],
"size": formatInt(object["Size"]),
"state": object["State"],
"status": formatInt(object["Status"]),
"target": object["Target"],
"total_download": formatInt(object["TotalDownload"]),
"total_upload": formatInt(object["TotalUpload"]),
"volume_state": formatInt(object["VolumeState"]),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("volumes", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudCloudStorageGatewayGatewayCacheDisks() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCloudStorageGatewayGatewayCacheDisksRead,
Schema: map[string]*schema.Schema{
"gateway_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IntInSlice([]int{0, 1, 2}),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"disks": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cache_disk_category": {
Type: schema.TypeString,
Computed: true,
},
"cache_disk_size_in_gb": {
Type: schema.TypeInt,
Computed: true,
},
"cache_id": {
Type: schema.TypeString,
Computed: true,
},
"expired_time": {
Type: schema.TypeInt,
Computed: true,
},
"gateway_id": {
Type: schema.TypeString,
Computed: true,
},
"iops": {
Type: schema.TypeInt,
Computed: true,
},
"is_used": {
Type: schema.TypeBool,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"local_file_path": {
Type: schema.TypeString,
Computed: true,
},
"renew_url": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCloudStorageGatewayGatewayCacheDisksRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeGatewayCaches"
request := make(map[string]interface{})
request["GatewayId"] = d.Get("gateway_id")
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cloud_storage_gateway_gateway_cache_disks", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.Caches.Cache", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Caches.Cache", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(request["GatewayId"], ":", item["CacheId"], ":", item["LocalFilePath"])]; !ok {
continue
}
}
if statusOk && fmt.Sprint(status) != fmt.Sprint(item["ExpireStatus"]) {
continue
}
objects = append(objects, item)
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"cache_disk_category": object["CacheType"],
"cache_disk_size_in_gb": formatInt(object["SizeInGB"]),
"cache_id": object["CacheId"],
"expired_time": formatInt(object["ExpiredTime"]),
"gateway_id": request["GatewayId"],
"iops": formatInt(object["Iops"]),
"is_used": object["IsUsed"],
"id": fmt.Sprint(request["GatewayId"], ":", object["CacheId"], ":", object["LocalFilePath"]),
"local_file_path": fmt.Sprint(object["LocalFilePath"]),
"renew_url": object["RenewURL"],
"status": formatInt(object["ExpireStatus"]),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("disks", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCloudStorageGatewayGatewayFileShares() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCloudStorageGatewayGatewayFileSharesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"gateway_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"shares": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"access_based_enumeration": {
Type: schema.TypeBool,
Computed: true,
},
"address": {
Type: schema.TypeString,
Computed: true,
},
"backend_limit": {
Type: schema.TypeInt,
Computed: true,
},
"browsable": {
Type: schema.TypeBool,
Computed: true,
},
"bucket_infos": {
Type: schema.TypeString,
Computed: true,
},
"buckets_stub": {
Type: schema.TypeBool,
Computed: true,
},
"cache_mode": {
Type: schema.TypeString,
Computed: true,
},
"client_side_cmk": {
Type: schema.TypeString,
Computed: true,
},
"client_side_encryption": {
Type: schema.TypeBool,
Computed: true,
},
"direct_io": {
Type: schema.TypeBool,
Computed: true,
},
"disk_id": {
Type: schema.TypeString,
Computed: true,
},
"disk_type": {
Type: schema.TypeString,
Computed: true,
},
"download_limit": {
Type: schema.TypeInt,
Computed: true,
},
"enabled": {
Type: schema.TypeBool,
Computed: true,
},
"express_sync_id": {
Type: schema.TypeString,
Computed: true,
},
"fast_reclaim": {
Type: schema.TypeBool,
Computed: true,
},
"fe_limit": {
Type: schema.TypeInt,
Computed: true,
},
"file_num_limit": {
Type: schema.TypeString,
Computed: true,
},
"fs_size_limit": {
Type: schema.TypeString,
Computed: true,
},
"gateway_file_share_name": {
Type: schema.TypeString,
Computed: true,
},
"gateway_id": {
Type: schema.TypeString,
Computed: true,
},
"ignore_delete": {
Type: schema.TypeBool,
Computed: true,
},
"in_place": {
Type: schema.TypeBool,
Computed: true,
},
"in_rate": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"index_id": {
Type: schema.TypeString,
Computed: true,
},
"kms_rotate_period": {
Type: schema.TypeInt,
Computed: true,
},
"lag_period": {
Type: schema.TypeString,
Computed: true,
},
"local_path": {
Type: schema.TypeString,
Computed: true,
},
"mns_health": {
Type: schema.TypeString,
Computed: true,
},
"nfs_v4_optimization": {
Type: schema.TypeBool,
Computed: true,
},
"obsolete_buckets": {
Type: schema.TypeString,
Computed: true,
},
"oss_bucket_name": {
Type: schema.TypeString,
Computed: true,
},
"oss_bucket_ssl": {
Type: schema.TypeBool,
Computed: true,
},
"oss_endpoint": {
Type: schema.TypeString,
Computed: true,
},
"oss_health": {
Type: schema.TypeString,
Computed: true,
},
"oss_used": {
Type: schema.TypeString,
Computed: true,
},
"out_rate": {
Type: schema.TypeString,
Computed: true,
},
"partial_sync_paths": {
Type: schema.TypeString,
Computed: true,
},
"path_prefix": {
Type: schema.TypeString,
Computed: true,
},
"polling_interval": {
Type: schema.TypeInt,
Computed: true,
},
"protocol": {
Type: schema.TypeString,
Computed: true,
},
"remaining_meta_space": {
Type: schema.TypeString,
Computed: true,
},
"remote_sync": {
Type: schema.TypeBool,
Computed: true,
},
"remote_sync_download": {
Type: schema.TypeBool,
Computed: true,
},
"ro_client_list": {
Type: schema.TypeString,
Computed: true,
},
"ro_user_list": {
Type: schema.TypeString,
Computed: true,
},
"rw_client_list": {
Type: schema.TypeString,
Computed: true,
},
"rw_user_list": {
Type: schema.TypeString,
Computed: true,
},
"server_side_cmk": {
Type: schema.TypeString,
Computed: true,
},
"server_side_encryption": {
Type: schema.TypeBool,
Computed: true,
},
"size": {
Type: schema.TypeString,
Computed: true,
},
"squash": {
Type: schema.TypeString,
Computed: true,
},
"state": {
Type: schema.TypeString,
Computed: true,
},
"support_archive": {
Type: schema.TypeBool,
Computed: true,
},
"sync_progress": {
Type: schema.TypeInt,
Computed: true,
},
"total_download": {
Type: schema.TypeString,
Computed: true,
},
"total_upload": {
Type: schema.TypeString,
Computed: true,
},
"transfer_acceleration": {
Type: schema.TypeBool,
Computed: true,
},
"used": {
Type: schema.TypeString,
Computed: true,
},
"windows_acl": {
Type: schema.TypeBool,
Computed: true,
},
"bypass_cache_read": {
Type: schema.TypeBool,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCloudStorageGatewayGatewayFileSharesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeGatewayFileShares"
request := make(map[string]interface{})
request["GatewayId"] = d.Get("gateway_id")
request["Refresh"] = true
var objects []map[string]interface{}
var gatewayFileShareNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
gatewayFileShareNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cloud_storage_gateway_gateway_file_shares", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.FileShares.FileShare", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.FileShares.FileShare", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if gatewayFileShareNameRegex != nil && !gatewayFileShareNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(request["GatewayId"], ":", item["IndexId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"access_based_enumeration": object["AccessBasedEnumeration"],
"address": object["Address"],
"backend_limit": formatInt(object["BeLimit"]),
"browsable": object["Browsable"],
"bucket_infos": object["BucketInfos"],
"buckets_stub": object["BucketsStub"],
"cache_mode": object["CacheMode"],
"client_side_cmk": object["ClientSideCmk"],
"client_side_encryption": object["ClientSideEncryption"],
"direct_io": object["DirectIO"],
"disk_id": object["DiskId"],
"disk_type": object["DiskType"],
"download_limit": formatInt(object["DownloadLimit"]),
"enabled": object["Enabled"],
"fast_reclaim": object["FastReclaim"],
"fe_limit": formatInt(object["FeLimit"]),
"file_num_limit": fmt.Sprint(object["FileNumLimit"]),
"fs_size_limit": fmt.Sprint(object["FsSizeLimit"]),
"gateway_file_share_name": object["Name"],
"gateway_id": request["GatewayId"],
"ignore_delete": object["IgnoreDelete"],
"in_place": object["InPlace"],
"in_rate": fmt.Sprint(object["InRate"]),
"id": fmt.Sprint(request["GatewayId"], ":", object["IndexId"]),
"index_id": fmt.Sprint(object["IndexId"]),
"kms_rotate_period": formatInt(object["KmsRotatePeriod"]),
"lag_period": fmt.Sprint(object["LagPeriod"]),
"local_path": object["LocalPath"],
"mns_health": object["MnsHealth"],
"nfs_v4_optimization": object["NfsV4Optimization"],
"obsolete_buckets": object["ObsoleteBuckets"],
"oss_bucket_name": object["OssBucketName"],
"oss_bucket_ssl": object["OssBucketSsl"],
"oss_endpoint": object["OssEndpoint"],
"oss_health": object["OssHealth"],
"oss_used": fmt.Sprint(object["OssUsed"]),
"out_rate": fmt.Sprint(object["OutRate"]),
"partial_sync_paths": object["PartialSyncPaths"],
"path_prefix": object["PathPrefix"],
"polling_interval": formatInt(object["PollingInterval"]),
"protocol": object["Protocol"],
"remaining_meta_space": fmt.Sprint(object["RemainingMetaSpace"]),
"remote_sync": object["RemoteSync"],
"remote_sync_download": object["RemoteSyncDownload"],
"server_side_encryption": object["ServerSideEncryption"],
"size": fmt.Sprint(object["Size"]),
"squash": object["Squash"],
"state": object["State"],
"support_archive": object["SupportArchive"],
"sync_progress": formatInt(object["SyncProgress"]),
"total_download": fmt.Sprint(object["TotalDownload"]),
"total_upload": fmt.Sprint(object["TotalUpload"]),
"transfer_acceleration": object["TransferAcceleration"],
"used": fmt.Sprint(object["Used"]),
"windows_acl": object["WindowsAcl"],
"bypass_cache_read": object["BypassCacheRead"],
}
if v, ok := object["ExpressSyncId"]; ok {
mapping["express_sync_id"] = v
}
if v, ok := object["RoUserList"]; ok {
mapping["ro_user_list"] = v
}
if v, ok := object["RoClientList"]; ok {
mapping["ro_client_list"] = v
}
if v, ok := object["ServerSideCmk"]; ok {
mapping["server_side_cmk"] = v
}
if v, ok := object["RwUserList"]; ok {
mapping["rw_user_list"] = v
}
if v, ok := object["RwClientList"]; ok {
mapping["rw_client_list"] = v
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("shares", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudCloudStorageGatewayGatewaySmbUsers() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCloudStorageGatewayGatewaySmbUsersRead,
Schema: map[string]*schema.Schema{
"gateway_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"users": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"gateway_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"username": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCloudStorageGatewayGatewaySmbUsersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeGatewaySMBUsers"
request := make(map[string]interface{})
request["GatewayId"] = d.Get("gateway_id")
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
nameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cloud_storage_gateway_gateway_smb_users", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.Users.User", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Users.User", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if nameRegex != nil && !nameRegex.MatchString(fmt.Sprint(item["Username"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(request["GatewayId"], ":", item["Username"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"gateway_id": request["GatewayId"],
"id": fmt.Sprint(request["GatewayId"], ":", object["Username"]),
"username": fmt.Sprint(object["Username"]),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("users", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCloudStorageGatewayGateways() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCloudStorageGatewayGatewaysRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Deactivated", "Rebooting", "Failed", "Starting", "Stopped", "Unknown", "Stopping", "Activated", "Deleting", "Deploying", "Initialized", "Modifying", "Running", "Upgrading"}, false),
},
"storage_bundle_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"page_number": {
Type: schema.TypeInt,
Optional: true,
},
"page_size": {
Type: schema.TypeInt,
Optional: true,
Default: 50,
},
"gateways": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"activated_time": {
Type: schema.TypeString,
Computed: true,
},
"buy_url": {
Type: schema.TypeString,
Computed: true,
},
"category": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"ecs_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"expire_status": {
Type: schema.TypeInt,
Computed: true,
},
"expired_time": {
Type: schema.TypeString,
Computed: true,
},
"gateway_class": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"gateway_id": {
Type: schema.TypeString,
Computed: true,
},
"gateway_name": {
Type: schema.TypeString,
Computed: true,
},
"gateway_version": {
Type: schema.TypeString,
Computed: true,
},
"inner_ip": {
Type: schema.TypeString,
Computed: true,
},
"ip": {
Type: schema.TypeString,
Computed: true,
},
"is_release_after_expiration": {
Type: schema.TypeBool,
Computed: true,
},
"location": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"public_network_bandwidth": {
Type: schema.TypeInt,
Computed: true,
},
"renew_url": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"storage_bundle_id": {
Type: schema.TypeString,
Computed: true,
},
"task_id": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"total_count": {
Type: schema.TypeInt,
Computed: true,
},
},
}
}
func dataSourceAlicloudCloudStorageGatewayGatewaysRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeGateways"
request := make(map[string]interface{})
request["StorageBundleId"] = d.Get("storage_bundle_id")
setPagingRequest(d, request, PageSizeLarge)
var objects []interface{}
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
nameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cloud_storage_gateway_gateways", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.Gateways.Gateway", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Gateways.Gateway", response)
}
result, _ := resp.([]interface{})
if isPagingRequest(d) {
objects = result
break
}
for _, v := range result {
item := v.(map[string]interface{})
if nameRegex != nil && !nameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["GatewayId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, v := range objects {
object := v.(map[string]interface{})
mapping := map[string]interface{}{
"activated_time": fmt.Sprint(object["ActivatedTime"]),
"buy_url": object["BuyURL"],
"category": object["Category"],
"create_time": fmt.Sprint(object["CreatedTime"]),
"description": object["Description"],
"ecs_instance_id": object["EcsInstanceId"],
"expire_status": formatInt(object["ExpireStatus"]),
"expired_time": fmt.Sprint(object["ExpiredTime"]),
"gateway_class": object["GatewayClass"],
"id": fmt.Sprint(object["GatewayId"]),
"gateway_id": fmt.Sprint(object["GatewayId"]),
"gateway_name": object["Name"],
"gateway_version": object["GatewayVersion"],
"inner_ip": object["InnerIp"],
"ip": object["Ip"],
"is_release_after_expiration": object["IsReleaseAfterExpiration"],
"location": object["Location"],
"payment_type": convertCsgGatewayPaymentTypeResp(object["IsPostPaid"].(bool)),
"public_network_bandwidth": formatInt(object["PublicNetworkBandwidth"]),
"renew_url": object["RenewURL"],
"status": object["Status"],
"storage_bundle_id": object["StorageBundleId"],
"task_id": object["TaskId"],
"type": object["Type"],
"vswitch_id": object["VSwitchId"],
"vpc_id": object["VpcId"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("gateways", s); err != nil {
return WrapError(err)
}
if err := d.Set("total_count", formatInt(response["TotalCount"])); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCloudStorageGatewayService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCloudStorageGatewayServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudCloudStorageGatewayServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("CloudStorageGatewayServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
action := "OpenSgwService"
conn, err := meta.(*connectivity.AliyunClient).NewTeaCommonClient(connectivity.OpenCloudStorageGatewayService)
if err != nil {
return WrapError(err)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, nil, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"QPS Limit Exceeded"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
addDebug(action, response, nil)
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"OrderOpend"}) {
d.SetId("CloudStorageGatewayServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cloud_storage_gateway_service", action, AlibabaCloudSdkGoERROR)
}
d.SetId("CloudStorageGatewayServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
package alicloud
import (
"fmt"
"strconv"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCloudStorageGatewayStocks() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCloudStorageGatewayStocksRead,
Schema: map[string]*schema.Schema{
"gateway_class": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Basic", "Standard", "Enhanced", "Advanced"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"stocks": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
"available_gateway_classes": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
},
}
}
func dataSourceAlicloudCloudStorageGatewayStocksRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeGatewayStock"
request := make(map[string]interface{})
request["GatewayRegionId"] = client.RegionId
gatewayClass, gatewayClassOk := d.GetOk("gateway_class")
var objects []map[string]interface{}
var response map[string]interface{}
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cloud_storage_gateway_stocks", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.Stocks.Stock", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Stocks.Stock", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
stockInfo, _ := convertJsonStringToMap(item["StockInfo"].(string))
if gatewayClassOk && gatewayClass.(string) != "" && !stockInfo[gatewayClass.(string)].(bool) {
continue
}
stockInfoKeys := make([]string, 0)
for k, v := range stockInfo {
if v.(bool) {
stockInfoKeys = append(stockInfoKeys, k)
}
}
if len(stockInfoKeys) > 0 {
object := map[string]interface{}{
"zone_id": fmt.Sprint(item["ZoneId"]),
"available_gateway_classes": stockInfoKeys,
}
objects = append(objects, object)
}
}
d.SetId(strconv.FormatInt(time.Now().Unix(), 16))
if err := d.Set("stocks", objects); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), objects)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCloudStorageGatewayStorageBundles() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCloudStorageGatewayStorageBundlesRead,
Schema: map[string]*schema.Schema{
"backend_bucket_region_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"page_number": {
Type: schema.TypeInt,
Optional: true,
},
"page_size": {
Type: schema.TypeInt,
Optional: true,
Default: 50,
},
"bundles": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Computed: true,
},
"location": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"storage_bundle_id": {
Type: schema.TypeString,
Computed: true,
},
"storage_bundle_name": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"total_count": {
Type: schema.TypeInt,
Computed: true,
},
},
}
}
func dataSourceAlicloudCloudStorageGatewayStorageBundlesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeStorageBundles"
request := make(map[string]interface{})
request["BackendBucketRegionId"] = d.Get("backend_bucket_region_id")
setPagingRequest(d, request, PageSizeLarge)
var objects []interface{}
var storageBundleNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
storageBundleNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cloud_storage_gateway_storage_bundles", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.StorageBundles.StorageBundle", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.StorageBundles.StorageBundle", response)
}
result, _ := resp.([]interface{})
if isPagingRequest(d) {
objects = result
break
}
for _, v := range result {
item := v.(map[string]interface{})
if storageBundleNameRegex != nil {
if !storageBundleNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["StorageBundleId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, v := range objects {
object := v.(map[string]interface{})
mapping := map[string]interface{}{
"description": object["Description"],
"location": object["Location"],
"id": fmt.Sprint(object["StorageBundleId"]),
"storage_bundle_id": fmt.Sprint(object["StorageBundleId"]),
"storage_bundle_name": object["Name"],
"create_time": object["CreatedTime"],
}
ids = append(ids, fmt.Sprint(object["StorageBundleId"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("bundles", s); err != nil {
return WrapError(err)
}
if err := d.Set("total_count", formatInt(response["TotalCount"])); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudCloudauthFaceConfigs() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCloudauthFaceConfigsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"configs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"biz_name": {
Type: schema.TypeString,
Computed: true,
},
"biz_type": {
Type: schema.TypeString,
Computed: true,
},
"gmt_updated": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCloudauthFaceConfigsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeFaceConfig"
request := make(map[string]interface{})
var objects []map[string]interface{}
var configNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
configNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewCloudauthClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-07"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cloudauth_face_configs", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Items", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Items", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if configNameRegex != nil && !configNameRegex.MatchString(fmt.Sprint(item["BizName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["BizType"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"biz_name": object["BizName"],
"biz_type": object["BizType"],
"gmt_updated": object["GmtUpdated"],
}
ids = append(ids, fmt.Sprint(object["BizType"]))
names = append(names, fmt.Sprint(mapping["BizName"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("configs", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cms"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCmsAlarmContactGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCmsAlarmContactGroupsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"alarm_contact_group_name": {
Type: schema.TypeString,
Computed: true,
},
"contacts": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"describe": {
Type: schema.TypeString,
Computed: true,
},
"enable_subscribed": {
Type: schema.TypeBool,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCmsAlarmContactGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cms.CreateDescribeContactGroupListRequest()
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var objects []cms.ContactGroup
var alarmContactGroupNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
alarmContactGroupNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response *cms.DescribeContactGroupListResponse
for {
raw, err := client.WithCmsClient(func(cmsClient *cms.Client) (interface{}, error) {
return cmsClient.DescribeContactGroupList(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cms_alarm_contact_groups", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ = raw.(*cms.DescribeContactGroupListResponse)
for _, item := range response.ContactGroupList.ContactGroup {
if alarmContactGroupNameRegex != nil {
if !alarmContactGroupNameRegex.MatchString(item.Name) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[item.Name]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(response.ContactGroupList.ContactGroup) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
ids := make([]string, 0)
names := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": object.Name,
"alarm_contact_group_name": object.Name,
"contacts": object.Contacts.Contact,
"describe": object.Describe,
"enable_subscribed": object.EnableSubscribed,
}
ids = append(ids, object.Name)
names = append(names, object.Name)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cms"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCmsAlarmContacts() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCmsAlarmContactsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"chanel_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"chanel_value": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"contacts": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"alarm_contact_name": {
Type: schema.TypeString,
Computed: true,
},
"channels_aliim": {
Type: schema.TypeString,
Computed: true,
},
"channels_ding_web_hook": {
Type: schema.TypeString,
Computed: true,
},
"channels_mail": {
Type: schema.TypeString,
Computed: true,
},
"channels_sms": {
Type: schema.TypeString,
Computed: true,
},
"channels_state_aliim": {
Type: schema.TypeString,
Computed: true,
},
"channels_state_ding_web_hook": {
Type: schema.TypeString,
Computed: true,
},
"channels_state_mail": {
Type: schema.TypeString,
Computed: true,
},
"channels_status_sms": {
Type: schema.TypeString,
Computed: true,
},
"contact_groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"describe": {
Type: schema.TypeString,
Computed: true,
},
"lang": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCmsAlarmContactsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cms.CreateDescribeContactListRequest()
if v, ok := d.GetOk("chanel_type"); ok {
request.ChanelType = v.(string)
}
if v, ok := d.GetOk("chanel_value"); ok {
request.ChanelValue = v.(string)
}
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var objects []cms.Contact
var alarmContactNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
alarmContactNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response *cms.DescribeContactListResponse
for {
raw, err := client.WithCmsClient(func(cmsClient *cms.Client) (interface{}, error) {
return cmsClient.DescribeContactList(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cms_alarm_contacts", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ = raw.(*cms.DescribeContactListResponse)
for _, item := range response.Contacts.Contact {
if alarmContactNameRegex != nil {
if !alarmContactNameRegex.MatchString(item.Name) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[item.Name]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(response.Contacts.Contact) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
ids := make([]string, 0)
names := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": object.Name,
"alarm_contact_name": object.Name,
"channels_aliim": object.Channels.AliIM,
"channels_ding_web_hook": object.Channels.DingWebHook,
"channels_mail": object.Channels.Mail,
"channels_sms": object.Channels.SMS,
"channels_state_aliim": object.ChannelsState.AliIM,
"channels_state_ding_web_hook": object.ChannelsState.DingWebHook,
"channels_state_mail": object.ChannelsState.Mail,
"channels_status_sms": object.ChannelsState.SMS,
"contact_groups": object.ContactGroups.ContactGroup,
"describe": object.Desc,
"lang": object.Lang,
}
ids = append(ids, object.Name)
names = append(names, object.Name)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("contacts", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCmsDynamicTagGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCmsDynamicTagGroupsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"FINISH", "RUNNING"}, false),
},
"tag_key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"match_express": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"tag_value": {
Type: schema.TypeString,
Computed: true,
},
"tag_value_match_function": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"dynamic_tag_rule_id": {
Type: schema.TypeString,
Computed: true,
},
"match_express_filter_relation": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tag_key": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCmsDynamicTagGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDynamicTagRuleList"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("tag_key"); ok {
request["TagKey"] = v.(string)
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewCmsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cms_dynamic_tag_groups", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.TagGroupList.TagGroup", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.TagGroupList.TagGroup", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DynamicTagRuleId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["DynamicTagRuleId"]),
"dynamic_tag_rule_id": fmt.Sprint(object["DynamicTagRuleId"]),
"match_express_filter_relation": object["MatchExpressFilterRelation"],
"status": object["Status"],
"tag_key": object["TagKey"],
}
if matchExpressMap, ok := object["MatchExpress"]; ok && matchExpressMap != nil {
resourceData := make([]map[string]interface{}, 0)
for _, matchExpressListItem := range matchExpressMap.(map[string]interface{}) {
for _, val := range matchExpressListItem.([]interface{}) {
matchExpressObject := make(map[string]interface{}, 0)
matchExpressObject["tag_value"] = val.(map[string]interface{})["TagValue"]
matchExpressObject["tag_value_match_function"] = val.(map[string]interface{})["TagValueMatchFunction"]
resourceData = append(resourceData, matchExpressObject)
}
}
mapping["match_express"] = resourceData
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCmsGroupMetricRules() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCmsGroupMetricRulesRead,
Schema: map[string]*schema.Schema{
"dimensions": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"enable_state": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"group_metric_rule_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"metric_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"namespace": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ALARM", "INSUFFICIENT_DATA", "OK"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"contact_groups": {
Type: schema.TypeString,
Computed: true,
},
"dimensions": {
Type: schema.TypeString,
Computed: true,
},
"effective_interval": {
Type: schema.TypeString,
Computed: true,
},
"email_subject": {
Type: schema.TypeString,
Computed: true,
},
"enable_state": {
Type: schema.TypeBool,
Computed: true,
},
"escalations": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"critical": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"comparison_operator": {
Type: schema.TypeString,
Computed: true,
},
"statistics": {
Type: schema.TypeString,
Computed: true,
},
"threshold": {
Type: schema.TypeString,
Computed: true,
},
"times": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"info": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"comparison_operator": {
Type: schema.TypeString,
Computed: true,
},
"statistics": {
Type: schema.TypeString,
Computed: true,
},
"threshold": {
Type: schema.TypeString,
Computed: true,
},
"times": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"warn": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"comparison_operator": {
Type: schema.TypeString,
Computed: true,
},
"statistics": {
Type: schema.TypeString,
Computed: true,
},
"threshold": {
Type: schema.TypeString,
Computed: true,
},
"times": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
},
},
"group_id": {
Type: schema.TypeString,
Computed: true,
},
"group_metric_rule_name": {
Type: schema.TypeString,
Computed: true,
},
"metric_name": {
Type: schema.TypeString,
Computed: true,
},
"namespace": {
Type: schema.TypeString,
Computed: true,
},
"no_effective_interval": {
Type: schema.TypeString,
Computed: true,
},
"period": {
Type: schema.TypeInt,
Computed: true,
},
"resources": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"rule_id": {
Type: schema.TypeString,
Computed: true,
},
"silence_time": {
Type: schema.TypeInt,
Computed: true,
},
"source_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"webhook": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCmsGroupMetricRulesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeMetricRuleList"
request := make(map[string]interface{})
if v, ok := d.GetOk("dimensions"); ok {
request["Dimensions"] = v
}
if v, ok := d.GetOkExists("enable_state"); ok {
request["EnableState"] = v
}
if v, ok := d.GetOk("group_id"); ok {
request["GroupId"] = v
}
if v, ok := d.GetOk("group_metric_rule_name"); ok {
request["RuleName"] = v
}
if v, ok := d.GetOk("metric_name"); ok {
request["MetricName"] = v
}
if v, ok := d.GetOk("namespace"); ok {
request["Namespace"] = v
}
if v, ok := d.GetOk("status"); ok {
request["AlertState"] = v
}
request["PageSize"] = PageSizeLarge
request["Page"] = 1
var objects []map[string]interface{}
var groupMetricRuleNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
groupMetricRuleNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewCmsClient()
if err != nil {
return WrapError(err)
}
for {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cms_group_metric_rules", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Alarms.Alarm", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Alarms.Alarm", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if groupMetricRuleNameRegex != nil {
if !groupMetricRuleNameRegex.MatchString(item["RuleName"].(string)) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["RuleId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["Page"] = request["Page"].(int) + 1
}
ids := make([]string, 0)
names := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"contact_groups": object["ContactGroups"],
"dimensions": object["Dimensions"],
"effective_interval": object["EffectiveInterval"],
"email_subject": object["MailSubject"],
"enable_state": object["EnableState"],
"group_id": object["GroupId"],
"group_metric_rule_name": object["RuleName"],
"metric_name": object["MetricName"],
"namespace": object["Namespace"],
"no_effective_interval": object["NoEffectiveInterval"],
"period": formatInt(object["Period"]),
"resources": object["Resources"],
"id": fmt.Sprint(object["RuleId"]),
"rule_id": fmt.Sprint(object["RuleId"]),
"silence_time": formatInt(object["SilenceTime"]),
"source_type": object["SourceType"],
"status": object["AlertState"],
"webhook": object["Webhook"],
}
escalationsSli := make([]map[string]interface{}, 0)
if len(object["Escalations"].(map[string]interface{})) > 0 {
escalations := object["Escalations"]
escalationsMap := make(map[string]interface{})
criticalSli := make([]map[string]interface{}, 0)
if len(escalations.(map[string]interface{})["Critical"].(map[string]interface{})) > 0 {
critical := escalations.(map[string]interface{})["Critical"]
criticalMap := make(map[string]interface{})
criticalMap["comparison_operator"] = critical.(map[string]interface{})["ComparisonOperator"]
criticalMap["statistics"] = critical.(map[string]interface{})["Statistics"]
criticalMap["threshold"] = critical.(map[string]interface{})["Threshold"]
criticalMap["times"] = critical.(map[string]interface{})["Times"]
criticalSli = append(criticalSli, criticalMap)
}
escalationsMap["critical"] = criticalSli
infoSli := make([]map[string]interface{}, 0)
if len(escalations.(map[string]interface{})["Info"].(map[string]interface{})) > 0 {
info := escalations.(map[string]interface{})["Info"]
infoMap := make(map[string]interface{})
infoMap["comparison_operator"] = info.(map[string]interface{})["ComparisonOperator"]
infoMap["statistics"] = info.(map[string]interface{})["Statistics"]
infoMap["threshold"] = info.(map[string]interface{})["Threshold"]
infoMap["times"] = info.(map[string]interface{})["Times"]
infoSli = append(infoSli, infoMap)
}
escalationsMap["info"] = infoSli
warnSli := make([]map[string]interface{}, 0)
if len(escalations.(map[string]interface{})["Warn"].(map[string]interface{})) > 0 {
warn := escalations.(map[string]interface{})["Warn"]
warnMap := make(map[string]interface{})
warnMap["comparison_operator"] = warn.(map[string]interface{})["ComparisonOperator"]
warnMap["statistics"] = warn.(map[string]interface{})["Statistics"]
warnMap["threshold"] = warn.(map[string]interface{})["Threshold"]
warnMap["times"] = warn.(map[string]interface{})["Times"]
warnSli = append(warnSli, warnMap)
}
escalationsMap["warn"] = warnSli
escalationsSli = append(escalationsSli, escalationsMap)
}
mapping["escalations"] = escalationsSli
ids = append(ids, fmt.Sprint(object["RuleId"]))
names = append(names, object["RuleName"].(string))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("rules", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCmsMetricRuleTemplates() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCmsMetricRuleTemplatesRead,
Schema: map[string]*schema.Schema{
"keyword": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"template_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"metric_rule_template_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"templates": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"alert_templates": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"category": {
Type: schema.TypeString,
Computed: true,
},
"escalations": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"critical": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"comparison_operator": {
Type: schema.TypeString,
Computed: true,
},
"statistics": {
Type: schema.TypeString,
Computed: true,
},
"threshold": {
Type: schema.TypeString,
Computed: true,
},
"times": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"info": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"comparison_operator": {
Type: schema.TypeString,
Computed: true,
},
"statistics": {
Type: schema.TypeString,
Computed: true,
},
"threshold": {
Type: schema.TypeString,
Computed: true,
},
"times": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"warn": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"comparison_operator": {
Type: schema.TypeString,
Computed: true,
},
"statistics": {
Type: schema.TypeString,
Computed: true,
},
"threshold": {
Type: schema.TypeString,
Computed: true,
},
"times": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
"metric_name": {
Type: schema.TypeString,
Computed: true,
},
"namespace": {
Type: schema.TypeString,
Computed: true,
},
"rule_name": {
Type: schema.TypeString,
Computed: true,
},
"selector": {
Type: schema.TypeString,
Computed: true,
},
"webhook": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"group_id": {
Type: schema.TypeString,
Computed: true,
},
"metric_rule_template_name": {
Type: schema.TypeString,
Computed: true,
},
"rest_version": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"template_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudCmsMetricRuleTemplatesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeMetricRuleTemplateList"
request := make(map[string]interface{})
if v, ok := d.GetOk("keyword"); ok {
request["Keyword"] = v
}
if v, ok := d.GetOk("template_id"); ok {
request["TemplateId"] = v
}
if v, ok := d.GetOk("metric_rule_template_name"); ok {
request["Name"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var metricRuleTemplateNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
metricRuleTemplateNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewCmsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cms_metric_rule_templates", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.Templates.Template", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Templates.Template", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if metricRuleTemplateNameRegex != nil && !metricRuleTemplateNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["TemplateId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"description": object["Description"],
"metric_rule_template_name": object["Name"],
"rest_version": fmt.Sprint(object["RestVersion"]),
"id": fmt.Sprint(object["TemplateId"]),
"template_id": fmt.Sprint(object["TemplateId"]),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["TemplateId"])
cmsService := CmsService{client}
getResp, err := cmsService.DescribeCmsMetricRuleTemplate(id)
if err != nil {
return WrapError(err)
}
alertTemplate := make([]map[string]interface{}, 0)
if alertTemplateList, ok := getResp["AlertTemplates"].(map[string]interface{})["AlertTemplate"].([]interface{}); ok {
for _, v := range alertTemplateList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"category": m1["Category"],
"metric_name": m1["MetricName"],
"namespace": m1["Namespace"],
"rule_name": m1["RuleName"],
"selector": m1["Selector"],
"webhook": m1["Webhook"],
}
alertTemplate = append(alertTemplate, temp1)
}
}
}
mapping["alert_templates"] = alertTemplate
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("templates", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"strings"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudCmsMonitorGroupInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCmsMonitorGroupInstancesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Required: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
MaxItems: 1,
MinItems: 1,
},
"keyword": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"category": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_name": {
Type: schema.TypeString,
Computed: true,
},
"region_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudCmsMonitorGroupInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeMonitorGroupInstances"
request := make(map[string]interface{})
if v, ok := d.GetOk("keyword"); ok {
request["Keyword"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
request["GroupId"] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewCmsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cms_monitor_group_instances", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$", response)
}
objects = append(objects, resp.(map[string]interface{}))
if len(resp.(map[string]interface{})["Resources"].(map[string]interface{})["Resource"].([]interface{})) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{}
resourceMap := make([]map[string]interface{}, 0)
if resourceMapList, ok := object["Resources"].(map[string]interface{})["Resource"].([]interface{}); ok {
for _, v := range resourceMapList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"category": strings.ToLower(m1["Category"].(string)),
"instance_id": m1["InstanceId"],
"instance_name": m1["InstanceName"],
"region_id": m1["RegionId"],
}
resourceMap = append(resourceMap, temp1)
}
}
}
mapping["instances"] = resourceMap
ids = append(ids, request["GroupId"].(string))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCmsMonitorGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCmsMonitorGroupsRead,
Schema: map[string]*schema.Schema{
"dynamic_tag_rule_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"include_template_history": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"keyword": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"monitor_group_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"select_contact_groups": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"tags": tagsSchema(),
"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"custom", "ehpc_cluster", "kubernetes"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"bind_url": {
Type: schema.TypeString,
Computed: true,
},
"contact_groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"dynamic_tag_rule_id": {
Type: schema.TypeString,
Computed: true,
},
"gmt_create": {
Type: schema.TypeInt,
Computed: true,
},
"gmt_modified": {
Type: schema.TypeInt,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"group_id": {
Type: schema.TypeString,
Computed: true,
},
"monitor_group_name": {
Type: schema.TypeString,
Computed: true,
},
"service_id": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"template_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCmsMonitorGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeMonitorGroups"
request := make(map[string]interface{})
if v, ok := d.GetOk("dynamic_tag_rule_id"); ok {
request["DynamicTagRuleId"] = v
}
if v, ok := d.GetOkExists("include_template_history"); ok {
request["IncludeTemplateHistory"] = v
}
if v, ok := d.GetOk("keyword"); ok {
request["Keyword"] = v
}
if v, ok := d.GetOk("monitor_group_name"); ok {
request["GroupName"] = v
}
if v, ok := d.GetOkExists("select_contact_groups"); ok {
request["SelectContactGroups"] = v
}
if v, ok := d.GetOk("tags"); ok {
tags := make([]map[string]interface{}, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, map[string]interface{}{
"Key": key,
"Value": value.(string),
})
}
request["Tag"] = tags
}
if v, ok := d.GetOk("type"); ok {
request["Type"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var monitorGroupNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
monitorGroupNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewCmsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cms_monitor_groups", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Resources.Resource", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Resources.Resource", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if monitorGroupNameRegex != nil {
if !monitorGroupNameRegex.MatchString(fmt.Sprint(item["GroupName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["GroupId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"bind_url": object["BindUrl"],
"dynamic_tag_rule_id": object["DynamicTagRuleId"],
"gmt_create": formatInt(object["GmtCreate"]),
"gmt_modified": formatInt(object["GmtModified"]),
"id": fmt.Sprint(formatInt(object["GroupId"])),
"group_id": fmt.Sprint(formatInt(object["GroupId"])),
"monitor_group_name": object["GroupName"],
"service_id": object["ServiceId"],
"template_ids": object["TemplateIds"].(map[string]interface{})["TemplateId"],
"type": object["Type"],
}
if v := object["ContactGroups"].(map[string]interface{})["ContactGroup"].([]interface{}); len(v) > 0 {
var contactGroups []interface{}
if v, ok := object["ContactGroups"].(map[string]interface{})["ContactGroup"]; ok {
for _, contactGroup := range v.([]interface{}) {
contactGroups = append(contactGroups, contactGroup.(map[string]interface{})["Name"])
}
}
mapping["contact_groups"] = contactGroups
}
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags.Tag", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["Key"].(string)
value := t.(map[string]interface{})["Value"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
ids = append(ids, fmt.Sprint(object["GroupId"]))
names = append(names, object["GroupName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCmsService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCmsServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudCmsServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("CmsServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
action := "OpenCmsService"
request := map[string]interface{}{}
conn, err := meta.(*connectivity.AliyunClient).NewTeaCommonClient(connectivity.OpenCmsService)
if err != nil {
return WrapError(err)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"QPS Limit Exceeded"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
addDebug(action, response, nil)
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ORDER.OPEND", "Has.effect.suit"}) {
d.SetId("CmsServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cms_service", action, AlibabaCloudSdkGoERROR)
}
d.SetId("CmsServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
package alicloud
import (
"bytes"
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/helper/hashcode"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
// Generates a hash for the set hash function used by the ID
func dataResourceIdHash(ids []string) string {
var buf bytes.Buffer
for _, id := range ids {
buf.WriteString(fmt.Sprintf("%s-", id))
}
return fmt.Sprintf("%d", hashcode.String(buf.String()))
}
func outputInstancesSchema() map[string]*schema.Schema {
return map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_name": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"image_id": {
Type: schema.TypeString,
Computed: true,
},
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"availability_zone": {
Type: schema.TypeString,
Computed: true,
},
"instance_type": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"public_ip": {
Type: schema.TypeString,
Computed: true,
},
"private_ip": {
Type: schema.TypeString,
Computed: true,
},
"key_name": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
}
}
func outputShortVpcsSchema() map[string]*schema.Schema {
return map[string]*schema.Schema{
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_name": {
Type: schema.TypeString,
Computed: true,
},
}
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCommonBandwidthPackages() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCommonBandwidthPackagesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"bandwidth_package_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"include_reservation_data": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "Pending"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"packages": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"bandwidth": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"bandwidth_package_id": {
Type: schema.TypeString,
Computed: true,
},
"bandwidth_package_name": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"business_status": {
Type: schema.TypeString,
Computed: true,
},
"deletion_protection": {
Type: schema.TypeBool,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"expired_time": {
Type: schema.TypeString,
Computed: true,
},
"has_reservation_data": {
Type: schema.TypeBool,
Computed: true,
},
"isp": {
Type: schema.TypeString,
Computed: true,
},
"internet_charge_type": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"public_ip_addresses": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"allocation_id": {
Type: schema.TypeString,
Computed: true,
},
"bandwidth_package_ip_relation_status": {
Type: schema.TypeString,
Computed: true,
},
"ip_address": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"ratio": {
Type: schema.TypeInt,
Computed: true,
},
"reservation_active_time": {
Type: schema.TypeString,
Computed: true,
},
"reservation_bandwidth": {
Type: schema.TypeString,
Computed: true,
},
"reservation_internet_charge_type": {
Type: schema.TypeString,
Computed: true,
},
"reservation_order_type": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"service_managed": {
Type: schema.TypeInt,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCommonBandwidthPackagesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeCommonBandwidthPackages"
request := make(map[string]interface{})
if v, ok := d.GetOk("bandwidth_package_name"); ok {
request["Name"] = v
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
if v, ok := d.GetOkExists("include_reservation_data"); ok {
request["IncludeReservationData"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var bandwidthPackageNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
bandwidthPackageNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_common_bandwidth_packages", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.CommonBandwidthPackages.CommonBandwidthPackage", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.CommonBandwidthPackages.CommonBandwidthPackage", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if bandwidthPackageNameRegex != nil {
if !bandwidthPackageNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["BandwidthPackageId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"bandwidth": object["Bandwidth"],
"id": fmt.Sprint(object["BandwidthPackageId"]),
"bandwidth_package_id": fmt.Sprint(object["BandwidthPackageId"]),
"bandwidth_package_name": object["Name"],
"name": object["Name"],
"business_status": object["BusinessStatus"],
"deletion_protection": object["DeletionProtection"],
"description": object["Description"],
"expired_time": object["ExpiredTime"],
"has_reservation_data": object["HasReservationData"],
"isp": object["ISP"],
"internet_charge_type": object["InternetChargeType"],
"payment_type": object["InstanceChargeType"],
"ratio": formatInt(object["Ratio"]),
"reservation_active_time": object["ReservationActiveTime"],
"reservation_bandwidth": object["ReservationBandwidth"],
"reservation_internet_charge_type": object["ReservationInternetChargeType"],
"reservation_order_type": object["ReservationOrderType"],
"resource_group_id": object["ResourceGroupId"],
"service_managed": formatInt(object["ServiceManaged"]),
"status": object["Status"],
}
publicIpAddresse := make([]map[string]interface{}, 0)
if publicIpAddresseList, ok := object["PublicIpAddresses"].(map[string]interface{})["PublicIpAddresse"].([]interface{}); ok {
for _, v := range publicIpAddresseList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"allocation_id": m1["AllocationId"],
"bandwidth_package_ip_relation_status": m1["BandwidthPackageIpRelationStatus"],
"ip_address": m1["IpAddress"],
}
publicIpAddresse = append(publicIpAddresse, temp1)
}
}
}
mapping["public_ip_addresses"] = publicIpAddresse
ids = append(ids, fmt.Sprint(object["BandwidthPackageId"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("packages", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudConfigAggregateCompliancePacks() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudConfigAggregateCompliancePacksRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"aggregator_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ACTIVE", "CREATING", "INACTIVE"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"packs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_id": {
Type: schema.TypeString,
Computed: true,
},
"aggregate_compliance_pack_name": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"aggregator_compliance_pack_id": {
Type: schema.TypeString,
Computed: true,
},
"compliance_pack_template_id": {
Type: schema.TypeString,
Computed: true,
},
"config_rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"config_rule_id": {
Type: schema.TypeString,
Computed: true,
},
"config_rule_parameters": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"parameter_name": {
Type: schema.TypeString,
Computed: true,
},
"parameter_value": {
Type: schema.TypeString,
Computed: true,
},
"required": {
Type: schema.TypeBool,
Computed: true,
},
},
},
},
"managed_rule_identifier": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"risk_level": {
Type: schema.TypeInt,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudConfigAggregateCompliancePacksRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListAggregateCompliancePacks"
request := make(map[string]interface{})
request["AggregatorId"] = d.Get("aggregator_id")
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var aggregateCompliancePackNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
aggregateCompliancePackNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2020-09-07"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_config_aggregate_compliance_packs", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.CompliancePacksResult.CompliancePacks", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.CompliancePacksResult.CompliancePacks", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if aggregateCompliancePackNameRegex != nil {
if !aggregateCompliancePackNameRegex.MatchString(fmt.Sprint(item["CompliancePackName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["CompliancePackId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"account_id": fmt.Sprint(object["AccountId"]),
"aggregate_compliance_pack_name": object["CompliancePackName"],
"id": fmt.Sprint(object["CompliancePackId"]),
"aggregator_compliance_pack_id": fmt.Sprint(object["CompliancePackId"]),
"compliance_pack_template_id": object["CompliancePackTemplateId"],
"description": object["Description"],
"risk_level": formatInt(object["RiskLevel"]),
"status": object["Status"],
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["CompliancePackName"])
s = append(s, mapping)
continue
}
configService := ConfigService{client}
id := fmt.Sprint(object["AggregatorId"], ":", object["CompliancePackId"])
getResp, err := configService.DescribeConfigAggregateCompliancePack(id)
if err != nil {
return WrapError(err)
}
configRules := make([]map[string]interface{}, 0)
if configRulesList, ok := getResp["ConfigRules"].([]interface{}); ok {
for _, v := range configRulesList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"config_rule_id": m1["ConfigRuleId"],
"managed_rule_identifier": m1["ManagedRuleIdentifier"],
}
if m1["ConfigRuleParameters"] != nil {
configRuleParametersMaps := make([]map[string]interface{}, 0)
for _, configRuleParametersValue := range m1["ConfigRuleParameters"].([]interface{}) {
configRuleParameters := configRuleParametersValue.(map[string]interface{})
configRuleParametersMap := map[string]interface{}{
"parameter_name": configRuleParameters["ParameterName"],
"parameter_value": configRuleParameters["ParameterValue"],
"required": configRuleParameters["Required"],
}
configRuleParametersMaps = append(configRuleParametersMaps, configRuleParametersMap)
}
temp1["config_rule_parameters"] = configRuleParametersMaps
}
configRules = append(configRules, temp1)
}
}
}
mapping["config_rules"] = configRules
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["CompliancePackName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("packs", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudConfigAggregateConfigRules() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudConfigAggregateConfigRulesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"aggregate_config_rule_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"aggregator_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"risk_level": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3}),
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ACTIVE", "DELETING", "EVALUATING", "INACTIVE"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_id": {
Type: schema.TypeString,
Computed: true,
},
"aggregator_id": {
Type: schema.TypeString,
Computed: true,
},
"aggregate_config_rule_name": {
Type: schema.TypeString,
Computed: true,
},
"compliance": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"compliance_type": {
Type: schema.TypeString,
Computed: true,
},
"count": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"compliance_pack_id": {
Type: schema.TypeString,
Computed: true,
},
"config_rule_arn": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"config_rule_id": {
Type: schema.TypeString,
Computed: true,
},
"config_rule_trigger_types": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"event_source": {
Type: schema.TypeString,
Computed: true,
},
"exclude_resource_ids_scope": {
Type: schema.TypeString,
Computed: true,
},
"input_parameters": {
Type: schema.TypeMap,
Computed: true,
},
"maximum_execution_frequency": {
Type: schema.TypeString,
Computed: true,
},
"modified_timestamp": {
Type: schema.TypeString,
Computed: true,
},
"region_ids_scope": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_ids_scope": {
Type: schema.TypeString,
Computed: true,
},
"resource_types_scope": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"risk_level": {
Type: schema.TypeInt,
Computed: true,
},
"source_identifier": {
Type: schema.TypeString,
Computed: true,
},
"source_owner": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tag_key_scope": {
Type: schema.TypeString,
Computed: true,
},
"tag_value_scope": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudConfigAggregateConfigRulesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListAggregateConfigRules"
request := make(map[string]interface{})
if v, ok := d.GetOk("aggregate_config_rule_name"); ok {
request["ConfigRuleName"] = v
}
request["AggregatorId"] = d.Get("aggregator_id")
if v, ok := d.GetOk("risk_level"); ok {
request["RiskLevel"] = v
}
if v, ok := d.GetOk("status"); ok {
request["ConfigRuleState"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var aggregateConfigRuleNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
aggregateConfigRuleNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2020-09-07"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_config_aggregate_config_rules", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.ConfigRules.ConfigRuleList", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.ConfigRules.ConfigRuleList", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if aggregateConfigRuleNameRegex != nil {
if !aggregateConfigRuleNameRegex.MatchString(fmt.Sprint(item["ConfigRuleName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ConfigRuleId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"account_id": fmt.Sprint(object["AccountId"]),
"aggregate_config_rule_name": object["ConfigRuleName"],
"compliance_pack_id": object["CreateBy"].(map[string]interface{})["CompliancePackId"],
"config_rule_arn": object["ConfigRuleArn"],
"id": fmt.Sprint(object["ConfigRuleId"]),
"config_rule_id": fmt.Sprint(object["ConfigRuleId"]),
"description": object["Description"],
"risk_level": formatInt(object["RiskLevel"]),
"source_identifier": object["SourceIdentifier"],
"source_owner": object["SourceOwner"],
"status": object["ConfigRuleState"],
}
mapping["compliance"] = []map[string]interface{}{{
"compliance_type": object["Compliance"].(map[string]interface{})["ComplianceType"],
"count": object["Compliance"].(map[string]interface{})["Count"],
}}
mapping["aggregator_id"] = object["CreateBy"].(map[string]interface{})["AggregatorId"]
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["ConfigRuleName"])
s = append(s, mapping)
continue
}
configService := ConfigService{client}
id := fmt.Sprint(request["AggregatorId"], ":", object["ConfigRuleId"])
getResp, err := configService.DescribeConfigAggregateConfigRule(id)
if err != nil {
return WrapError(err)
}
mapping["config_rule_trigger_types"] = getResp["ConfigRuleTriggerTypes"]
mapping["exclude_resource_ids_scope"] = getResp["ExcludeResourceIdsScope"]
mapping["input_parameters"] = getResp["InputParameters"]
mapping["maximum_execution_frequency"] = getResp["MaximumExecutionFrequency"]
mapping["modified_timestamp"] = fmt.Sprint(getResp["ModifiedTimestamp"])
mapping["region_ids_scope"] = getResp["RegionIdsScope"]
mapping["resource_group_ids_scope"] = getResp["ResourceGroupIdsScope"]
mapping["resource_types_scope"] = getResp["Scope"].(map[string]interface{})["ComplianceResourceTypes"]
mapping["tag_key_scope"] = getResp["TagKeyScope"]
mapping["tag_value_scope"] = getResp["TagValueScope"]
if v := getResp["Source"].(map[string]interface{})["SourceDetails"].([]interface{}); len(v) > 0 {
mapping["event_source"] = v[0].(map[string]interface{})["EventSource"]
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["ConfigRuleName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("rules", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudConfigAggregators() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudConfigAggregatorsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Creating", "Deleting", "Normal"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"aggregators": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_id": {
Type: schema.TypeString,
Computed: true,
},
"aggregator_accounts": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_id": {
Type: schema.TypeString,
Computed: true,
},
"account_name": {
Type: schema.TypeString,
Computed: true,
},
"account_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"aggregator_id": {
Type: schema.TypeString,
Computed: true,
},
"aggregator_name": {
Type: schema.TypeString,
Computed: true,
},
"aggregator_type": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudConfigAggregatorsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListAggregators"
request := make(map[string]interface{})
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var aggregatorNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
aggregatorNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2020-09-07"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_config_aggregators", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.AggregatorsResult.Aggregators", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.AggregatorsResult.Aggregators", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if aggregatorNameRegex != nil {
if !aggregatorNameRegex.MatchString(fmt.Sprint(item["AggregatorName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["AggregatorId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != convertConfigAggregatorStatusResponse(formatInt(item["AggregatorStatus"])) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"account_id": fmt.Sprint(object["AccountId"]),
"id": fmt.Sprint(object["AggregatorId"]),
"aggregator_id": fmt.Sprint(object["AggregatorId"]),
"aggregator_name": object["AggregatorName"],
"aggregator_type": object["AggregatorType"],
"description": object["Description"],
"status": convertConfigAggregatorStatusResponse(formatInt(object["AggregatorStatus"])),
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["AggregatorName"])
s = append(s, mapping)
continue
}
configService := ConfigService{client}
id := fmt.Sprint(object["AggregatorId"])
getResp, err := configService.DescribeConfigAggregator(id)
if err != nil {
return WrapError(err)
}
aggregatorAccounts := make([]map[string]interface{}, 0)
if aggregatorAccountsList, ok := getResp["AggregatorAccounts"].([]interface{}); ok {
for _, v := range aggregatorAccountsList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"account_id": fmt.Sprint(m1["AccountId"]),
"account_name": m1["AccountName"],
"account_type": m1["AccountType"],
}
aggregatorAccounts = append(aggregatorAccounts, temp1)
}
}
}
mapping["aggregator_accounts"] = aggregatorAccounts
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["AggregatorName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("aggregators", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudConfigCompliancePacks() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudConfigCompliancePacksRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ACTIVE", "CREATING", "INACTIVE"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"packs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"compliance_pack_id": {
Type: schema.TypeString,
Computed: true,
},
"compliance_pack_name": {
Type: schema.TypeString,
Computed: true,
},
"compliance_pack_template_id": {
Type: schema.TypeString,
Computed: true,
},
"config_rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"config_rule_id": {
Type: schema.TypeString,
Computed: true,
},
"config_rule_parameters": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"parameter_name": {
Type: schema.TypeString,
Computed: true,
},
"parameter_value": {
Type: schema.TypeString,
Computed: true,
},
"required": {
Type: schema.TypeBool,
Computed: true,
},
},
},
},
"managed_rule_identifier": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"risk_level": {
Type: schema.TypeInt,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudConfigCompliancePacksRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListCompliancePacks"
request := make(map[string]interface{})
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var compliancePackNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
compliancePackNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2020-09-07"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_config_compliance_packs", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.CompliancePacksResult.CompliancePacks", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.CompliancePacksResult.CompliancePacks", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if compliancePackNameRegex != nil {
if !compliancePackNameRegex.MatchString(fmt.Sprint(item["CompliancePackName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["CompliancePackId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"account_id": fmt.Sprint(object["AccountId"]),
"id": fmt.Sprint(object["CompliancePackId"]),
"compliance_pack_id": fmt.Sprint(object["CompliancePackId"]),
"compliance_pack_name": object["CompliancePackName"],
"compliance_pack_template_id": object["CompliancePackTemplateId"],
"description": object["Description"],
"risk_level": formatInt(object["RiskLevel"]),
"status": object["Status"],
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["CompliancePackId"]))
names = append(names, object["CompliancePackName"])
s = append(s, mapping)
continue
}
configService := ConfigService{client}
id := fmt.Sprint(object["CompliancePackId"])
getResp, err := configService.DescribeConfigCompliancePack(id)
if err != nil {
return WrapError(err)
}
configRules := make([]map[string]interface{}, 0)
if configRulesList, ok := getResp["ConfigRules"].([]interface{}); ok {
for _, v := range configRulesList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"config_rule_id": m1["ConfigRuleId"],
"managed_rule_identifier": m1["ManagedRuleIdentifier"],
}
if m1["ConfigRuleParameters"] != nil {
configRuleParametersMaps := make([]map[string]interface{}, 0)
for _, configRuleParametersValue := range m1["ConfigRuleParameters"].([]interface{}) {
configRuleParameters := configRuleParametersValue.(map[string]interface{})
configRuleParametersMap := map[string]interface{}{
"parameter_name": configRuleParameters["ParameterName"],
"parameter_value": configRuleParameters["ParameterValue"],
"required": configRuleParameters["Required"],
}
configRuleParametersMaps = append(configRuleParametersMaps, configRuleParametersMap)
}
temp1["config_rule_parameters"] = configRuleParametersMaps
}
configRules = append(configRules, temp1)
}
}
}
mapping["config_rules"] = configRules
ids = append(ids, fmt.Sprint(object["CompliancePackId"]))
names = append(names, object["CompliancePackName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("packs", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"strconv"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudConfigConfigurationRecorders() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudConfigConfigurationRecordersRead,
Schema: map[string]*schema.Schema{
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"recorders": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"account_id": {
Type: schema.TypeString,
Computed: true,
},
"organization_enable_status": {
Type: schema.TypeString,
Computed: true,
},
"organization_master_id": {
Type: schema.TypeInt,
Computed: true,
},
"resource_types": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudConfigConfigurationRecordersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeConfigurationRecorder"
request := make(map[string]interface{})
var response map[string]interface{}
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-01-08"), StringPointer("AK"), request, nil, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_config_configuration_recorders", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
s := make([]map[string]interface{}, 0)
mapping := map[string]interface{}{
"id": fmt.Sprint(formatInt(response["ConfigurationRecorder"].(map[string]interface{})["AccountId"])),
"account_id": fmt.Sprint(formatInt(response["ConfigurationRecorder"].(map[string]interface{})["AccountId"])),
"organization_enable_status": response["ConfigurationRecorder"].(map[string]interface{})["OrganizationEnableStatus"],
"organization_master_id": formatInt(response["ConfigurationRecorder"].(map[string]interface{})["OrganizationMasterId"]),
"resource_types": response["ConfigurationRecorder"].(map[string]interface{})["ResourceTypes"],
"status": response["ConfigurationRecorder"].(map[string]interface{})["ConfigurationRecorderStatus"],
}
s = append(s, mapping)
d.SetId(strconv.FormatInt(time.Now().Unix(), 16))
if err := d.Set("recorders", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudConfigDeliveryChannels() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudConfigDeliveryChannelsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IntInSlice([]int{0, 1}),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"channels": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"delivery_channel_assume_role_arn": {
Type: schema.TypeString,
Computed: true,
},
"delivery_channel_condition": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"delivery_channel_id": {
Type: schema.TypeString,
Computed: true,
},
"delivery_channel_name": {
Type: schema.TypeString,
Computed: true,
},
"delivery_channel_target_arn": {
Type: schema.TypeString,
Computed: true,
},
"delivery_channel_type": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudConfigDeliveryChannelsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDeliveryChannels"
request := make(map[string]interface{})
var objects []map[string]interface{}
var deliveryChannelNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
deliveryChannelNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOkExists("status")
var response map[string]interface{}
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-01-08"), StringPointer("AK"), request, nil, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_config_delivery_channels", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.DeliveryChannels", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.DeliveryChannels", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if deliveryChannelNameRegex != nil {
if !deliveryChannelNameRegex.MatchString(item["DeliveryChannelName"].(string)) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DeliveryChannelId"])]; !ok {
continue
}
}
if statusOk && status.(int) != formatInt(item["Status"]) {
continue
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"delivery_channel_assume_role_arn": object["DeliveryChannelAssumeRoleArn"],
"delivery_channel_condition": object["DeliveryChannelCondition"],
"id": fmt.Sprint(object["DeliveryChannelId"]),
"delivery_channel_id": fmt.Sprint(object["DeliveryChannelId"]),
"delivery_channel_name": object["DeliveryChannelName"],
"delivery_channel_target_arn": object["DeliveryChannelTargetArn"],
"delivery_channel_type": object["DeliveryChannelType"],
"description": object["Description"],
"status": formatInt(object["Status"]),
}
ids = append(ids, fmt.Sprint(object["DeliveryChannelId"]))
names = append(names, object["DeliveryChannelName"].(string))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("channels", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudConfigRules() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudConfigRulesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"config_rule_state": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ACTIVE", "DELETING", "DELETING_RESULTS", "EVALUATING", "INACTIVE"}, false),
Deprecated: "Field 'config_rule_state' has been deprecated from provider version 1.124.1. New field 'status' instead.",
},
"member_id": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Removed: "Field 'member_id' has been removed from provider version 1.146.0. Please Use the Resource alicloud_config_aggregate_config_rule",
},
"message_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ConfigurationItemChangeNotification", "ScheduledNotification", "ConfigurationSnapshotDeliveryCompleted"}, false),
Removed: "Field 'message_type' has been removed from provider version 1.124.1. ",
},
"multi_account": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: false,
Removed: "Field 'multi_account' has been removed from provider version 1.146.0. Please Use the Resource alicloud_config_aggregate_config_rule",
},
"risk_level": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3}),
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"rule_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ACTIVE", "DELETING", "EVALUATING", "INACTIVE"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_id": {
Type: schema.TypeString,
Computed: true,
},
"compliance": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"compliance_type": {
Type: schema.TypeString,
Computed: true,
},
"count": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"compliance_pack_id": {
Type: schema.TypeString,
Computed: true,
},
"config_rule_arn": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"config_rule_id": {
Type: schema.TypeString,
Computed: true,
},
"config_rule_state": {
Type: schema.TypeString,
Computed: true,
},
"config_rule_trigger_types": {
Type: schema.TypeString,
Computed: true,
},
"source_detail_message_type": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"event_source": {
Type: schema.TypeString,
Computed: true,
},
"exclude_resource_ids_scope": {
Type: schema.TypeString,
Computed: true,
},
"input_parameters": {
Type: schema.TypeMap,
Computed: true,
},
"maximum_execution_frequency": {
Type: schema.TypeString,
Computed: true,
},
"source_maximum_execution_frequency": {
Type: schema.TypeString,
Computed: true,
},
"modified_timestamp": {
Type: schema.TypeString,
Computed: true,
},
"region_ids_scope": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_ids_scope": {
Type: schema.TypeString,
Computed: true,
},
"resource_types_scope": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"scope_compliance_resource_types": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"risk_level": {
Type: schema.TypeInt,
Computed: true,
},
"rule_name": {
Type: schema.TypeString,
Computed: true,
},
"source_identifier": {
Type: schema.TypeString,
Computed: true,
},
"source_owner": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tag_key_scope": {
Type: schema.TypeString,
Computed: true,
},
"tag_value_scope": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudConfigRulesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListConfigRules"
request := make(map[string]interface{})
if v, ok := d.GetOk("risk_level"); ok {
request["RiskLevel"] = v
}
if v, ok := d.GetOk("rule_name"); ok {
request["ConfigRuleName"] = v
}
if v, ok := d.GetOk("status"); ok {
request["ConfigRuleState"] = v
} else if v, ok := d.GetOk("config_rule_state"); ok {
request["ConfigRuleState"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var ruleNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
ruleNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(6*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-01-08"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_config_rules", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.ConfigRules.ConfigRuleList", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.ConfigRules.ConfigRuleList", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if ruleNameRegex != nil {
if !ruleNameRegex.MatchString(fmt.Sprint(item["ConfigRuleName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ConfigRuleId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"account_id": fmt.Sprint(object["AccountId"]),
"compliance_pack_id": object["CompliancePackId"],
"config_rule_arn": object["ConfigRuleArn"],
"id": fmt.Sprint(object["ConfigRuleId"]),
"config_rule_id": fmt.Sprint(object["ConfigRuleId"]),
"config_rule_state": object["ConfigRuleState"],
"description": object["Description"],
"risk_level": formatInt(object["RiskLevel"]),
"rule_name": object["ConfigRuleName"],
"source_identifier": object["SourceIdentifier"],
"source_owner": object["SourceOwner"],
"status": object["ConfigRuleState"],
}
complianceSli := make([]map[string]interface{}, 0)
if len(object["Compliance"].(map[string]interface{})) > 0 {
compliance := object["Compliance"]
complianceMap := make(map[string]interface{})
complianceMap["compliance_type"] = compliance.(map[string]interface{})["ComplianceType"]
complianceMap["count"] = compliance.(map[string]interface{})["Count"]
complianceSli = append(complianceSli, complianceMap)
}
mapping["compliance"] = complianceSli
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["ConfigRuleName"])
s = append(s, mapping)
continue
}
configService := ConfigService{client}
id := fmt.Sprint(object["ConfigRuleId"])
getResp, err := configService.DescribeConfigRule(id)
if err != nil {
return WrapError(err)
}
mapping["exclude_resource_ids_scope"] = getResp["ExcludeResourceIdsScope"]
mapping["input_parameters"] = getResp["InputParameters"]
mapping["maximum_execution_frequency"] = getResp["MaximumExecutionFrequency"]
mapping["source_maximum_execution_frequency"] = getResp["MaximumExecutionFrequency"]
mapping["modified_timestamp"] = getResp["ModifiedTimestamp"]
mapping["region_ids_scope"] = getResp["RegionIdsScope"]
mapping["resource_group_ids_scope"] = getResp["ResourceGroupIdsScope"]
mapping["resource_types_scope"] = getResp["Scope"].(map[string]interface{})["ComplianceResourceTypes"]
mapping["scope_compliance_resource_types"] = getResp["Scope"].(map[string]interface{})["ComplianceResourceTypes"]
mapping["tag_key_scope"] = getResp["TagKeyScope"]
mapping["tag_value_scope"] = getResp["TagValueScope"]
if v := getResp["Source"].(map[string]interface{})["SourceDetails"].([]interface{}); len(v) > 0 {
mapping["config_rule_trigger_types"] = v[0].(map[string]interface{})["MessageType"]
mapping["source_detail_message_type"] = v[0].(map[string]interface{})["MessageType"]
mapping["event_source"] = v[0].(map[string]interface{})["EventSource"]
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["ConfigRuleName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("rules", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudCrChartNamespaces() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCrChartNamespacesRead,
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"namespaces": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"auto_create_repo": {
Type: schema.TypeBool,
Computed: true,
},
"chart_namespace_id": {
Type: schema.TypeString,
Computed: true,
},
"default_repo_type": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"namespace_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCrChartNamespacesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListChartNamespace"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
request["InstanceId"] = d.Get("instance_id")
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
nameRegex = regexp.MustCompile(v.(string))
}
var response map[string]interface{}
conn, err := client.NewAcrClient()
if err != nil {
return WrapError(err)
}
pageNo, pageSize := 1, PageSizeLarge
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cr_chart_namespaces", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Namespaces", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Namespaces", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if nameRegex != nil && !nameRegex.MatchString(fmt.Sprint(item["NamespaceName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["InstanceId"], ":", item["NamespaceName"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < pageSize {
break
}
pageNo++
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"auto_create_repo": object["AutoCreateRepo"],
"chart_namespace_id": object["NamespaceId"],
"default_repo_type": object["DefaultRepoType"],
"id": fmt.Sprint(request["InstanceId"], ":", request["NamespaceName"]),
"instance_id": fmt.Sprint(object["InstanceId"]),
"namespace_name": object["NamespaceName"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, mapping["namespace_name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("namespaces", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudCrChartRepositories() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCrChartRepositoriesRead,
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"repositories": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"chart_repository_id": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"repo_name": {
Type: schema.TypeString,
Computed: true,
},
"repo_namespace_name": {
Type: schema.TypeString,
Computed: true,
},
"repo_type": {
Type: schema.TypeString,
Computed: true,
},
"summary": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCrChartRepositoriesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListChartRepository"
request := make(map[string]interface{})
request["InstanceId"] = d.Get("instance_id")
request["RegionId"] = client.RegionId
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
nameRegex = regexp.MustCompile(v.(string))
}
var response map[string]interface{}
conn, err := client.NewAcrClient()
if err != nil {
return WrapError(err)
}
pageNo, pageSize := 1, PageSizeLarge
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cr_chart_repositories", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Repositories", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Repositories", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if nameRegex != nil && !nameRegex.MatchString(fmt.Sprint(item["RepoName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["InstanceId"], ":", item["RepoNamespaceName"], ":", item["RepoName"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < pageSize {
break
}
pageNo++
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"chart_repository_id": object["RepoId"],
"create_time": fmt.Sprint(object["CreateTime"]),
"instance_id": object["InstanceId"],
"id": fmt.Sprint(object["InstanceId"], ":", object["RepoNamespaceName"], ":", object["RepoName"]),
"repo_name": fmt.Sprint(object["RepoName"]),
"repo_namespace_name": object["RepoNamespaceName"],
"repo_type": object["RepoType"],
"summary": object["Summary"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, mapping["repo_name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("repositories", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"sort"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cr_ee"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCrEEInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCrEEInstancesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
// Computed values
"ids": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"region": {
Type: schema.TypeString,
Computed: true,
},
"specification": {
Type: schema.TypeString,
Computed: true,
},
"namespace_quota": {
Type: schema.TypeString,
Computed: true,
},
"namespace_usage": {
Type: schema.TypeString,
Computed: true,
},
"repo_quota": {
Type: schema.TypeString,
Computed: true,
},
"repo_usage": {
Type: schema.TypeString,
Computed: true,
},
"vpc_endpoints": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"public_endpoints": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"authorization_token": {
Type: schema.TypeString,
Computed: true,
},
"temp_username": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCrEEInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
crService := &CrService{client}
pageNo := 1
pageSize := 50
var instances []cr_ee.InstancesItem
for {
resp, err := crService.ListCrEEInstances(pageNo, pageSize)
if err != nil {
return WrapError(err)
}
instances = append(instances, resp.Instances...)
if len(resp.Instances) < pageSize {
break
}
pageNo++
}
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
nameRegex = regexp.MustCompile(v.(string))
}
var idsMap map[string]string
if v, ok := d.GetOk("ids"); ok {
idsMap = make(map[string]string)
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var targetInstances []cr_ee.InstancesItem
for _, instance := range instances {
if nameRegex != nil && !nameRegex.MatchString(instance.InstanceName) {
continue
}
if idsMap != nil && idsMap[instance.InstanceId] == "" {
continue
}
targetInstances = append(targetInstances, instance)
}
instances = targetInstances
sort.SliceStable(instances, func(i, j int) bool {
return instances[i].CreateTime < instances[j].CreateTime
})
var (
ids []string
names []string
instanceMaps []map[string]interface{}
)
for _, instance := range instances {
usageResp, err := crService.GetCrEEInstanceUsage(instance.InstanceId)
if err != nil {
return WrapError(err)
}
endpointResp, err := crService.ListCrEEInstanceEndpoint(instance.InstanceId)
if err != nil {
return WrapError(err)
}
var (
publicDomains []string
vpcDomains []string
)
for _, endpoint := range endpointResp.Endpoints {
if !endpoint.Enable {
continue
}
if endpoint.EndpointType == "internet" {
for _, d := range endpoint.Domains {
publicDomains = append(publicDomains, d.Domain)
}
} else if endpoint.EndpointType == "vpc" {
for _, d := range endpoint.Domains {
vpcDomains = append(vpcDomains, d.Domain)
}
}
}
mapping := make(map[string]interface{})
mapping["id"] = instance.InstanceId
mapping["name"] = instance.InstanceName
mapping["region"] = instance.RegionId
mapping["specification"] = instance.InstanceSpecification
mapping["namespace_quota"] = usageResp.NamespaceQuota
mapping["namespace_usage"] = usageResp.NamespaceUsage
mapping["repo_quota"] = usageResp.RepoQuota
mapping["repo_usage"] = usageResp.RepoUsage
mapping["vpc_endpoints"] = vpcDomains
mapping["public_endpoints"] = publicDomains
ids = append(ids, instance.InstanceId)
names = append(names, instance.InstanceName)
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
instanceMaps = append(instanceMaps, mapping)
continue
}
response := &cr_ee.GetAuthorizationTokenResponse{}
request := cr_ee.CreateGetAuthorizationTokenRequest()
request.InstanceId = instance.InstanceId
action := request.GetActionName()
raw, err := client.WithCrEEClient(func(creeClient *cr_ee.Client) (interface{}, error) {
return creeClient.GetAuthorizationToken(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "data_alicloud_cr_ee_instances", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, raw, request.RpcRequest, request)
response, _ = raw.(*cr_ee.GetAuthorizationTokenResponse)
if !response.GetAuthorizationTokenIsSuccess {
return WrapErrorf(err, DefaultErrorMsg, "data_alicloud_cr_ee_instances", action, AlibabaCloudSdkGoERROR)
}
mapping["authorization_token"] = response.AuthorizationToken
mapping["temp_username"] = response.TempUsername
instanceMaps = append(instanceMaps, mapping)
}
d.SetId(dataResourceIdHash(names))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("instances", instanceMaps); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok {
writeToFile(output.(string), instanceMaps)
}
return nil
}
package alicloud
import (
"regexp"
"sort"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cr_ee"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCrEENamespaces() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCrEENamespacesRead,
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"ids": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"namespaces": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"auto_create": {
Type: schema.TypeBool,
Computed: true,
},
"default_visibility": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCrEENamespacesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
crService := &CrService{client}
pageNo := 1
pageSize := 50
instanceId := d.Get("instance_id").(string)
var namespaces []cr_ee.NamespacesItem
for {
resp, err := crService.ListCrEENamespaces(instanceId, pageNo, pageSize)
if err != nil {
return WrapError(err)
}
namespaces = append(namespaces, resp.Namespaces...)
if len(resp.Namespaces) < pageSize {
break
}
pageNo++
}
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
nameRegex = regexp.MustCompile(v.(string))
}
var idsMap map[string]string
if v, ok := d.GetOk("ids"); ok {
idsMap = make(map[string]string)
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var targetNamespaces []cr_ee.NamespacesItem
for _, namespace := range namespaces {
if nameRegex != nil && !nameRegex.MatchString(namespace.NamespaceName) {
continue
}
if idsMap != nil && idsMap[namespace.NamespaceId] == "" {
continue
}
targetNamespaces = append(targetNamespaces, namespace)
}
namespaces = targetNamespaces
sort.SliceStable(namespaces, func(i, j int) bool {
return namespaces[i].NamespaceName < namespaces[j].NamespaceName
})
var (
ids []string
names []string
namespaceMaps []map[string]interface{}
)
for _, namespace := range namespaces {
mapping := make(map[string]interface{})
mapping["instance_id"] = namespace.InstanceId
mapping["id"] = namespace.NamespaceId
mapping["name"] = namespace.NamespaceName
mapping["auto_create"] = namespace.AutoCreateRepo
mapping["default_visibility"] = namespace.DefaultRepoType
ids = append(ids, namespace.NamespaceId)
names = append(names, namespace.NamespaceName)
namespaceMaps = append(namespaceMaps, mapping)
}
d.SetId(dataResourceIdHash(names))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("namespaces", namespaceMaps); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok {
writeToFile(output.(string), namespaceMaps)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cr_ee"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCrEERepos() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCrEEReposRead,
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"namespace": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
// Computed values
"ids": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"repos": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"namespace": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"summary": {
Type: schema.TypeString,
Computed: true,
},
"repo_type": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"tag": {
Type: schema.TypeString,
Computed: true,
},
"image_id": {
Type: schema.TypeString,
Computed: true,
},
"digest": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"image_size": {
Type: schema.TypeInt,
Computed: true,
},
"image_update": {
Type: schema.TypeString,
Computed: true,
},
"image_create": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudCrEEReposRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
crService := &CrService{client}
pageNo := 1
pageSize := 100
instanceId := d.Get("instance_id").(string)
var namespaces []string
if namespace, ok := d.GetOk("namespace"); ok {
namespaces = append(namespaces, namespace.(string))
} else {
for {
resp, err := crService.ListCrEENamespaces(instanceId, pageNo, pageSize)
if err != nil {
return WrapError(err)
}
for _, n := range resp.Namespaces {
namespaces = append(namespaces, n.NamespaceName)
}
if len(resp.Namespaces) < pageSize {
break
}
pageNo++
}
}
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
nameRegex = regexp.MustCompile(v.(string))
}
var idsMap map[string]string
if v, ok := d.GetOk("ids"); ok {
idsMap = make(map[string]string)
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var enableDetails bool
if v, ok := d.GetOk("enable_details"); ok {
enableDetails = v.(bool)
}
var repos []cr_ee.RepositoriesItem
for _, namespace := range namespaces {
pageNo = 1
for {
resp, err := crService.ListCrEERepos(instanceId, namespace, pageNo, pageSize)
if err != nil {
return WrapError(err)
}
for _, r := range resp.Repositories {
if nameRegex != nil && !nameRegex.MatchString(r.RepoName) {
continue
}
if idsMap != nil && idsMap[r.RepoId] == "" {
continue
}
repos = append(repos, r)
}
if len(resp.Repositories) < pageSize {
break
}
pageNo++
}
}
tags := make([][]map[string]interface{}, len(repos))
if enableDetails {
for i, repo := range repos {
pageNo = 1
var images []cr_ee.ImagesItem
for {
resp, err := crService.ListCrEERepoTags(instanceId, repo.RepoId, pageNo, pageSize)
if err != nil {
return WrapError(err)
}
images = append(images, resp.Images...)
if len(resp.Images) < pageSize {
break
}
pageNo++
}
repoTags := make([]map[string]interface{}, len(images))
for j, image := range images {
m := make(map[string]interface{})
m["tag"] = image.Tag
m["image_id"] = image.ImageId
m["digest"] = image.Digest
m["status"] = image.Status
m["image_size"] = image.ImageSize
m["image_update"] = image.ImageUpdate
m["image_create"] = image.ImageCreate
repoTags[j] = m
}
tags[i] = repoTags
}
}
ids := make([]string, len(repos))
names := make([]string, len(repos))
reposMaps := make([]map[string]interface{}, len(repos))
for i, r := range repos {
ids[i] = r.RepoId
names[i] = r.RepoName
m := make(map[string]interface{})
m["instance_id"] = r.InstanceId
m["namespace"] = r.RepoNamespaceName
m["id"] = r.RepoId
m["name"] = r.RepoName
m["summary"] = r.Summary
m["repo_type"] = r.RepoType
if enableDetails {
m["tags"] = tags[i]
}
reposMaps[i] = m
}
d.SetId(dataResourceIdHash(names))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("repos", reposMaps); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), reposMaps)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"sort"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cr_ee"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCrEESyncRules() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCrEESyncRulesRead,
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"namespace_name": {
Type: schema.TypeString,
Optional: true,
},
"repo_name": {
Type: schema.TypeString,
Optional: true,
},
"target_instance_id": {
Type: schema.TypeString,
Optional: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"ids": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"namespace_name": {
Type: schema.TypeString,
Computed: true,
},
"repo_name": {
Type: schema.TypeString,
Computed: true,
},
"target_region_id": {
Type: schema.TypeString,
Computed: true,
},
"target_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"target_namespace_name": {
Type: schema.TypeString,
Computed: true,
},
"target_repo_name": {
Type: schema.TypeString,
Computed: true,
},
"tag_filter": {
Type: schema.TypeString,
Computed: true,
},
"sync_scope": {
Type: schema.TypeString,
Computed: true,
},
"sync_direction": {
Type: schema.TypeString,
Computed: true,
},
"sync_trigger": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCrEESyncRulesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
crService := &CrService{client}
instanceId := d.Get("instance_id").(string)
var (
namespaceName string
repoName string
targetInstanceId string
)
if v, ok := d.GetOk("namespace_name"); ok {
namespaceName = v.(string)
}
if v, ok := d.GetOk("repo_name"); ok {
repoName = v.(string)
}
if v, ok := d.GetOk("target_instance_id"); ok {
targetInstanceId = v.(string)
}
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
nameRegex = regexp.MustCompile(v.(string))
}
var idsMap map[string]string
if v, ok := d.GetOk("ids"); ok {
idsMap = make(map[string]string)
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
pageNo, pageSize := 1, 50
var syncRules []cr_ee.SyncRulesItem
for {
response := &cr_ee.ListRepoSyncRuleResponse{}
request := cr_ee.CreateListRepoSyncRuleRequest()
request.RegionId = crService.client.RegionId
request.InstanceId = instanceId
if namespaceName != "" {
request.NamespaceName = namespaceName
}
if repoName != "" {
request.RepoName = repoName
}
if targetInstanceId != "" {
request.TargetInstanceId = targetInstanceId
}
request.PageNo = requests.NewInteger(pageNo)
request.PageSize = requests.NewInteger(pageSize)
raw, err := crService.client.WithCrEEClient(func(creeClient *cr_ee.Client) (interface{}, error) {
return creeClient.ListRepoSyncRule(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cr_ee_sync_rules", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*cr_ee.ListRepoSyncRuleResponse)
if !response.ListRepoSyncRuleIsSuccess {
return WrapErrorf(fmt.Errorf("%v", response), DataDefaultErrorMsg, "alicloud_cr_ee_sync_rules", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
for _, rule := range response.SyncRules {
if nameRegex != nil && !nameRegex.MatchString(rule.SyncRuleName) {
continue
}
if idsMap != nil && idsMap[rule.SyncRuleId] == "" {
continue
}
syncRules = append(syncRules, rule)
}
if len(response.SyncRules) < pageSize {
break
}
pageNo++
}
sort.SliceStable(syncRules, func(i, j int) bool {
return syncRules[i].CreateTime < syncRules[j].CreateTime
})
ids := make([]string, len(syncRules))
names := make([]string, len(syncRules))
rulesMaps := make([]map[string]interface{}, len(syncRules))
for i, r := range syncRules {
ids[i] = r.SyncRuleId
names[i] = r.SyncRuleName
m := make(map[string]interface{})
m["region_id"] = r.LocalRegionId
m["instance_id"] = r.LocalInstanceId
m["namespace_name"] = r.LocalNamespaceName
m["repo_name"] = r.LocalRepoName
m["target_region_id"] = r.TargetRegionId
m["target_instance_id"] = r.TargetInstanceId
m["target_namespace_name"] = r.TargetNamespaceName
m["target_repo_name"] = r.TargetRepoName
m["tag_filter"] = r.TagFilter
m["sync_scope"] = r.SyncScope
m["sync_direction"] = r.SyncDirection
m["sync_trigger"] = r.SyncTrigger
m["id"] = r.SyncRuleId
m["name"] = r.SyncRuleName
rulesMaps[i] = m
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("rules", rulesMaps); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), rulesMaps)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCrEndpointAclPolicies() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCrEndpointAclPoliciesRead,
Schema: map[string]*schema.Schema{
"endpoint_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"internet"}, false),
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"policies": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Computed: true,
},
"endpoint_type": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"entry": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCrEndpointAclPoliciesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "GetInstanceEndpoint"
request := make(map[string]interface{})
request["EndpointType"] = d.Get("endpoint_type")
request["InstanceId"] = d.Get("instance_id")
if v, ok := d.GetOk("module_name"); ok {
request["ModuleName"] = v
}
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewAcrClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cr_instance_endpoint_acl_policies", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.AclEntries", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.AclEntries", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(request["InstanceId"], ":", request["EndpointType"], ":", item["Entry"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"description": object["Comment"],
"endpoint_type": request["EndpointType"],
"id": fmt.Sprint(request["InstanceId"], ":", request["EndpointType"], ":", object["Entry"]),
"entry": fmt.Sprint(object["Entry"]),
"instance_id": request["InstanceId"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("policies", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCrEndpointAclService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCrEndpointAclServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeBool,
Required: true,
},
"endpoint_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"internet"}, false),
},
"instance_id": {
Type: schema.TypeString,
Required: true,
},
"module_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Registry", "Chart"}, false),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudCrEndpointAclServiceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "UpdateInstanceEndpointStatus"
request := make(map[string]interface{})
request["Enable"] = d.Get("enable")
request["EndpointType"] = d.Get("endpoint_type")
request["InstanceId"] = d.Get("instance_id")
if v, ok := d.GetOk("module_name"); ok {
request["ModuleName"] = v
}
var response map[string]interface{}
conn, err := client.NewAcrClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cr_instance_endpoint_acl_service", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["InstanceId"], ":", request["EndpointType"]))
d.Set("endpoint_type", request["EndpointType"])
d.Set("instance_id", request["InstanceId"])
d.Set("enable", request["Enable"])
if v, ok := d.GetOk("enable"); !ok || !v.(bool) {
d.Set("status", "")
return nil
}
crService := CrService{client}
stateConf := BuildStateConf([]string{}, []string{"RUNNING"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, crService.CrEndpointAclServiceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.Set("status", "RUNNING")
return nil
}
package alicloud
import (
"encoding/json"
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cr"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCRNamespaces() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCRNamespacesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"namespaces": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Computed: true,
},
"auto_create": {
Type: schema.TypeBool,
Computed: true,
},
"default_visibility": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudCRNamespacesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
crService := CrService{client}
invoker := NewInvoker()
var (
request *cr.GetNamespaceListRequest
response *cr.GetNamespaceListResponse
)
if err := invoker.Run(func() error {
raw, err := client.WithCrClient(func(crClient *cr.Client) (interface{}, error) {
request = cr.CreateGetNamespaceListRequest()
return crClient.GetNamespaceList(request)
})
response, _ = raw.(*cr.GetNamespaceListResponse)
return err
}); err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cr_namespaces", "GetNamespaceList", AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), response)
var crResp crDescribeNamespaceListResponse
err := json.Unmarshal(response.GetHttpContentBytes(), &crResp)
if err != nil {
return WrapError(err)
}
var names []string
var s []map[string]interface{}
for _, ns := range crResp.Data.Namespace {
if nameRegex, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
if !r.MatchString(ns.Namespace) {
continue
}
}
mapping := map[string]interface{}{
"name": ns.Namespace,
}
raw, err := crService.DescribeCrNamespace(ns.Namespace)
if err != nil {
if NotFoundError(err) {
continue
}
return WrapError(err)
}
var resp crDescribeNamespaceResponse
err = json.Unmarshal(raw.GetHttpContentBytes(), &resp)
if err != nil {
return WrapError(err)
}
mapping["auto_create"] = resp.Data.Namespace.AutoCreate
mapping["default_visibility"] = resp.Data.Namespace.DefaultVisibility
names = append(names, ns.Namespace)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(names))
if err := d.Set("namespaces", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", names); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"encoding/json"
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cr"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCRRepos() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCRReposRead,
Schema: map[string]*schema.Schema{
"namespace": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
// Computed values
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"repos": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"namespace": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"summary": {
Type: schema.TypeString,
Computed: true,
},
"repo_type": {
Type: schema.TypeString,
Computed: true,
},
"domain_list": {
Type: schema.TypeMap,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"vpc": {
Type: schema.TypeString,
Computed: true,
},
"public": {
Type: schema.TypeString,
Computed: true,
},
"internal": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"tags": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"tag": {
Type: schema.TypeString,
Computed: true,
},
"image_id": {
Type: schema.TypeString,
Computed: true,
},
"digest": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"image_size": {
Type: schema.TypeInt,
Computed: true,
},
"image_update": {
Type: schema.TypeInt,
Computed: true,
},
"image_create": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudCRReposRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
invoker := NewInvoker()
getRepoListRequest := cr.CreateGetRepoListRequest()
getRepoListRequest.RegionId = string(client.Region)
getRepoListRequest.PageSize = requests.NewInteger(PageSizeMedium)
getRepoListRequest.Page = requests.NewInteger(1)
var repos []crRepo
for {
var getRepoListResponse *cr.GetRepoListResponse
if err := invoker.Run(func() error {
raw, err := client.WithCrClient(func(crClient *cr.Client) (interface{}, error) {
return crClient.GetRepoList(getRepoListRequest)
})
getRepoListResponse, _ = raw.(*cr.GetRepoListResponse)
return err
}); err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cr_repos", "GetRepoList", AlibabaCloudSdkGoERROR)
}
addDebug(getRepoListRequest.GetActionName(), getRepoListResponse)
var crResp crDescribeReposResponse
err := json.Unmarshal(getRepoListResponse.GetHttpContentBytes(), &crResp)
if err != nil {
return WrapError(err)
}
repos = append(repos, crResp.Data.Repos...)
if len(crResp.Data.Repos) < PageSizeMedium {
break
}
if page, err := getNextpageNumber(getRepoListRequest.Page); err != nil {
return WrapError(err)
} else {
getRepoListRequest.Page = page
}
}
var names []string
var s []map[string]interface{}
for _, repo := range repos {
if namespace, ok := d.GetOk("namespace"); ok {
if repo.RepoNamespace != namespace {
continue
}
}
if nameRegex, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
if !r.MatchString(repo.RepoName) {
continue
}
}
mapping := map[string]interface{}{
"namespace": repo.RepoNamespace,
"name": repo.RepoName,
"summary": repo.Summary,
"repo_type": repo.RepoType,
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
names = append(names, repo.RepoName)
s = append(s, mapping)
continue
}
domainList := make(map[string]string)
domainList["public"] = repo.RepoDomainList.Public
domainList["internal"] = repo.RepoDomainList.Internal
domainList["vpc"] = repo.RepoDomainList.Vpc
mapping["domain_list"] = domainList
var tags []crTag
getRepoTagsRequest := cr.CreateGetRepoTagsRequest()
getRepoTagsRequest.RegionId = string(client.Region)
getRepoTagsRequest.PageSize = requests.NewInteger(PageSizeMedium)
getRepoTagsRequest.Page = requests.NewInteger(1)
getRepoTagsRequest.RepoNamespace = repo.RepoNamespace
getRepoTagsRequest.RepoName = repo.RepoName
for {
var getRepoTagsResponse *cr.GetRepoTagsResponse
if err := invoker.Run(func() error {
raw, err := client.WithCrClient(func(crClient *cr.Client) (interface{}, error) {
return crClient.GetRepoTags(getRepoTagsRequest)
})
getRepoTagsResponse, _ = raw.(*cr.GetRepoTagsResponse)
return err
}); err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cr_repos", "GetRepoTags", AlibabaCloudSdkGoERROR)
}
addDebug(getRepoTagsRequest.GetActionName(), getRepoTagsResponse)
var crResp crDescribeRepoTagsResponse
err := json.Unmarshal(getRepoTagsResponse.GetHttpContentBytes(), &crResp)
if err != nil {
return WrapError(err)
}
tags = append(tags, crResp.Data.Tags...)
if len(crResp.Data.Tags) < PageSizeMedium {
break
}
if page, err := getNextpageNumber(getRepoTagsRequest.Page); err != nil {
return WrapError(err)
} else {
getRepoTagsRequest.Page = page
}
}
var tagList []map[string]interface{}
for _, tag := range tags {
tagList = append(tagList, map[string]interface{}{
"tag": tag.Tag,
"image_id": tag.ImageId,
"digest": tag.Digest,
"status": tag.Status,
"image_size": tag.ImageSize,
"image_update": tag.ImageUpdate,
"image_create": tag.ImageCreate,
})
}
mapping["tags"] = tagList
names = append(names, repo.RepoName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(names))
if err := d.Set("repos", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", names); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCrService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCrServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"password": {
Type: schema.TypeString,
ValidateFunc: validation.StringLenBetween(8, 32),
Required: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudCrServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("CrServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
action := "CreateUserInfo"
request := map[string]interface{}{
"User": map[string]interface{}{
"Password": d.Get("password"),
},
}
conn, err := meta.(*connectivity.AliyunClient).NewTeaRoaCommonClient(connectivity.OpenCrService)
if err != nil {
return WrapError(err)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequestWithAction(StringPointer(action), StringPointer("2016-06-07"), nil, StringPointer("PUT"), StringPointer("AK"), String("/users"), nil, nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"QPS Limit Exceeded"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
addDebug(action, response, nil)
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ORDER.OPEND"}) {
d.SetId("CrServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cr_service", action, AlibabaCloudSdkGoERROR)
}
d.SetId("CrServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
package alicloud
import (
"regexp"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/denverdino/aliyungo/common"
"github.com/denverdino/aliyungo/cs"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCSEdgeKubernetesClusters() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCSEdgeKubernetesClustersRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Computed: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
ForceNew: true,
},
"clusters": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"availability_zone": {
Type: schema.TypeString,
Computed: true,
},
"security_group_id": {
Type: schema.TypeString,
Computed: true,
},
"nat_gateway_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"worker_nodes": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"private_ip": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"connections": {
Type: schema.TypeMap,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"api_server_internet": {
Type: schema.TypeString,
Computed: true,
},
"api_server_intranet": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudCSEdgeKubernetesClustersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var allClusterTypes []cs.ClusterType
var requestInfo *cs.Client
invoker := NewInvoker()
var response interface{}
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
return csClient.DescribeClusters("")
})
response = raw
return err
}); err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cs_edge_kubernetes_clusters", "DescribeClusters", DenverdinoAliyungo)
}
if debugOn() {
addDebug("DescribeClusters", response, requestInfo)
}
allClusterTypes, _ = response.([]cs.ClusterType)
var filteredClusterTypes []cs.ClusterType
for _, v := range allClusterTypes {
if v.ClusterType != cs.ClusterTypeManagedKubernetes {
continue
}
if client.RegionId != string(v.RegionID) {
continue
}
if nameRegex, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
if !r.MatchString(v.Name) {
continue
}
}
if ids, ok := d.GetOk("ids"); ok {
var found bool
for _, i := range expandStringList(ids.([]interface{})) {
if v.ClusterID == i {
found = true
break
}
}
if !found {
continue
}
}
filteredClusterTypes = append(filteredClusterTypes, v)
}
var filteredKubernetesCluster []cs.KubernetesCluster
for _, v := range filteredClusterTypes {
var kubernetesCluster cs.KubernetesCluster
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
return csClient.DescribeKubernetesCluster(v.ClusterID)
})
response = raw
return err
}); err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cs_edge_kubernetes_clusters", "DescribeKubernetesCluster", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["Id"] = v.ClusterID
addDebug("DescribeKubernetesCluster", response, requestInfo, requestMap)
}
kubernetesCluster = response.(cs.KubernetesCluster)
if az, ok := d.GetOk("availability_zone"); ok && az != kubernetesCluster.ZoneId {
continue
}
filteredKubernetesCluster = append(filteredKubernetesCluster, kubernetesCluster)
}
return csEdgeKubernetesClusterDescriptionAttributes(d, filteredKubernetesCluster, meta)
}
func csEdgeKubernetesClusterDescriptionAttributes(d *schema.ResourceData, clusterTypes []cs.KubernetesCluster, meta interface{}) error {
var ids, names []string
var s []map[string]interface{}
for _, ct := range clusterTypes {
mapping := map[string]interface{}{
"id": ct.ClusterID,
"name": ct.Name,
}
if detailedEnabled, ok := d.GetOk("enable_details"); ok && !detailedEnabled.(bool) {
ids = append(ids, ct.ClusterID)
names = append(names, ct.Name)
s = append(s, mapping)
continue
}
mapping["vpc_id"] = ct.VPCID
mapping["security_group_id"] = ct.SecurityGroupID
mapping["availability_zone"] = ct.ZoneId
var workerNodes []map[string]interface{}
invoker := NewInvoker()
client := meta.(*connectivity.AliyunClient)
pageNumber := 1
for {
var result []cs.KubernetesNodeType
var pagination *cs.PaginationResult
var requestInfo *cs.Client
var response interface{}
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
nodes, paginationResult, err := csClient.GetKubernetesClusterNodes(ct.ClusterID, common.Pagination{PageNumber: pageNumber, PageSize: PageSizeLarge}, "")
return []interface{}{nodes, paginationResult}, err
})
response = raw
return err
}); err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cs_edge_kubernetes_clusters", "GetKubernetesClusterNodes", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["Id"] = ct.ClusterID
requestMap["Pagination"] = common.Pagination{PageNumber: pageNumber, PageSize: PageSizeLarge}
addDebug("GetKubernetesClusterNodes", response, requestInfo, requestMap)
}
result, _ = response.([]interface{})[0].([]cs.KubernetesNodeType)
pagination, _ = response.([]interface{})[1].(*cs.PaginationResult)
if pageNumber == 1 && (len(result) == 0 || result[0].InstanceId == "") {
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
nodes, _, err := csClient.GetKubernetesClusterNodes(ct.ClusterID, common.Pagination{PageNumber: pageNumber, PageSize: PageSizeLarge}, "")
return nodes, err
})
response = raw
return err
}); err != nil {
return resource.NonRetryableError(err)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["Id"] = ct.ClusterID
requestMap["Pagination"] = common.Pagination{PageNumber: pageNumber, PageSize: PageSizeLarge}
addDebug("GetKubernetesClusterNodes", response, requestInfo, requestMap)
}
tmp, _ := response.([]cs.KubernetesNodeType)
if len(tmp) > 0 && tmp[0].InstanceId != "" {
result = tmp
}
for _, stableState := range cs.NodeStableClusterState {
// If cluster is in NodeStableClusteState, node list will not change
if ct.State == stableState {
return nil
}
}
time.Sleep(5 * time.Second)
return resource.RetryableError(Error("there is no any nodes in kubernetes cluster %s", d.Id()))
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cs_managed_kubernetes_clusters", "GetKubernetesClusterNodes", DenverdinoAliyungo)
}
}
for _, node := range result {
subMapping := map[string]interface{}{
"id": node.InstanceId,
"name": node.InstanceName,
"private_ip": node.IpAddress[0],
}
workerNodes = append(workerNodes, subMapping)
}
if len(result) < pagination.PageSize {
break
}
pageNumber += 1
}
mapping["worker_nodes"] = workerNodes
var response interface{}
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
endpoints, err := csClient.GetClusterEndpoints(ct.ClusterID)
return endpoints, err
})
response = raw
return err
}); err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cs_edge_kubernetes_clusters", "GetClusterEndpoints", DenverdinoAliyungo)
}
connection := make(map[string]string)
if endpoints, ok := response.(cs.ClusterEndpoints); ok && endpoints.ApiServerEndpoint != "" {
connection["api_server_internet"] = endpoints.ApiServerEndpoint
}
if endpoints, ok := response.(cs.ClusterEndpoints); ok && endpoints.IntranetApiServerEndpoint != "" {
connection["api_server_intranet"] = endpoints.IntranetApiServerEndpoint
}
mapping["connections"] = connection
request := vpc.CreateDescribeNatGatewaysRequest()
request.VpcId = ct.VPCID
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeNatGateways(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, ct.VPCID, "DescribeNatGateways", AlibabaCloudSdkGoERROR)
}
addDebug("DescribeNatGateways", raw, request.RpcRequest, request)
nat, _ := raw.(*vpc.DescribeNatGatewaysResponse)
if nat != nil && len(nat.NatGateways.NatGateway) > 0 {
mapping["nat_gateway_id"] = nat.NatGateways.NatGateway[0].NatGatewayId
}
ids = append(ids, ct.ClusterID)
names = append(names, ct.Name)
s = append(s, mapping)
}
d.Set("ids", ids)
d.Set("names", names)
d.SetId(dataResourceIdHash(ids))
if err := d.Set("clusters", s); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/hashicorp/terraform-plugin-sdk/helper/hashcode"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/alibabacloud-go/tea/tea"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudCSKubernetesAddons() *schema.Resource {
return &schema.Resource{
Read: dataAlicloudCSKubernetesAddonsRead,
Schema: map[string]*schema.Schema{
"cluster_id": {
Type: schema.TypeString,
Required: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"addons": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Computed: true,
},
"current_version": {
Type: schema.TypeString,
Computed: true,
},
"next_version": {
Type: schema.TypeString,
Computed: true,
},
"required": {
Type: schema.TypeBool,
Computed: true,
},
},
},
},
},
}
}
func dataAlicloudCSKubernetesAddonsRead(d *schema.ResourceData, meta interface{}) error {
filterAddons := make(map[string]*Component)
var ids, names []string
clusterId := d.Get("cluster_id").(string)
addons, err := describeAvailableAddons(d, meta)
for _, addon := range addons {
if nameRegex, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
if !r.MatchString(addon.ComponentName) {
continue
}
}
if ids, ok := d.GetOk("ids"); ok {
findId := func(id string, ids []string) (ret bool) {
for _, i := range ids {
if id == i {
ret = true
}
}
return
}
if !findId(fmt.Sprintf("%s%s%s", clusterId, COLON_SEPARATED, addon.ComponentName), expandStringList(ids.([]interface{}))) {
continue
}
}
filterAddons[addon.ComponentName] = addon
ids = append(ids, fmt.Sprintf("%s%s%s", clusterId, COLON_SEPARATED, addon.ComponentName))
names = append(names, addon.ComponentName)
}
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceAlicloudCSKubernetesAddon, "describeAddonsMeta", err)
}
result := fetchAddonsMetadata(filterAddons)
d.Set("cluster_id", clusterId)
d.Set("ids", ids)
d.Set("names", names)
d.Set("addons", result)
d.SetId(tea.ToString(hashcode.String(clusterId)))
return nil
}
func describeAvailableAddons(d *schema.ResourceData, meta interface{}) (map[string]*Component, error) {
clusterId := d.Get("cluster_id").(string)
client, err := meta.(*connectivity.AliyunClient).NewRoaCsClient()
if err != nil {
return nil, err
}
csClient := CsClient{client}
availableAddons, err := csClient.DescribeCsKubernetesAllAvailableAddons(clusterId)
if err != nil {
return nil, WrapErrorf(err, DefaultErrorMsg, ResourceAlicloudCSKubernetesAddon, "DescribeCsKubernetesAllAvailableAddons", err)
}
return availableAddons, nil
}
func fetchAddonsMetadata(addonsMap map[string]*Component) []map[string]interface{} {
result := []map[string]interface{}{}
for name, addon := range addonsMap {
state := map[string]interface{}{}
state["name"] = name
state["current_version"] = addon.Version
state["next_version"] = addon.NextVersion
state["required"] = addon.Required
result = append(result, state)
}
return result
}
package alicloud
import (
"fmt"
"regexp"
"strconv"
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/denverdino/aliyungo/common"
"github.com/denverdino/aliyungo/cs"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCSKubernetesClusters() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCSKubernetesClustersRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"clusters": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"availability_zone": {
Type: schema.TypeString,
Computed: true,
},
"slb_internet_enabled": {
Type: schema.TypeBool,
Computed: true,
},
"security_group_id": {
Type: schema.TypeString,
Computed: true,
},
"nat_gateway_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"master_instance_types": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"worker_instance_types": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"worker_numbers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeInt,
},
},
"key_name": {
Type: schema.TypeString,
Computed: true,
},
"pod_cidr": {
Type: schema.TypeString,
Computed: true,
},
"service_cidr": {
Type: schema.TypeString,
Computed: true,
},
"cluster_network_type": {
Type: schema.TypeString,
Computed: true,
},
"node_cidr_mask": {
Type: schema.TypeInt,
Computed: true,
},
"log_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"type": {
Type: schema.TypeString,
Computed: true,
},
"project": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"image_id": {
Type: schema.TypeString,
Computed: true,
},
"master_disk_size": {
Type: schema.TypeInt,
Computed: true,
},
"master_disk_category": {
Type: schema.TypeString,
Computed: true,
},
"worker_disk_size": {
Type: schema.TypeInt,
Computed: true,
},
"worker_disk_category": {
Type: schema.TypeString,
Computed: true,
},
"worker_data_disk_size": {
Type: schema.TypeInt,
Computed: true,
},
"worker_data_disk_category": {
Type: schema.TypeString,
Computed: true,
},
"master_instance_charge_type": {
Type: schema.TypeString,
Computed: true,
},
"master_period_unit": {
Type: schema.TypeString,
Computed: true,
},
"master_period": {
Type: schema.TypeInt,
Computed: true,
},
"master_auto_renew": {
Type: schema.TypeBool,
Computed: true,
},
"master_auto_renew_period": {
Type: schema.TypeInt,
Computed: true,
},
"worker_instance_charge_type": {
Type: schema.TypeString,
Computed: true,
},
"worker_period_unit": {
Type: schema.TypeString,
Computed: true,
},
"worker_period": {
Type: schema.TypeInt,
Computed: true,
},
"worker_auto_renew": {
Type: schema.TypeBool,
Computed: true,
},
"worker_auto_renew_period": {
Type: schema.TypeInt,
Computed: true,
},
"master_nodes": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"private_ip": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"worker_nodes": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"private_ip": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"connections": {
Type: schema.TypeMap,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"api_server_internet": {
Type: schema.TypeString,
Computed: true,
},
"api_server_intranet": {
Type: schema.TypeString,
Computed: true,
},
"master_public_ip": {
Type: schema.TypeString,
Computed: true,
},
"service_domain": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudCSKubernetesClustersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var allClusterTypes []cs.ClusterType
var requestInfo *cs.Client
invoker := NewInvoker()
var response interface{}
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
return csClient.DescribeClusters("")
})
response = raw
return err
}); err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cs_kubernetes_clusters", "DescribeClusters", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["NameFilter"] = ""
addDebug("DescribeClusters", response, requestInfo, requestMap)
}
allClusterTypes, _ = response.([]cs.ClusterType)
var filteredClusterTypes []cs.ClusterType
for _, v := range allClusterTypes {
if v.ClusterType != cs.ClusterTypeKubernetes {
continue
}
if client.RegionId != string(v.RegionID) {
continue
}
if nameRegex, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
if !r.MatchString(v.Name) {
continue
}
}
if ids, ok := d.GetOk("ids"); ok {
findId := func(id string, ids []string) (ret bool) {
for _, i := range ids {
if id == i {
ret = true
}
}
return
}
if !findId(v.ClusterID, expandStringList(ids.([]interface{}))) {
continue
}
}
filteredClusterTypes = append(filteredClusterTypes, v)
}
var filteredKubernetesCluster []cs.KubernetesCluster
for _, v := range filteredClusterTypes {
var kubernetesCluster cs.KubernetesCluster
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
return csClient.DescribeKubernetesCluster(v.ClusterID)
})
response = raw
return err
}); err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cs_kubernetes_clusters", "DescribeKubernetesCluster", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["Id"] = v.ClusterID
addDebug("DescribeKubernetesCluster", response, requestInfo, requestMap)
}
kubernetesCluster = response.(cs.KubernetesCluster)
if az, ok := d.GetOk("availability_zone"); ok && az != kubernetesCluster.ZoneId {
continue
}
filteredKubernetesCluster = append(filteredKubernetesCluster, kubernetesCluster)
}
return csKubernetesClusterDescriptionAttributes(d, filteredKubernetesCluster, meta)
}
func csKubernetesClusterDescriptionAttributes(d *schema.ResourceData, clusterTypes []cs.KubernetesCluster, meta interface{}) error {
var ids, names []string
var s []map[string]interface{}
for _, ct := range clusterTypes {
mapping := map[string]interface{}{
"id": ct.ClusterID,
"name": ct.Name,
}
if detailedEnabled, ok := d.GetOk("enable_details"); ok && !detailedEnabled.(bool) {
ids = append(ids, ct.ClusterID)
names = append(names, ct.Name)
s = append(s, mapping)
continue
}
mapping["vpc_id"] = ct.VPCID
mapping["security_group_id"] = ct.SecurityGroupID
mapping["availability_zone"] = ct.ZoneId
mapping["key_name"] = ct.Parameters.KeyPair
mapping["master_disk_category"] = ct.Parameters.MasterSystemDiskCategory
mapping["worker_disk_category"] = ct.Parameters.WorkerSystemDiskCategory
if ct.Parameters.PublicSLB != nil {
mapping["slb_internet_enabled"] = *ct.Parameters.PublicSLB
}
if ct.Parameters.ImageId != "" {
mapping["image_id"] = ct.Parameters.ImageId
} else {
mapping["image_id"] = ct.Parameters.MasterImageId
}
if size, err := strconv.Atoi(ct.Parameters.MasterSystemDiskSize); err != nil {
return WrapError(err)
} else {
mapping["master_disk_size"] = size
}
if size, err := strconv.Atoi(ct.Parameters.WorkerSystemDiskSize); err != nil {
return WrapError(err)
} else {
mapping["worker_disk_size"] = size
}
if ct.Parameters.MasterInstanceChargeType == string(PrePaid) {
mapping["master_instance_charge_type"] = string(PrePaid)
if period, err := strconv.Atoi(ct.Parameters.MasterPeriod); err != nil {
return WrapError(err)
} else {
mapping["master_period"] = period
}
mapping["master_period_unit"] = ct.Parameters.MasterPeriodUnit
if ct.Parameters.MasterAutoRenew != nil {
mapping["master_auto_renew"] = *ct.Parameters.MasterAutoRenew
}
if period, err := strconv.Atoi(ct.Parameters.MasterAutoRenewPeriod); err != nil {
return WrapError(err)
} else {
mapping["master_auto_renew_period"] = period
}
} else {
mapping["master_instance_charge_type"] = string(PostPaid)
}
if ct.Parameters.WorkerInstanceChargeType == string(PrePaid) {
mapping["worker_instance_charge_type"] = string(PrePaid)
if period, err := strconv.Atoi(ct.Parameters.WorkerPeriod); err != nil {
return WrapError(err)
} else {
mapping["worker_period"] = period
}
mapping["worker_period_unit"] = ct.Parameters.WorkerPeriodUnit
if ct.Parameters.WorkerAutoRenew != nil {
mapping["worker_auto_renew"] = *ct.Parameters.WorkerAutoRenew
}
if period, err := strconv.Atoi(ct.Parameters.WorkerAutoRenewPeriod); err != nil {
return WrapError(err)
} else {
mapping["worker_auto_renew_period"] = period
}
} else {
mapping["worker_instance_charge_type"] = string(PostPaid)
}
if cidrMask, err := strconv.Atoi(ct.Parameters.NodeCIDRMask); err == nil {
mapping["node_cidr_mask"] = cidrMask
} else {
return WrapError(err)
}
if ct.Parameters.WorkerDataDisk != nil && *ct.Parameters.WorkerDataDisk {
if size, err := strconv.Atoi(ct.Parameters.WorkerDataDiskSize); err != nil {
return WrapError(err)
} else {
mapping["worker_data_disk_size"] = size
}
mapping["worker_data_disk_category"] = ct.Parameters.WorkerDataDiskCategory
}
if ct.Parameters.LoggingType != "None" {
logConfig := map[string]interface{}{}
logConfig["type"] = ct.Parameters.LoggingType
if ct.Parameters.SLSProjectName == "None" {
logConfig["project"] = ""
} else {
logConfig["project"] = ct.Parameters.SLSProjectName
}
mapping["log_config"] = []map[string]interface{}{logConfig}
}
// Each k8s cluster contains 3 master nodes
if ct.MetaData.MultiAZ || ct.MetaData.SubClass == "3az" {
numOfNodeA, err := strconv.Atoi(ct.Parameters.NumOfNodesA)
if err != nil {
return WrapError(err)
}
numOfNodeB, err := strconv.Atoi(ct.Parameters.NumOfNodesB)
if err != nil {
return WrapError(err)
}
numOfNodeC, err := strconv.Atoi(ct.Parameters.NumOfNodesC)
if err != nil {
return WrapError(err)
}
mapping["worker_numbers"] = []int{numOfNodeA, numOfNodeB, numOfNodeC}
mapping["vswitch_ids"] = []string{ct.Parameters.VSwitchIdA, ct.Parameters.VSwitchIdB, ct.Parameters.VSwitchIdC}
mapping["master_instance_types"] = []string{ct.Parameters.MasterInstanceTypeA, ct.Parameters.MasterInstanceTypeB, ct.Parameters.MasterInstanceTypeC}
mapping["worker_instance_types"] = []string{ct.Parameters.WorkerInstanceTypeA, ct.Parameters.WorkerInstanceTypeB, ct.Parameters.WorkerInstanceTypeC}
} else {
if numOfNode, err := strconv.Atoi(ct.Parameters.NumOfNodes); err != nil {
return WrapError(err)
} else {
mapping["worker_numbers"] = []int{numOfNode}
}
mapping["vswitch_ids"] = []string{ct.Parameters.VSwitchID}
mapping["master_instance_types"] = []string{ct.Parameters.MasterInstanceType}
mapping["worker_instance_types"] = []string{ct.Parameters.WorkerInstanceType}
}
var masterNodes []map[string]interface{}
var workerNodes []map[string]interface{}
invoker := NewInvoker()
client := meta.(*connectivity.AliyunClient)
pageNumber := 1
for {
var result []cs.KubernetesNodeType
var pagination *cs.PaginationResult
var requestInfo *cs.Client
var response interface{}
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
nodes, paginationResult, err := csClient.GetKubernetesClusterNodes(ct.ClusterID, common.Pagination{PageNumber: pageNumber, PageSize: PageSizeLarge}, "")
return []interface{}{nodes, paginationResult}, err
})
response = raw
return err
}); err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cs_kubernetes_clusters", "GetKubernetesClusterNodes", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["Id"] = ct.ClusterID
requestMap["Pagination"] = common.Pagination{PageNumber: pageNumber, PageSize: PageSizeLarge}
addDebug("GetKubernetesClusterNodes", response, requestInfo, requestMap)
}
result, _ = response.([]interface{})[0].([]cs.KubernetesNodeType)
pagination, _ = response.([]interface{})[1].(*cs.PaginationResult)
if pageNumber == 1 && (len(result) == 0 || result[0].InstanceId == "") {
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
nodes, _, err := csClient.GetKubernetesClusterNodes(ct.ClusterID, common.Pagination{PageNumber: pageNumber, PageSize: PageSizeLarge}, "")
return nodes, err
})
response = raw
return err
}); err != nil {
return resource.NonRetryableError(err)
}
tmp, _ := response.([]cs.KubernetesNodeType)
if len(tmp) > 0 && tmp[0].InstanceId != "" {
result = tmp
}
for _, stableState := range cs.NodeStableClusterState {
// If cluster is in NodeStableClusteState, node list will not change
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["Id"] = ct.ClusterID
requestMap["Pagination"] = common.Pagination{PageNumber: pageNumber, PageSize: PageSizeLarge}
addDebug("GetKubernetesClusterNodes", response, requestInfo, requestMap)
}
if ct.State == stableState {
return nil
}
}
time.Sleep(5 * time.Second)
return resource.RetryableError(Error("[ERROR] There is no any nodes in kubernetes cluster %s.", d.Id()))
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cs_kubernetes_clusters", "GetKubernetesClusterNodes", DenverdinoAliyungo)
}
}
for _, node := range result {
subMapping := map[string]interface{}{
"id": node.InstanceId,
"name": node.InstanceName,
"private_ip": node.IpAddress[0],
}
if node.InstanceRole == "Master" {
masterNodes = append(masterNodes, subMapping)
} else {
workerNodes = append(workerNodes, subMapping)
}
}
if len(result) < pagination.PageSize {
break
}
pageNumber += 1
}
mapping["master_nodes"] = masterNodes
mapping["worker_nodes"] = workerNodes
var requestInfo *cs.Client
var response interface{}
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
endpoints, err := csClient.GetClusterEndpoints(ct.ClusterID)
return endpoints, err
})
response = raw
return err
}); err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cs_kubernetes_clusters", "GetClusterEndpoints", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["Id"] = ct.ClusterID
addDebug("GetClusterEndpoints", response, requestInfo, requestMap)
}
connection := make(map[string]string)
if endpoints, ok := response.(cs.ClusterEndpoints); ok && endpoints.ApiServerEndpoint != "" {
connection["api_server_internet"] = endpoints.ApiServerEndpoint
connection["master_public_ip"] = strings.TrimSuffix(strings.TrimPrefix(endpoints.ApiServerEndpoint, "https://"), ":6443")
}
if endpoints, ok := response.(cs.ClusterEndpoints); ok && endpoints.IntranetApiServerEndpoint != "" {
connection["api_server_intranet"] = endpoints.IntranetApiServerEndpoint
}
connection["service_domain"] = fmt.Sprintf("*.%s.%s.alicontainer.com", ct.ClusterID, ct.RegionID)
mapping["connections"] = connection
request := vpc.CreateDescribeNatGatewaysRequest()
request.VpcId = ct.VPCID
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeNatGateways(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cs_kubernetes_clusters", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
nat, _ := raw.(*vpc.DescribeNatGatewaysResponse)
if nat != nil && len(nat.NatGateways.NatGateway) > 0 {
mapping["nat_gateway_id"] = nat.NatGateways.NatGateway[0].NatGatewayId
}
ids = append(ids, ct.ClusterID)
names = append(names, ct.Name)
s = append(s, mapping)
}
d.Set("ids", ids)
d.Set("names", names)
d.SetId(dataResourceIdHash(ids))
if err := d.Set("clusters", s); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
cs "github.com/alibabacloud-go/cs-20151215/v2/client"
"github.com/alibabacloud-go/tea/tea"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/hashcode"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCSKubernetesPermissions() *schema.Resource {
return &schema.Resource{
Read: dataAlicloudCSKubernetesPermissionsRead,
Schema: map[string]*schema.Schema{
"uid": {
Type: schema.TypeString,
Required: true,
},
"permissions": {
Optional: true,
Type: schema.TypeList,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"resource_id": {
Type: schema.TypeString,
Required: true,
},
"resource_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"cluster", "namespace", "console"}, false),
},
"role_name": {
Type: schema.TypeString,
Required: true,
},
"role_type": {
Type: schema.TypeString,
Optional: true,
},
"is_owner": {
Type: schema.TypeBool,
Optional: true,
},
"is_ram_role": {
Type: schema.TypeBool,
Optional: true,
},
},
},
},
},
}
}
func dataAlicloudCSKubernetesPermissionsRead(d *schema.ResourceData, meta interface{}) error {
client, err := meta.(*connectivity.AliyunClient).NewRoaCsClient()
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceName, "InitializeClient", err)
}
// Query existing permissions, DescribeUserPermission
uid := d.Get("uid").(string)
perms, _err := describeUserPermissions(client, uid)
if _err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceName, "DescribeUserPermission", err)
}
_ = d.Set("permissions", flattenPermissionsConfig(perms))
_ = d.Set("uid", uid)
d.SetId(tea.ToString(hashcode.String(uid)))
return nil
}
func describeUserPermissions(client *cs.Client, uid string) ([]*cs.DescribeUserPermissionResponseBody, error) {
resp, err := client.DescribeUserPermission(tea.String(uid))
if err != nil {
return nil, err
}
return resp.Body, nil
}
func flattenPermissionsConfig(permissions []*cs.DescribeUserPermissionResponseBody) (m []map[string]interface{}) {
if permissions == nil {
return []map[string]interface{}{}
}
for _, permission := range permissions {
m = append(m, map[string]interface{}{
"resource_id": permission.ResourceId,
"resource_type": permission.ResourceType,
"role_name": permission.RoleName,
"role_type": permission.RoleType,
"is_owner": convertToBool(permission.IsOwner),
"is_ram_role": convertToBool(permission.IsRamRole),
})
}
return m
}
func convertToBool(i *int64) bool {
in := tea.Int64Value(i)
var b bool
if in == 0 {
b = false
}
if in == 1 {
b = true
}
return b
}
package alicloud
import (
"fmt"
"regexp"
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/denverdino/aliyungo/common"
"github.com/denverdino/aliyungo/cs"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCSManagerKubernetesClusters() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCSManagerKubernetesClustersRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"clusters": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"availability_zone": {
Type: schema.TypeString,
Computed: true,
},
"slb_internet_enabled": {
Type: schema.TypeBool,
Computed: true,
Removed: "Field 'slb_internet_enabled' has been removed from provider version 1.53.0.",
},
"security_group_id": {
Type: schema.TypeString,
Computed: true,
},
"nat_gateway_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Removed: "Field 'vswitch_ids' has been removed from provider version 1.53.0.",
},
"worker_instance_types": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Removed: "Field 'worker_instance_types' has been removed from provider version 1.53.0.",
},
"worker_numbers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeInt,
},
Removed: "Field 'worker_numbers' has been removed from provider version 1.53.0.",
},
"key_name": {
Type: schema.TypeString,
Computed: true,
Removed: "Field 'key_name' has been removed from provider version 1.53.0.",
},
"pod_cidr": {
Type: schema.TypeString,
Computed: true,
Removed: "Field 'pod_cidr' has been removed from provider version 1.53.0.",
},
"service_cidr": {
Type: schema.TypeString,
Computed: true,
Removed: "Field 'service_cidr' has been removed from provider version 1.53.0.",
},
"cluster_network_type": {
Type: schema.TypeString,
Computed: true,
Removed: "Field 'cluster_network_type' has been removed from provider version 1.53.0.",
},
"log_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"type": {
Type: schema.TypeString,
Computed: true,
},
"project": {
Type: schema.TypeString,
Computed: true,
},
},
},
Removed: "Field 'log_config' has been removed from provider version 1.53.0.",
},
"image_id": {
Type: schema.TypeString,
Computed: true,
Removed: "Field 'image_id' has been removed from provider version 1.53.0.",
},
"worker_disk_size": {
Type: schema.TypeInt,
Computed: true,
Removed: "Field 'worker_disk_size' has been removed from provider version 1.53.0.",
},
"worker_disk_category": {
Type: schema.TypeString,
Computed: true,
Removed: "Field 'worker_disk_category' has been removed from provider version 1.53.0.",
},
"worker_data_disk_size": {
Type: schema.TypeInt,
Computed: true,
Removed: "Field 'worker_data_disk_size' has been removed from provider version 1.53.0.",
},
"worker_data_disk_category": {
Type: schema.TypeString,
Computed: true,
Removed: "Field 'worker_data_disk_category' has been removed from provider version 1.53.0.",
},
"worker_instance_charge_type": {
Type: schema.TypeString,
Computed: true,
Removed: "Field 'worker_instance_charge_type' has been removed from provider version 1.53.0.",
},
"worker_period_unit": {
Type: schema.TypeString,
Computed: true,
Removed: "Field 'worker_period_unit' has been removed from provider version 1.53.0.",
},
"worker_period": {
Type: schema.TypeInt,
Computed: true,
Removed: "Field 'worker_period' has been removed from provider version 1.53.0.",
},
"worker_auto_renew": {
Type: schema.TypeBool,
Computed: true,
Removed: "Field 'worker_auto_renew' has been removed from provider version 1.53.0.",
},
"worker_auto_renew_period": {
Type: schema.TypeInt,
Computed: true,
Removed: "Field 'worker_auto_renew_period' has been removed from provider version 1.53.0.",
},
"worker_nodes": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"private_ip": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"connections": {
Type: schema.TypeMap,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"api_server_internet": {
Type: schema.TypeString,
Computed: true,
},
"api_server_intranet": {
Type: schema.TypeString,
Computed: true,
},
"master_public_ip": {
Type: schema.TypeString,
Computed: true,
},
"service_domain": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudCSManagerKubernetesClustersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var allClusterTypes []cs.ClusterType
var requestInfo *cs.Client
invoker := NewInvoker()
var response interface{}
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
return csClient.DescribeClusters("")
})
response = raw
return err
}); err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cs_managed_kubernetes_clusters", "DescribeClusters", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["NameFilter"] = ""
addDebug("DescribeClusters", response, requestInfo, requestMap)
}
allClusterTypes, _ = response.([]cs.ClusterType)
var filteredClusterTypes []cs.ClusterType
for _, v := range allClusterTypes {
if v.ClusterType != cs.ClusterTypeManagedKubernetes {
continue
}
if client.RegionId != string(v.RegionID) {
continue
}
if nameRegex, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
if !r.MatchString(v.Name) {
continue
}
}
if ids, ok := d.GetOk("ids"); ok {
var found bool
for _, i := range expandStringList(ids.([]interface{})) {
if v.ClusterID == i {
found = true
break
}
}
if !found {
continue
}
}
filteredClusterTypes = append(filteredClusterTypes, v)
}
var filteredKubernetesCluster []cs.KubernetesCluster
for _, v := range filteredClusterTypes {
var kubernetesCluster cs.KubernetesCluster
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
return csClient.DescribeKubernetesCluster(v.ClusterID)
})
response = raw
return err
}); err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cs_managed_kubernetes_clusters", "DescribeKubernetesCluster", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["Id"] = v.ClusterID
addDebug("DescribeKubernetesCluster", response, requestInfo, requestMap)
}
kubernetesCluster = response.(cs.KubernetesCluster)
if az, ok := d.GetOk("availability_zone"); ok && az != kubernetesCluster.ZoneId {
continue
}
filteredKubernetesCluster = append(filteredKubernetesCluster, kubernetesCluster)
}
return csManagedKubernetesClusterDescriptionAttributes(d, filteredKubernetesCluster, meta)
}
func csManagedKubernetesClusterDescriptionAttributes(d *schema.ResourceData, clusterTypes []cs.KubernetesCluster, meta interface{}) error {
var ids, names []string
var s []map[string]interface{}
for _, ct := range clusterTypes {
mapping := map[string]interface{}{
"id": ct.ClusterID,
"name": ct.Name,
}
if detailedEnabled, ok := d.GetOk("enable_details"); ok && !detailedEnabled.(bool) {
ids = append(ids, ct.ClusterID)
names = append(names, ct.Name)
s = append(s, mapping)
continue
}
mapping["vpc_id"] = ct.VPCID
mapping["security_group_id"] = ct.SecurityGroupID
mapping["availability_zone"] = ct.ZoneId
var workerNodes []map[string]interface{}
invoker := NewInvoker()
client := meta.(*connectivity.AliyunClient)
pageNumber := 1
for {
var result []cs.KubernetesNodeType
var pagination *cs.PaginationResult
var requestInfo *cs.Client
var response interface{}
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
nodes, paginationResult, err := csClient.GetKubernetesClusterNodes(ct.ClusterID, common.Pagination{PageNumber: pageNumber, PageSize: PageSizeLarge}, "")
return []interface{}{nodes, paginationResult}, err
})
response = raw
return err
}); err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cs_managed_kubernetes_clusters", "GetKubernetesClusterNodes", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["Id"] = ct.ClusterID
requestMap["Pagination"] = common.Pagination{PageNumber: pageNumber, PageSize: PageSizeLarge}
addDebug("GetKubernetesClusterNodes", response, requestInfo, requestMap)
}
result, _ = response.([]interface{})[0].([]cs.KubernetesNodeType)
pagination, _ = response.([]interface{})[1].(*cs.PaginationResult)
if pageNumber == 1 && (len(result) == 0 || result[0].InstanceId == "") {
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
nodes, _, err := csClient.GetKubernetesClusterNodes(ct.ClusterID, common.Pagination{PageNumber: pageNumber, PageSize: PageSizeLarge}, "")
return nodes, err
})
response = raw
return err
}); err != nil {
return resource.NonRetryableError(err)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["Id"] = ct.ClusterID
requestMap["Pagination"] = common.Pagination{PageNumber: pageNumber, PageSize: PageSizeLarge}
addDebug("GetKubernetesClusterNodes", response, requestInfo, requestMap)
}
tmp, _ := response.([]cs.KubernetesNodeType)
if len(tmp) > 0 && tmp[0].InstanceId != "" {
result = tmp
}
for _, stableState := range cs.NodeStableClusterState {
// If cluster is in NodeStableClusteState, node list will not change
if ct.State == stableState {
return nil
}
}
time.Sleep(5 * time.Second)
return resource.RetryableError(Error("there is no any nodes in kubernetes cluster %s", d.Id()))
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cs_managed_kubernetes_clusters", "GetKubernetesClusterNodes", DenverdinoAliyungo)
}
}
for _, node := range result {
subMapping := map[string]interface{}{
"id": node.InstanceId,
"name": node.InstanceName,
"private_ip": node.IpAddress[0],
}
workerNodes = append(workerNodes, subMapping)
}
if len(result) < pagination.PageSize {
break
}
pageNumber += 1
}
mapping["worker_nodes"] = workerNodes
if ct.Parameters.LoggingType != "None" {
logConfig := map[string]interface{}{}
logConfig["type"] = ct.Parameters.LoggingType
if ct.Parameters.SLSProjectName == "None" {
logConfig["project"] = ""
} else {
logConfig["project"] = ct.Parameters.SLSProjectName
}
mapping["log_config"] = []map[string]interface{}{logConfig}
}
var response interface{}
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
endpoints, err := csClient.GetClusterEndpoints(ct.ClusterID)
return endpoints, err
})
response = raw
return err
}); err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cs_managed_kubernetes_clusters", "GetClusterEndpoints", DenverdinoAliyungo)
}
connection := make(map[string]string)
if endpoints, ok := response.(cs.ClusterEndpoints); ok && endpoints.ApiServerEndpoint != "" {
connection["api_server_internet"] = endpoints.ApiServerEndpoint
connection["master_public_ip"] = strings.TrimSuffix(strings.TrimPrefix(endpoints.ApiServerEndpoint, "https://"), ":6443")
}
if endpoints, ok := response.(cs.ClusterEndpoints); ok && endpoints.IntranetApiServerEndpoint != "" {
connection["api_server_intranet"] = endpoints.IntranetApiServerEndpoint
}
connection["service_domain"] = fmt.Sprintf("*.%s.%s.alicontainer.com", ct.ClusterID, ct.RegionID)
mapping["connections"] = connection
request := vpc.CreateDescribeNatGatewaysRequest()
request.VpcId = ct.VPCID
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeNatGateways(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, ct.VPCID, "DescribeNatGateways", AlibabaCloudSdkGoERROR)
}
addDebug("DescribeNatGateways", raw, request.RpcRequest, request)
nat, _ := raw.(*vpc.DescribeNatGatewaysResponse)
if nat != nil && len(nat.NatGateways.NatGateway) > 0 {
mapping["nat_gateway_id"] = nat.NatGateways.NatGateway[0].NatGatewayId
}
ids = append(ids, ct.ClusterID)
names = append(names, ct.Name)
s = append(s, mapping)
}
d.Set("ids", ids)
d.Set("names", names)
d.SetId(dataResourceIdHash(ids))
if err := d.Set("clusters", s); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/denverdino/aliyungo/cs"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudCSServerlessKubernetesClusters() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudCSServerlessKubernetesClustersRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"clusters": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"endpoint_public_access_enabled": {
Type: schema.TypeBool,
Computed: true,
},
"deletion_protection": {
Type: schema.TypeBool,
Computed: true,
},
"nat_gateway_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"security_group_id": {
Type: schema.TypeString,
Computed: true,
},
"connections": {
Type: schema.TypeMap,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"api_server_internet": {
Type: schema.TypeString,
Computed: true,
},
"api_server_intranet": {
Type: schema.TypeString,
Computed: true,
},
"master_public_ip": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"tags": {
Type: schema.TypeMap,
Optional: true,
Computed: true,
}},
},
},
},
}
}
func dataSourceAlicloudCSServerlessKubernetesClustersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var allClusterTypes []*cs.ServerlessClusterResponse
var requestInfo *cs.Client
invoker := NewInvoker()
var response interface{}
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
return csClient.DescribeServerlessKubernetesClusters()
})
response = raw
return err
}); err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cs_serverless_kubernetes_clusters", "DescribeServerlessKubernetesClusters", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
addDebug("DescribeServerlessKubernetesClusters", response, requestInfo, requestMap)
}
allClusterTypes, _ = response.([]*cs.ServerlessClusterResponse)
var filteredClusterTypes []*cs.ServerlessClusterResponse
for _, v := range allClusterTypes {
if v.ClusterType != cs.ClusterTypeServerlessKubernetes {
continue
}
if nameRegex, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
if !r.MatchString(v.Name) {
continue
}
}
if ids, ok := d.GetOk("ids"); ok {
var found bool
for _, i := range expandStringList(ids.([]interface{})) {
if v.ClusterId == i {
found = true
break
}
}
if !found {
continue
}
}
filteredClusterTypes = append(filteredClusterTypes, v)
}
var filteredKubernetesCluster []*cs.ServerlessClusterResponse
for _, v := range filteredClusterTypes {
var serverlessCluster *cs.ServerlessClusterResponse
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
return csClient.DescribeServerlessKubernetesCluster(v.ClusterId)
})
response = raw
return err
}); err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cs_serverless_kubernetes_clusters", "DescribeServerlessKubernetesCluster", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["Id"] = v.ClusterId
addDebug("DescribeServerlessKubernetesCluster", response, requestInfo, requestMap)
}
serverlessCluster = response.(*cs.ServerlessClusterResponse)
filteredKubernetesCluster = append(filteredKubernetesCluster, serverlessCluster)
}
return csServerlessKubernetesClusterDescriptionAttributes(d, filteredClusterTypes, meta)
}
func csServerlessKubernetesClusterDescriptionAttributes(d *schema.ResourceData, clusters []*cs.ServerlessClusterResponse, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
csService := CsService{client}
var ids, names []string
var s []map[string]interface{}
for _, ct := range clusters {
mapping := map[string]interface{}{
"id": ct.ClusterId,
"name": ct.Name,
}
if detailedEnabled, ok := d.GetOk("enable_details"); ok && !detailedEnabled.(bool) {
ids = append(ids, ct.ClusterId)
names = append(names, ct.Name)
s = append(s, mapping)
continue
}
mapping["vpc_id"] = ct.VpcId
mapping["vswitch_id"] = ct.VSwitchId
mapping["security_group_id"] = ct.SecurityGroupId
mapping["deletion_protection"] = ct.DeletionProtection
mapping["tags"] = csService.tagsToMap(ct.Tags)
//set default value
mapping["endpoint_public_access_enabled"] = false
invoker := NewInvoker()
client := meta.(*connectivity.AliyunClient)
var response interface{}
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
endpoints, err := csClient.GetClusterEndpoints(ct.ClusterId)
return endpoints, err
})
response = raw
return err
}); err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cs_serverless_kubernetes_clusters", "GetClusterEndpoints", DenverdinoAliyungo)
}
connection := make(map[string]string)
if endpoints, ok := response.(cs.ClusterEndpoints); ok && endpoints.ApiServerEndpoint != "" {
//set public access
mapping["endpoint_public_access_enabled"] = true
connection["api_server_internet"] = endpoints.ApiServerEndpoint
connection["master_public_ip"] = strings.TrimSuffix(strings.TrimPrefix(endpoints.ApiServerEndpoint, "https://"), ":6443")
}
if endpoints, ok := response.(cs.ClusterEndpoints); ok && endpoints.IntranetApiServerEndpoint != "" {
connection["api_server_intranet"] = endpoints.IntranetApiServerEndpoint
}
mapping["connections"] = connection
request := vpc.CreateDescribeNatGatewaysRequest()
request.VpcId = ct.VpcId
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeNatGateways(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, ct.VpcId, "DescribeNatGateways", AlibabaCloudSdkGoERROR)
}
addDebug("DescribeNatGateways", raw, request.RpcRequest, request)
nat, _ := raw.(*vpc.DescribeNatGatewaysResponse)
if nat != nil && len(nat.NatGateways.NatGateway) > 0 {
mapping["nat_gateway_id"] = nat.NatGateways.NatGateway[0].NatGatewayId
}
ids = append(ids, ct.ClusterId)
names = append(names, ct.Name)
s = append(s, mapping)
}
_ = d.Set("ids", ids)
_ = d.Set("names", names)
d.SetId(dataResourceIdHash(ids))
if err := d.Set("clusters", s); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
_ = writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudDataWorksFolders() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDataWorksFoldersRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"parent_folder_path": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"project_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"folders": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"folder_id": {
Type: schema.TypeString,
Computed: true,
},
"folder_path": {
Type: schema.TypeString,
Computed: true,
},
"project_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudDataWorksFoldersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListFolders"
request := make(map[string]interface{})
folderPath := ConvertDataWorksFrontEndFolderPathToBackEndFolderPath(d.Get("parent_folder_path").(string))
request["ParentFolderPath"] = folderPath
if v, ok := d.GetOk("project_id"); ok {
request["ProjectId"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewDataworkspublicClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-05-18"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_data_works_folders", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Data.Folders", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Data.Folders", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["FolderId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["FolderId"]),
"folder_id": fmt.Sprint(object["FolderId"]),
"folder_path": ConvertDataWorksBackEndFolderPathToFrontEndFolderPath(object["FolderPath"].(string)),
"project_id": request["ProjectId"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
id := fmt.Sprint(object["FolderId"], ":", request["ProjectId"])
dataworksPublicService := DataworksPublicService{client}
_, err := dataworksPublicService.DescribeDataWorksFolder(id)
if err != nil {
return WrapError(err)
}
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("folders", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDataWorksService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDataWorksServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudDataWorksServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("DataWorksServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
action := "OpenDataWorksStandardService"
request := map[string]interface{}{
"Region": meta.(*connectivity.AliyunClient).RegionId,
}
conn, err := meta.(*connectivity.AliyunClient).NewTeaCommonClient(connectivity.DataWorksService)
if err != nil {
return WrapError(err)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-06-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"QPS Limit Exceeded"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
addDebug(action, response, nil)
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ORDER.OPEND"}) {
d.SetId("DataWorksServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_dataworks_service", action, AlibabaCloudSdkGoERROR)
}
d.SetId("DataWorksServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDatabaseGatewayGateways() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDatabaseGatewayGatewaysRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"search_key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"EXCEPTION", "NEW", "RUNNING", "STOPPED"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"gateways": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"gateway_desc": {
Type: schema.TypeString,
Computed: true,
},
"gateway_instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"connect_endpoint_type": {
Type: schema.TypeString,
Computed: true,
},
"current_daemon_version": {
Type: schema.TypeString,
Computed: true,
},
"current_version": {
Type: schema.TypeString,
Computed: true,
},
"end_point": {
Type: schema.TypeString,
Computed: true,
},
"gateway_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"gateway_instance_status": {
Type: schema.TypeString,
Computed: true,
},
"last_update_time": {
Type: schema.TypeString,
Computed: true,
},
"local_ip": {
Type: schema.TypeString,
Computed: true,
},
"message": {
Type: schema.TypeString,
Computed: true,
},
"output_ip": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"gateway_name": {
Type: schema.TypeString,
Computed: true,
},
"hosts": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"modified_time": {
Type: schema.TypeString,
Computed: true,
},
"parent_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"user_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudDatabaseGatewayGatewaysRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "GetUserGateways"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("search_key"); ok {
request["SearchKey"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var gatewayNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
gatewayNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewDgClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-27"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_database_gateway_gateways", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.Data", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Data", response)
}
result, _ := convertJsonStringToList(resp.(string))
for _, v := range result {
item := v.(map[string]interface{})
if gatewayNameRegex != nil && !gatewayNameRegex.MatchString(fmt.Sprint(item["gatewayName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["gatewayId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": object["gmtCreateString"],
"gateway_desc": object["gatewayDesc"],
"gateway_name": object["gatewayName"],
"hosts": object["hosts"],
"id": object["gatewayId"],
"modified_time": object["gmtModifiedString"],
"parent_id": object["parentId"],
"status": object["status"],
"user_id": object["userId"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["gatewayName"])
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["gatewayId"])
dgService := DgService{client}
getResp, err := dgService.GetUserGatewayInstances(id)
if err != nil {
return WrapError(err)
}
gatewayInstances := make([]map[string]interface{}, 0)
for _, v := range getResp {
if m, ok := v.(map[string]interface{}); ok {
temp := map[string]interface{}{
"connect_endpoint_type": m["connectEndpointType"],
"current_daemon_version": m["currentDaemonVersion"],
"current_version": m["currentVersion"],
"end_point": m["endPoint"],
"gateway_instance_id": m["gatewayInstanceId"],
"gateway_instance_status": m["gatewayInstanceStatus"],
"last_update_time": m["lastUpdateTime"],
"local_ip": m["localIP"],
"message": m["message"],
"output_ip": m["outputIP"],
}
gatewayInstances = append(gatewayInstances, temp)
}
}
mapping["gateway_instances"] = gatewayInstances
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("gateways", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDatahubService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDatahubServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudDatahubServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("DatahubServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
action := "OpenDataHubService"
request := map[string]interface{}{}
conn, err := meta.(*connectivity.AliyunClient).NewTeaCommonClient(connectivity.OpenDatahubService)
if err != nil {
return WrapError(err)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"QPS Limit Exceeded"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
addDebug(action, response, nil)
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ORDER.OPEND"}) {
d.SetId("DatahubServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_datahub_service", action, AlibabaCloudSdkGoERROR)
}
d.SetId("DatahubServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
package alicloud
import (
"fmt"
"strings"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDBInstanceClasses() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDBInstanceClassesRead,
Schema: map[string]*schema.Schema{
"zone_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"engine": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"MySQL", "SQLServer", "PostgreSQL", "PPAS", "MariaDB"}, false),
},
"engine_version": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"sorted_by": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Price"}, false),
},
"instance_charge_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: PostPaid,
ValidateFunc: validation.StringInSlice([]string{string(PostPaid), string(PrePaid)}, false),
},
"db_instance_class": {
Type: schema.TypeString,
Optional: true,
},
"category": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Basic", "HighAvailability", "AlwaysOn", "Finance"}, false),
},
"storage_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"cloud_ssd", "local_ssd", "cloud_essd", "cloud_essd2", "cloud_essd3"}, false),
},
"db_instance_storage_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"cloud_ssd", "local_ssd", "cloud_essd", "cloud_essd2", "cloud_essd3"}, false),
},
"multi_zone": {
Type: schema.TypeBool,
Default: false,
Optional: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
// Computed values.
"instance_classes": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"zone_ids": {
Type: schema.TypeList,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"sub_zone_ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
},
},
Computed: true,
},
"instance_class": {
Type: schema.TypeString,
Computed: true,
},
"price": {
Type: schema.TypeString,
Computed: true,
},
"storage_range": {
Type: schema.TypeMap,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"min": {
Type: schema.TypeString,
Computed: true,
},
"max": {
Type: schema.TypeString,
Computed: true,
},
"step": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudDBInstanceClassesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
instanceChargeType := d.Get("instance_charge_type").(string)
if instanceChargeType == string(PostPaid) {
instanceChargeType = string(Postpaid)
} else {
instanceChargeType = string(Prepaid)
}
zoneId, zoneIdOk := d.GetOk("zone_id")
engine, engineOk := d.GetOk("engine")
engineVersion, engineVersionOk := d.GetOk("engine_version")
dbInstanceClass, dbInstanceClassOk := d.GetOk("db_instance_class")
dbInstanceStorageType, dbInstanceStorageTypeOk := d.GetOk("db_instance_storage_type")
if !dbInstanceStorageTypeOk || dbInstanceStorageType.(string) == "" {
dbInstanceStorageType, dbInstanceStorageTypeOk = d.GetOk("storage_type")
}
category, categoryOk := d.GetOk("category")
availableZones := make([]map[string]interface{}, 0)
s := make([]map[string]interface{}, 0)
ids := make([]string, 0)
// if all filters can be got, there is no need to invoking DescribeAvailableZones to get them
if zoneIdOk && zoneId.(string) != "" &&
engineOk && engine.(string) != "" &&
engineVersionOk && engineVersion.(string) != "" &&
dbInstanceStorageTypeOk && dbInstanceStorageType.(string) != "" &&
categoryOk && category.(string) != "" {
action := "DescribeAvailableClasses"
request := map[string]interface{}{
"RegionId": client.RegionId,
"SourceIp": client.SourceIp,
"ZoneId": zoneId,
"InstanceChargeType": instanceChargeType,
"Engine": engine,
"EngineVersion": engineVersion,
"DBInstanceStorageType": dbInstanceStorageType,
"Category": category,
}
var response map[string]interface{}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_db_instance_classes", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.DBInstanceClasses", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.DBInstanceClasses", response)
}
zoneIds := make([]map[string]interface{}, 0)
zoneIds = append(zoneIds, map[string]interface{}{
"id": zoneId,
"sub_zone_ids": splitMultiZoneId(zoneId.(string)),
})
for _, r := range resp.([]interface{}) {
instanceClassItem := r.(map[string]interface{})
if dbInstanceClassOk && dbInstanceClass != "" && dbInstanceClass != fmt.Sprint(instanceClassItem["DBInstanceClass"]) {
continue
}
mapping := map[string]interface{}{
"instance_class": fmt.Sprint(instanceClassItem["DBInstanceClass"]),
"zone_ids": zoneIds,
"storage_range": map[string]interface{}{
"min": fmt.Sprint(instanceClassItem["DBInstanceStorageRange"].(map[string]interface{})["MinValue"]),
"max": fmt.Sprint(instanceClassItem["DBInstanceStorageRange"].(map[string]interface{})["MaxValue"]),
"step": fmt.Sprint(instanceClassItem["DBInstanceStorageRange"].(map[string]interface{})["Step"]),
},
}
s = append(s, mapping)
ids = append(ids, fmt.Sprint(instanceClassItem["DBInstanceClass"]))
}
} else {
// 1. Invkoing DescribeAvailableZones to get available zones and other filters
engines := make([]string, 0)
if v, ok := d.GetOk("engine"); ok && v.(string) != "" {
engines = append(engines, v.(string))
} else {
engines = []string{"MySQL", "SQLServer", "PostgreSQL", "PPAS", "MariaDB"}
}
action := "DescribeAvailableZones"
request := map[string]interface{}{
"RegionId": client.RegionId,
"SourceIp": client.SourceIp,
}
if v, ok := d.GetOk("engine_version"); ok && v.(string) != "" {
request["EngineVersion"] = v.(string)
}
if v, ok := d.GetOk("zone_id"); ok && v.(string) != "" {
request["ZoneId"] = v.(string)
}
if instanceChargeType == string(PostPaid) {
request["CommodityCode"] = "bards"
} else {
request["CommodityCode"] = "rds"
}
multiZone := false
if v, ok := d.GetOk("multi_zone"); ok {
multiZone = v.(bool)
}
var targetCategory, targetStorageType string
if v, ok := d.GetOk("category"); ok && v.(string) != "" {
targetCategory = v.(string)
}
if v, ok := d.GetOk("db_instance_storage_type"); ok && v.(string) != "" {
targetStorageType = v.(string)
}
var response map[string]interface{}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
for _, engine := range engines {
request["Engine"] = engine
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_db_zones", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.AvailableZones", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.AvailableZones", response)
}
for _, r := range resp.([]interface{}) {
availableZoneItem := r.(map[string]interface{})
zoneId := fmt.Sprint(availableZoneItem["ZoneId"])
if (multiZone && !strings.Contains(zoneId, MULTI_IZ_SYMBOL)) || (!multiZone && strings.Contains(zoneId, MULTI_IZ_SYMBOL)) {
continue
}
if targetCategory == "" && targetStorageType == "" {
availableZones = append(availableZones, availableZoneItem)
continue
}
for _, r := range availableZoneItem["SupportedEngines"].([]interface{}) {
supportedEngineItem := r.(map[string]interface{})
for _, r := range supportedEngineItem["SupportedEngineVersions"].([]interface{}) {
supportedEngineVersionItem := r.(map[string]interface{})
for _, r := range supportedEngineVersionItem["SupportedCategorys"].([]interface{}) {
supportedCategoryItem := r.(map[string]interface{})
if targetCategory != "" && targetCategory != fmt.Sprint(supportedCategoryItem["Category"]) {
continue
}
if targetStorageType == "" {
availableZones = append(availableZones, availableZoneItem)
goto NEXT
}
for _, r := range supportedCategoryItem["SupportedStorageTypes"].([]interface{}) {
supportedStorageTypeItem := r.(map[string]interface{})
if targetStorageType != fmt.Sprint(supportedStorageTypeItem["StorageType"]) {
continue
}
availableZones = append(availableZones, availableZoneItem)
goto NEXT
}
}
}
}
NEXT:
continue
}
}
// 2. Iterating the availableZones and invoking DescribeAvailableClasses to get available classes
for _, availableZone := range availableZones {
action := "DescribeAvailableClasses"
request := map[string]interface{}{
"RegionId": client.RegionId,
"SourceIp": client.SourceIp,
"ZoneId": fmt.Sprint(availableZone["ZoneId"]),
"InstanceChargeType": instanceChargeType,
}
zoneIds := make([]map[string]interface{}, 0)
zoneIds = append(zoneIds, map[string]interface{}{
"id": fmt.Sprint(availableZone["ZoneId"]),
"sub_zone_ids": splitMultiZoneId(fmt.Sprint(availableZone["ZoneId"])),
})
for _, r := range availableZone["SupportedEngines"].([]interface{}) {
supportedEngineItem := r.(map[string]interface{})
request["Engine"] = fmt.Sprint(supportedEngineItem["Engine"])
for _, r := range supportedEngineItem["SupportedEngineVersions"].([]interface{}) {
supportedEngineVersionItem := r.(map[string]interface{})
request["EngineVersion"] = fmt.Sprint(supportedEngineVersionItem["Version"])
for _, r := range supportedEngineVersionItem["SupportedCategorys"].([]interface{}) {
supportedCategoryItem := r.(map[string]interface{})
request["Category"] = fmt.Sprint(supportedCategoryItem["Category"])
for _, r := range supportedCategoryItem["SupportedStorageTypes"].([]interface{}) {
storageTypeItem := r.(map[string]interface{})
request["DBInstanceStorageType"] = fmt.Sprint(storageTypeItem["StorageType"])
var response map[string]interface{}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_db_instance_classes", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.DBInstanceClasses", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.DBInstanceClasses", response)
}
for _, r := range resp.([]interface{}) {
instanceClassItem := r.(map[string]interface{})
if dbInstanceClassOk && dbInstanceClass != "" && dbInstanceClass != fmt.Sprint(instanceClassItem["DBInstanceClass"]) {
continue
}
mapping := map[string]interface{}{
"instance_class": fmt.Sprint(instanceClassItem["DBInstanceClass"]),
"zone_ids": zoneIds,
"storage_range": map[string]interface{}{
"min": fmt.Sprint(instanceClassItem["DBInstanceStorageRange"].(map[string]interface{})["MinValue"]),
"max": fmt.Sprint(instanceClassItem["DBInstanceStorageRange"].(map[string]interface{})["MaxValue"]),
"step": fmt.Sprint(instanceClassItem["DBInstanceStorageRange"].(map[string]interface{})["Step"]),
},
}
s = append(s, mapping)
ids = append(ids, fmt.Sprint(instanceClassItem["DBInstanceClass"]))
}
}
}
}
}
}
}
d.SetId(dataResourceIdHash(ids))
err := d.Set("instance_classes", s)
if err != nil {
return WrapError(err)
}
d.Set("ids", ids)
if output, ok := d.GetOk("output_file"); ok {
err = writeToFile(output.(string), s)
if err != nil {
return WrapError(err)
}
}
return nil
}
package alicloud
import (
"fmt"
"strings"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDBInstanceEngines() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDBInstanceEnginesRead,
Schema: map[string]*schema.Schema{
"zone_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"instance_charge_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: PostPaid,
ValidateFunc: validation.StringInSlice([]string{string(PostPaid), string(PrePaid)}, false),
},
"engine": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"MySQL", "SQLServer", "PostgreSQL", "PPAS", "MariaDB"}, false),
},
"engine_version": {
Type: schema.TypeString,
Optional: true,
},
"category": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Basic", "HighAvailability", "AlwaysOn", "Finance"}, false),
},
"db_instance_storage_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"cloud_ssd", "local_ssd", "cloud_essd", "cloud_essd2", "cloud_essd3"}, false),
},
"multi_zone": {
Type: schema.TypeBool,
Default: false,
Optional: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
// Computed values.
"instance_engines": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"zone_ids": {
Type: schema.TypeList,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"sub_zone_ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
},
},
Computed: true,
},
"engine": {
Type: schema.TypeString,
Computed: true,
},
"engine_version": {
Type: schema.TypeString,
Computed: true,
},
"category": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudDBInstanceEnginesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
engines := make([]string, 0)
if v, ok := d.GetOk("engine"); ok && v.(string) != "" {
engines = append(engines, v.(string))
} else {
engines = []string{"MySQL", "SQLServer", "PostgreSQL", "PPAS", "MariaDB"}
}
action := "DescribeAvailableZones"
request := map[string]interface{}{
"RegionId": client.RegionId,
"SourceIp": client.SourceIp,
}
if v, ok := d.GetOk("engine_version"); ok && v.(string) != "" {
request["EngineVersion"] = v.(string)
}
if v, ok := d.GetOk("zone_id"); ok && v.(string) != "" {
request["ZoneId"] = v.(string)
}
instanceChargeType := d.Get("instance_charge_type").(string)
if instanceChargeType == string(PostPaid) {
request["CommodityCode"] = "bards"
} else {
request["CommodityCode"] = "rds"
}
multiZone := false
if v, ok := d.GetOk("multi_zone"); ok {
multiZone = v.(bool)
}
var targetCategory, targetStorageType string
if v, ok := d.GetOk("category"); ok && v.(string) != "" {
targetCategory = v.(string)
}
if v, ok := d.GetOk("db_instance_storage_type"); ok && v.(string) != "" {
targetStorageType = v.(string)
}
var ids []string
var s []map[string]interface{}
var response map[string]interface{}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
for _, engine := range engines {
request["Engine"] = engine
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_db_instance_engines", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.AvailableZones", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.AvailableZones", response)
}
for _, r := range resp.([]interface{}) {
availableZoneItem := r.(map[string]interface{})
zoneId := fmt.Sprint(availableZoneItem["ZoneId"])
if (multiZone && !strings.Contains(zoneId, MULTI_IZ_SYMBOL)) || (!multiZone && strings.Contains(zoneId, MULTI_IZ_SYMBOL)) {
continue
}
zoneIds := make([]map[string]interface{}, 0)
zoneIds = append(zoneIds, map[string]interface{}{
"id": zoneId,
"sub_zone_ids": splitMultiZoneId(zoneId),
})
for _, r := range availableZoneItem["SupportedEngines"].([]interface{}) {
supportedEngineItem := r.(map[string]interface{})
for _, r := range supportedEngineItem["SupportedEngineVersions"].([]interface{}) {
supportedEngineVersionItem := r.(map[string]interface{})
for _, r := range supportedEngineVersionItem["SupportedCategorys"].([]interface{}) {
supportedCategoryItem := r.(map[string]interface{})
if targetCategory != "" && targetCategory != fmt.Sprint(supportedCategoryItem["Category"]) {
continue
}
if targetStorageType != "" {
find := false
for _, r := range supportedCategoryItem["SupportedStorageTypes"].([]interface{}) {
supportedStorageTypeItem := r.(map[string]interface{})
if targetStorageType != fmt.Sprint(supportedStorageTypeItem["StorageType"]) {
continue
}
find = true
break
}
if !find {
continue
}
}
mapping := map[string]interface{}{
"zone_ids": zoneIds,
"engine": fmt.Sprint(supportedEngineItem["Engine"]),
"engine_version": fmt.Sprint(supportedEngineVersionItem["Version"]),
"category": fmt.Sprint(supportedCategoryItem["Category"]),
}
s = append(s, mapping)
ids = append(ids, fmt.Sprint(supportedEngineItem["Engine"]))
break
}
}
}
}
}
d.SetId(dataResourceIdHash(ids))
err = d.Set("instance_engines", s)
if err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
err = writeToFile(output.(string), s)
if err != nil {
return WrapError(err)
}
}
return nil
}
package alicloud
import (
"encoding/json"
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDBInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDBInstancesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"engine": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{
string(MySQL),
string(SQLServer),
string(PPAS),
string(PostgreSQL),
}, false),
},
"status": {
Type: schema.TypeString,
Optional: true,
// please follow the link below to see more details on available statusesplease follow the link below to see more details on available statuses
// https://help.aliyun.com/document_detail/26315.html
},
"db_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{
"Primary",
"Readonly",
"Guard",
"Temp",
}, false),
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
},
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"connection_mode": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{
"Standard",
"Safe",
}, false),
},
"tags": tagsSchema(),
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"page_number": {
Type: schema.TypeInt,
Optional: true,
},
"page_size": {
Type: schema.TypeInt,
Optional: true,
Default: 100,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"parameters": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"force_modify": {
Type: schema.TypeString,
Computed: true,
},
"checking_code": {
Type: schema.TypeString,
Computed: true,
},
"parameter_value": {
Type: schema.TypeString,
Computed: true,
},
"force_restart": {
Type: schema.TypeString,
Computed: true,
},
"parameter_name": {
Type: schema.TypeString,
Computed: true,
},
"parameter_description": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"charge_type": {
Type: schema.TypeString,
Computed: true,
},
"db_type": {
Type: schema.TypeString,
Computed: true,
},
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"expire_time": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"engine": {
Type: schema.TypeString,
Computed: true,
},
"engine_version": {
Type: schema.TypeString,
Computed: true,
},
"net_type": {
Type: schema.TypeString,
Computed: true,
},
"connection_mode": {
Type: schema.TypeString,
Computed: true,
},
"instance_type": {
Type: schema.TypeString,
Computed: true,
},
"availability_zone": {
Type: schema.TypeString,
Computed: true,
},
"master_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"guard_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"temp_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"readonly_instance_ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"connection_string": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeString,
Computed: true,
},
"db_instance_storage_type": {
Type: schema.TypeString,
Computed: true,
},
"instance_storage": {
Type: schema.TypeInt,
Computed: true,
},
"master_zone": {
Type: schema.TypeString,
Computed: true,
},
"zone_id_slave_a": {
Type: schema.TypeString,
Computed: true,
},
"zone_id_slave_b": {
Type: schema.TypeString,
Computed: true,
},
"ssl_expire_time": {
Type: schema.TypeString,
Computed: true,
},
"require_update": {
Type: schema.TypeString,
Computed: true,
},
"acl": {
Type: schema.TypeString,
Computed: true,
},
"ca_type": {
Type: schema.TypeString,
Computed: true,
},
"client_ca_cert": {
Type: schema.TypeString,
Computed: true,
},
"client_ca_cert_expire_time": {
Type: schema.TypeString,
Computed: true,
},
"client_cert_revocation_list": {
Type: schema.TypeString,
Computed: true,
},
"last_modify_status": {
Type: schema.TypeString,
Computed: true,
},
"modify_status_reason": {
Type: schema.TypeString,
Computed: true,
},
"replication_acl": {
Type: schema.TypeString,
Computed: true,
},
"require_update_item": {
Type: schema.TypeString,
Computed: true,
},
"require_update_reason": {
Type: schema.TypeString,
Computed: true,
},
"ssl_create_time": {
Type: schema.TypeString,
Computed: true,
},
"ssl_enabled": {
Type: schema.TypeString,
Computed: true,
},
"server_ca_url": {
Type: schema.TypeString,
Computed: true,
},
"server_cert": {
Type: schema.TypeString,
Computed: true,
},
"server_key": {
Type: schema.TypeString,
Computed: true,
},
"creator": {
Type: schema.TypeString,
Computed: true,
},
"delete_date": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"encryption_key": {
Type: schema.TypeString,
Computed: true,
},
"encryption_key_status": {
Type: schema.TypeString,
Computed: true,
},
"key_usage": {
Type: schema.TypeString,
Computed: true,
},
"material_expire_time": {
Type: schema.TypeString,
Computed: true,
},
"origin": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"total_count": {
Type: schema.TypeInt,
Computed: true,
},
},
}
}
func dataSourceAlicloudDBInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDBInstances"
request := map[string]interface{}{
"RegionId": client.RegionId,
"SourceIp": client.SourceIp,
}
if v, ok := d.GetOk("page_number"); ok && v.(int) > 0 {
request["PageNumber"] = v.(int)
} else {
request["PageNumber"] = 1
}
if v, ok := d.GetOk("page_size"); ok && v.(int) > 0 {
request["PageSize"] = v.(int)
} else {
request["PageSize"] = PageSizeLarge
}
if v, ok := d.GetOk("engine"); ok && v.(string) != "" {
request["Engine"] = v.(string)
}
if v, ok := d.GetOk("status"); ok && v.(string) != "" {
request["DBInstanceStatus"] = v.(string)
}
if v, ok := d.GetOk("db_type"); ok && v.(string) != "" {
request["DBInstanceType"] = v.(string)
}
if v, ok := d.GetOk("vpc_id"); ok && v.(string) != "" {
request["VpcId"] = v.(string)
}
if v, ok := d.GetOk("vswitch_id"); ok && v.(string) != "" {
request["VSwitchId"] = v.(string)
}
if v, ok := d.GetOk("connection_mode"); ok && v.(string) != "" {
request["ConnectionMode"] = v.(string)
}
if v, ok := d.GetOk("tags"); ok {
tagsMap := v.(map[string]interface{})
bs, err := json.Marshal(tagsMap)
if err != nil {
return WrapError(err)
}
request["Tags"] = string(bs)
}
var response map[string]interface{}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
var objects []interface{}
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
nameRegex = r
}
// ids
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_db_instances", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Items.DBInstance", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Items.DBInstance", response)
}
result, _ := resp.([]interface{})
if isPagingRequest(d) {
objects = result
break
}
for _, v := range result {
item := v.(map[string]interface{})
if nameRegex != nil {
if !nameRegex.MatchString(fmt.Sprint(item["DBInstanceDescription"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DBInstanceId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
return rdsInstancesDescription(d, meta, objects, formatInt(response["TotalRecordCount"]))
}
func rdsInstancesDescription(d *schema.ResourceData, meta interface{}, objects []interface{}, totalCount int) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
var ids []string
var names []string
var s []map[string]interface{}
for _, v := range objects {
item := v.(map[string]interface{})
readOnlyInstanceIDs := []string{}
for _, id := range item["ReadOnlyDBInstanceIds"].(map[string]interface{})["ReadOnlyDBInstanceId"].([]interface{}) {
readOnlyInstanceIDs = append(readOnlyInstanceIDs, fmt.Sprint(id.(map[string]interface{})["DBInstanceId"]))
}
instance, err := rdsService.DescribeDBInstance(fmt.Sprint(item["DBInstanceId"]))
if err != nil {
return WrapError(err)
}
mapping := map[string]interface{}{
"id": fmt.Sprint(item["DBInstanceId"]),
"name": fmt.Sprint(item["DBInstanceDescription"]),
"charge_type": fmt.Sprint(item["PayType"]),
"db_type": fmt.Sprint(item["DBInstanceType"]),
"region_id": fmt.Sprint(item["RegionId"]),
"create_time": fmt.Sprint(item["CreateTime"]),
"expire_time": fmt.Sprint(item["ExpireTime"]),
"status": fmt.Sprint(item["DBInstanceStatus"]),
"engine": fmt.Sprint(item["Engine"]),
"engine_version": fmt.Sprint(item["EngineVersion"]),
"net_type": fmt.Sprint(item["DBInstanceNetType"]),
"connection_mode": fmt.Sprint(item["ConnectionMode"]),
"instance_type": fmt.Sprint(item["DBInstanceClass"]),
"availability_zone": fmt.Sprint(item["ZoneId"]),
"master_instance_id": fmt.Sprint(item["MasterInstanceId"]),
"guard_instance_id": fmt.Sprint(item["GuardDBInstanceId"]),
"temp_instance_id": fmt.Sprint(item["TempDBInstanceId"]),
"readonly_instance_ids": readOnlyInstanceIDs,
"vpc_id": fmt.Sprint(item["VpcId"]),
"vswitch_id": fmt.Sprint(item["VSwitchId"]),
"connection_string": instance["ConnectionString"],
"port": instance["Port"],
"db_instance_storage_type": instance["DBInstanceStorageType"],
"instance_storage": instance["DBInstanceStorage"],
"master_zone": instance["MasterZone"],
}
sslResponse, sslErr := rdsService.DescribeDBInstanceSSL(fmt.Sprint(item["DBInstanceId"]))
if sslErr == nil {
if v, ok := sslResponse["SSLExpireTime"]; ok && v != "" {
mapping["ssl_expire_time"] = sslResponse["SSLExpireTime"]
}
if v, ok := sslResponse["RequireUpdate"]; ok && v != "" {
mapping["require_update"] = sslResponse["RequireUpdate"]
}
if v, ok := sslResponse["ACL"]; ok && v != "" {
mapping["acl"] = sslResponse["ACL"]
}
if v, ok := sslResponse["CAType"]; ok && v != "" {
mapping["ca_type"] = sslResponse["CAType"]
}
if v, ok := sslResponse["ClientCACert"]; ok && v != "" {
mapping["client_ca_cert"] = sslResponse["ClientCACert"]
}
if v, ok := sslResponse["ClientCACertExpireTime"]; ok && v != "" {
mapping["client_ca_cert_expire_time"] = sslResponse["ClientCACertExpireTime"]
}
if v, ok := sslResponse["ClientCertRevocationList"]; ok && v != "" {
mapping["client_cert_revocation_list"] = sslResponse["ClientCertRevocationList"]
}
if v, ok := sslResponse["LastModifyStatus"]; ok && v != "" {
mapping["last_modify_status"] = sslResponse["LastModifyStatus"]
}
if v, ok := sslResponse["ModifyStatusReason"]; ok && v != "" {
mapping["modify_status_reason"] = sslResponse["ModifyStatusReason"]
}
if v, ok := sslResponse["ReplicationACL"]; ok && v != "" {
mapping["replication_acl"] = sslResponse["ReplicationACL"]
}
if v, ok := sslResponse["RequireUpdateItem"]; ok && v != "" {
mapping["require_update_item"] = sslResponse["RequireUpdateItem"]
}
if v, ok := sslResponse["RequireUpdateReason"]; ok && v != "" {
mapping["require_update_reason"] = sslResponse["RequireUpdateReason"]
}
if v, ok := sslResponse["SSLCreateTime"]; ok && v != "" {
mapping["ssl_create_time"] = sslResponse["SSLCreateTime"]
}
if v, ok := sslResponse["SSLEnabled"]; ok && v != "" {
mapping["ssl_enabled"] = sslResponse["SSLEnabled"]
}
if v, ok := sslResponse["ServerCAUrl"]; ok && v != "" {
mapping["server_ca_url"] = sslResponse["ServerCAUrl"]
}
if v, ok := sslResponse["ServerCert"]; ok && v != "" {
mapping["server_cert"] = sslResponse["ServerCert"]
}
if v, ok := sslResponse["ServerKey"]; ok && v != "" {
mapping["server_key"] = sslResponse["ServerKey"]
}
}
encResponse, encError := rdsService.DescribeDBInstanceEncryptionKey(fmt.Sprint(item["DBInstanceId"]))
if encError == nil {
if v, ok := encResponse["Creator"]; ok && v != "" {
mapping["creator"] = encResponse["Creator"]
}
if v, ok := encResponse["DeleteDate"]; ok && v != "" {
mapping["delete_date"] = encResponse["DeleteDate"]
}
if v, ok := encResponse["Description"]; ok && v != "" {
mapping["description"] = encResponse["Description"]
}
if v, ok := encResponse["EncryptionKey"]; ok && v != "" {
mapping["encryption_key"] = encResponse["EncryptionKey"]
}
if v, ok := encResponse["EncryptionKeyStatus"]; ok && v != "" {
mapping["encryption_key_status"] = encResponse["EncryptionKeyStatus"]
}
if v, ok := encResponse["KeyUsage"]; ok && v != "" {
mapping["key_usage"] = encResponse["KeyUsage"]
}
if v, ok := encResponse["MaterialExpireTime"]; ok && v != "" {
mapping["material_expire_time"] = encResponse["MaterialExpireTime"]
}
if v, ok := encResponse["Origin"]; ok && v != "" {
mapping["origin"] = encResponse["Origin"]
}
}
slaveZones := instance["SlaveZones"].(map[string]interface{})["SlaveZone"].([]interface{})
if len(slaveZones) == 2 {
mapping["zone_id_slave_a"] = slaveZones[0].(map[string]interface{})["ZoneId"]
mapping["zone_id_slave_b"] = slaveZones[1].(map[string]interface{})["ZoneId"]
} else if len(slaveZones) == 1 {
mapping["zone_id_slave_a"] = slaveZones[0].(map[string]interface{})["ZoneId"]
}
if d.Get("enable_details").(bool) {
paramResponse, paramError := rdsService.DescribeParameterTemplates(item["DBInstanceId"].(string), item["Engine"].(string), item["EngineVersion"].(string))
if paramError == nil {
parameterDetail := make([]map[string]interface{}, 0)
for _, val := range paramResponse {
item := val.(map[string]interface{})
parameterDetail = append(parameterDetail, map[string]interface{}{
"force_modify": item["ForceModify"],
"checking_code": item["CheckingCode"],
"parameter_value": item["ParameterValue"],
"force_restart": item["ForceRestart"],
"parameter_name": item["ParameterName"],
"parameter_description": item["ParameterDescription"],
})
}
mapping["parameters"] = parameterDetail
}
}
ids = append(ids, fmt.Sprint(item["DBInstanceId"]))
names = append(names, fmt.Sprint(item["DBInstanceDescription"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("total_count", totalCount); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"sort"
"strings"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDBZones() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDBZonesRead,
Schema: map[string]*schema.Schema{
"multi": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"multi_zone": {
Type: schema.TypeBool,
Default: false,
Optional: true,
},
"instance_charge_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: PostPaid,
ValidateFunc: validation.StringInSlice([]string{"PrePaid", "PostPaid"}, false),
},
"engine": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"MySQL", "SQLServer", "PostgreSQL", "PPAS", "MariaDB"}, false),
},
"engine_version": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"db_instance_class": {
Type: schema.TypeString,
Optional: true,
},
"category": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Basic", "HighAvailability", "AlwaysOn", "Finance"}, false),
},
"db_instance_storage_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"cloud_ssd", "local_ssd", "cloud_essd", "cloud_essd2", "cloud_essd3"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"zones": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"multi_zone_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
},
}
}
func dataSourceAlicloudDBZonesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
engines := make([]string, 0)
if v, ok := d.GetOk("engine"); ok && v.(string) != "" {
engines = append(engines, v.(string))
} else {
engines = []string{"MySQL", "SQLServer", "PostgreSQL", "PPAS", "MariaDB"}
}
action := "DescribeAvailableZones"
request := map[string]interface{}{
"RegionId": client.RegionId,
"SourceIp": client.SourceIp,
}
if v, ok := d.GetOk("engine_version"); ok && v.(string) != "" {
request["EngineVersion"] = v.(string)
}
if v, ok := d.GetOk("zone_id"); ok && v.(string) != "" {
request["ZoneId"] = v.(string)
}
instanceChargeType := d.Get("instance_charge_type").(string)
if instanceChargeType == string(PostPaid) {
request["CommodityCode"] = "bards"
} else {
request["CommodityCode"] = "rds"
}
multiZone := false
if v, ok := d.GetOkExists("multi_zone"); ok {
multiZone = v.(bool)
} else if v, ok := d.GetOkExists("multi"); ok {
multiZone = v.(bool)
}
var targetCategory, targetStorageType string
if v, ok := d.GetOk("category"); ok && v.(string) != "" {
targetCategory = v.(string)
}
if v, ok := d.GetOk("db_instance_storage_type"); ok && v.(string) != "" {
targetStorageType = v.(string)
}
var ids []string
var s []map[string]interface{}
var response map[string]interface{}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
for _, engine := range engines {
request["Engine"] = engine
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_db_zones", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.AvailableZones", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.AvailableZones", response)
}
for _, r := range resp.([]interface{}) {
availableZoneItem := r.(map[string]interface{})
zoneId := fmt.Sprint(availableZoneItem["ZoneId"])
if (multiZone && !strings.Contains(zoneId, MULTI_IZ_SYMBOL)) || (!multiZone && strings.Contains(zoneId, MULTI_IZ_SYMBOL)) {
continue
}
if targetCategory == "" && targetStorageType == "" {
ids = append(ids, zoneId)
continue
}
for _, r := range availableZoneItem["SupportedEngines"].([]interface{}) {
supportedEngineItem := r.(map[string]interface{})
for _, r := range supportedEngineItem["SupportedEngineVersions"].([]interface{}) {
supportedEngineVersionItem := r.(map[string]interface{})
for _, r := range supportedEngineVersionItem["SupportedCategorys"].([]interface{}) {
supportedCategoryItem := r.(map[string]interface{})
if targetCategory != "" && targetCategory != fmt.Sprint(supportedCategoryItem["Category"]) {
continue
}
if targetStorageType == "" {
ids = append(ids, zoneId)
goto NEXT
}
for _, r := range supportedCategoryItem["SupportedStorageTypes"].([]interface{}) {
supportedStorageTypeItem := r.(map[string]interface{})
if targetStorageType != fmt.Sprint(supportedStorageTypeItem["StorageType"]) {
continue
}
ids = append(ids, zoneId)
goto NEXT
}
}
}
}
NEXT:
continue
}
}
if len(ids) > 0 {
sort.Strings(ids)
}
for _, zoneId := range ids {
mapping := map[string]interface{}{
"id": zoneId,
"multi_zone_ids": splitMultiZoneId(zoneId),
}
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("zones", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDbfsInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDbfsInstancesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"attached", "unattached", "attaching", "creating", "deleted", "deleting", "detaching", "resizing", "snapshotting", "upgrading"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"attach_node_number": {
Type: schema.TypeInt,
Computed: true,
},
"category": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"dbfs_cluster_id": {
Type: schema.TypeString,
Computed: true,
},
"ecs_list": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ecs_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_raid": {
Type: schema.TypeBool,
Computed: true,
},
"encryption": {
Type: schema.TypeBool,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_name": {
Type: schema.TypeString,
Computed: true,
},
"kms_key_id": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"performance_level": {
Type: schema.TypeString,
Computed: true,
},
"raid_stripe_unit_number": {
Type: schema.TypeString,
Computed: true,
},
"size": {
Type: schema.TypeInt,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudDbfsInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListDbfs"
request := make(map[string]interface{})
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var instanceNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
instanceNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewDbfsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-18"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_dbfs_instances", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.DBFSInfo", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.DBFSInfo", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if instanceNameRegex != nil && !instanceNameRegex.MatchString(fmt.Sprint(item["FsName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["FsId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"attach_node_number": formatInt(object["AttachNodeNumber"]),
"category": object["Category"],
"create_time": object["CreatedTime"],
"dbfs_cluster_id": object["DBFSClusterId"],
"enable_raid": object["EnableRaid"],
"encryption": object["Encryption"],
"id": fmt.Sprint(object["FsId"]),
"instance_id": fmt.Sprint(object["FsId"]),
"instance_name": object["FsName"],
"kms_key_id": object["KMSKeyId"],
"payment_type": convertDbfsInstancePaymentTypeResponse(fmt.Sprint(object["PayType"])),
"performance_level": object["PerformanceLevel"],
"raid_stripe_unit_number": fmt.Sprint(object["RaidStrip"]),
"size": formatInt(object["SizeG"]),
"status": object["Status"],
"zone_id": object["ZoneId"],
}
ecsList := make([]map[string]interface{}, 0)
if ecsListList, ok := object["EcsList"].([]interface{}); ok {
for _, v := range ecsListList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"ecs_id": m1["EcsId"],
}
ecsList = append(ecsList, temp1)
}
}
}
mapping["ecs_list"] = ecsList
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["FsName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDcdnDomains() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDcdnDomainsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"change_end_time": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"change_start_time": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"check_domain_show": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"domain_search_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"security_token": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"check_failed", "checking", "configure_failed", "configuring", "offline", "online"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"domains": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cert_name": {
Type: schema.TypeString,
Computed: true,
},
"cname": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"domain_name": {
Type: schema.TypeString,
Computed: true,
},
"gmt_modified": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"ssl_protocol": {
Type: schema.TypeString,
Computed: true,
},
"ssl_pub": {
Type: schema.TypeString,
Computed: true,
},
"scope": {
Type: schema.TypeString,
Computed: true,
},
"sources": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"content": {
Type: schema.TypeString,
Computed: true,
},
"enabled": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeInt,
Computed: true,
},
"priority": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"weight": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudDcdnDomainsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDcdnUserDomains"
request := make(map[string]interface{})
if v, ok := d.GetOk("change_end_time"); ok {
request["ChangeEndTime"] = v
}
if v, ok := d.GetOk("change_start_time"); ok {
request["ChangeStartTime"] = v
}
if v, ok := d.GetOkExists("check_domain_show"); ok {
request["CheckDomainShow"] = v
}
if v, ok := d.GetOk("domain_search_type"); ok {
request["DomainSearchType"] = v
}
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("security_token"); ok {
request["SecurityToken"] = v
}
if v, ok := d.GetOk("status"); ok {
request["DomainStatus"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var domainNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
domainNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewDcdnClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_dcdn_domains", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Domains.PageData", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Domains.PageData", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if domainNameRegex != nil {
if !domainNameRegex.MatchString(item["DomainName"].(string)) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DomainName"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"cname": object["Cname"],
"id": fmt.Sprint(object["DomainName"]),
"domain_name": fmt.Sprint(object["DomainName"]),
"gmt_modified": object["GmtModified"],
"resource_group_id": object["ResourceGroupId"],
"ssl_protocol": object["SSLProtocol"],
"status": object["DomainStatus"],
}
if v, ok := object["Sources"].(map[string]interface{})["Source"].([]interface{}); ok {
source := make([]map[string]interface{}, 0)
for _, val := range v {
item := val.(map[string]interface{})
source = append(source, map[string]interface{}{
"content": item["Content"],
"port": item["Port"],
"priority": item["Priority"],
"type": item["Type"],
"weight": item["Weight"],
})
}
mapping["sources"] = source
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["DomainName"]))
names = append(names, object["DomainName"].(string))
s = append(s, mapping)
continue
}
dcdnService := DcdnService{client}
id := fmt.Sprint(object["DomainName"])
getResp, err := dcdnService.DescribeDcdnDomainCertificateInfo(id)
if err != nil {
return WrapError(err)
}
mapping["cert_name"] = getResp["CertName"]
mapping["ssl_pub"] = getResp["SSLPub"]
getResp1, err := dcdnService.DescribeDcdnDomain(id)
if err != nil {
return WrapError(err)
}
mapping["description"] = getResp1["Description"]
mapping["scope"] = getResp1["Scope"]
ids = append(ids, fmt.Sprint(object["DomainName"]))
names = append(names, object["DomainName"].(string))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("domains", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDcdnService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDcdnServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudDcdnServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("DcdnServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
action := "OpenDcdnService"
request := map[string]interface{}{
"BillType": "PayByTraffic",
"WebsocketBillType": "websockettraffic",
}
conn, err := meta.(*connectivity.AliyunClient).NewTeaCommonClient(connectivity.OpenDcdnService)
if err != nil {
return WrapError(err)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"QPS Limit Exceeded"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
addDebug(action, response, nil)
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"DcdnService.HasOpened", "ORDER.OPEND"}) {
d.SetId("DcdnServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_dcdn_service", action, AlibabaCloudSdkGoERROR)
}
d.SetId("DcdnServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
package alicloud
import (
"encoding/json"
"regexp"
"strconv"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ddosbgp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDdosbgpInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDdosbgpInstancesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"region": {
Type: schema.TypeString,
Computed: true,
},
"base_bandwidth": {
Type: schema.TypeInt,
Computed: true,
},
"bandwidth": {
Type: schema.TypeInt,
Computed: true,
},
"ip_type": {
Type: schema.TypeString,
Computed: true,
},
"ip_count": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudDdosbgpInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ddosbgp.CreateDescribeInstanceListRequest()
request.PageSize = requests.Integer(strconv.Itoa(PageSizeSmall))
request.PageNo = "1"
request.RegionId = client.RegionId
request.DdosRegionId = client.RegionId
var instances []ddosbgp.Instance
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
if r, err := regexp.Compile(v.(string)); err == nil {
nameRegex = r
}
}
if v, ok := d.GetOk("ids"); ok {
idsStr, _ := json.Marshal(v)
request.InstanceIdList = string(idsStr)
}
// describe ddosbgp instance filtered by name_regex
for {
raw, err := client.WithDdosbgpClient(func(ddosbgpClient *ddosbgp.Client) (interface{}, error) {
return ddosbgpClient.DescribeInstanceList(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ddosbgp_instances", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
resp, _ := raw.(*ddosbgp.DescribeInstanceListResponse)
if len(resp.InstanceList) < 1 {
break
}
for _, item := range resp.InstanceList {
if nameRegex != nil && !nameRegex.MatchString(item.Remark) {
continue
}
instances = append(instances, item)
}
if len(resp.InstanceList) < PageSizeLarge {
break
}
currentPageNo, err := strconv.Atoi(string(request.PageNo))
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ddosbgp_instances", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
if page, err := getNextpageNumber(requests.NewInteger(currentPageNo)); err != nil {
return WrapError(err)
} else {
request.PageNo = requests.Integer(page)
}
}
// describe instance spec filtered by instanceids
var nameMap map[string]string = make(map[string]string)
var instanceIds []string
var ipTypeMap map[string]string = make(map[string]string)
var instanceTypeMap map[string]string = make(map[string]string)
for _, instance := range instances {
instanceIds = append(instanceIds, instance.InstanceId)
nameMap[instance.InstanceId] = instance.Remark
ipTypeMap[instance.InstanceId] = instance.IpType
instanceTypeMap[instance.InstanceId] = instance.InstanceType
}
if len(instanceIds) < 1 {
return WrapError(extractDdosbgpInstance(d, nameMap, ipTypeMap, instanceTypeMap, []ddosbgp.InstanceSpec{}))
}
specReq := ddosbgp.CreateDescribeInstanceSpecsRequest()
instanceIdsStr, _ := json.Marshal(instanceIds)
specReq.InstanceIdList = string(instanceIdsStr)
specReq.RegionId = client.RegionId
specReq.DdosRegionId = client.RegionId
raw, err := client.WithDdosbgpClient(func(ddosbgpClient *ddosbgp.Client) (interface{}, error) {
return ddosbgpClient.DescribeInstanceSpecs(specReq)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ddosbgp_instances", specReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
resp, _ := raw.(*ddosbgp.DescribeInstanceSpecsResponse)
return WrapError(extractDdosbgpInstance(d, nameMap, ipTypeMap, instanceTypeMap, resp.InstanceSpecs))
}
func extractDdosbgpInstance(d *schema.ResourceData, nameMap map[string]string, ipTypeMap map[string]string, instanceTypeMap map[string]string, instanceSpecs []ddosbgp.InstanceSpec) error {
var instanceIds []string
var names []string
var s []map[string]interface{}
for _, item := range instanceSpecs {
ddosbgpInstanceType := string(Enterprise)
if instanceTypeMap[item.InstanceId] == "0" {
ddosbgpInstanceType = string(Professional)
}
mapping := map[string]interface{}{
"id": item.InstanceId,
"name": nameMap[item.InstanceId],
"region": item.Region,
"bandwidth": item.PackConfig.PackAdvThre,
"base_bandwidth": item.PackConfig.PackBasicThre,
"ip_type": ipTypeMap[item.InstanceId],
"ip_count": item.PackConfig.IpSpec,
"type": ddosbgpInstanceType,
}
instanceIds = append(instanceIds, item.InstanceId)
names = append(names, nameMap[item.InstanceId])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(instanceIds))
if err := d.Set("ids", instanceIds); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDdoscooDomainResources() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDdoscooDomainResourcesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"instance_ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"query_domain_pattern": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"fuzzy", "exact"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"resources": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"black_list": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"cc_enabled": {
Type: schema.TypeBool,
Computed: true,
},
"cc_rule_enabled": {
Type: schema.TypeBool,
Computed: true,
},
"cc_template": {
Type: schema.TypeString,
Computed: true,
},
"cert_name": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"domain": {
Type: schema.TypeString,
Computed: true,
},
"http2_enable": {
Type: schema.TypeBool,
Computed: true,
},
"https_ext": {
Type: schema.TypeString,
Computed: true,
},
"instance_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"policy_mode": {
Type: schema.TypeString,
Computed: true,
},
"proxy_enabled": {
Type: schema.TypeBool,
Computed: true,
},
"proxy_types": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"proxy_ports": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeInt},
},
"proxy_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"real_servers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"rs_type": {
Type: schema.TypeInt,
Computed: true,
},
"ssl_ciphers": {
Type: schema.TypeString,
Computed: true,
},
"ssl_protocols": {
Type: schema.TypeString,
Computed: true,
},
"white_list": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
},
}
}
func dataSourceAlicloudDdoscooDomainResourcesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDomainResource"
request := make(map[string]interface{})
if v, ok := d.GetOk("instance_ids"); ok {
request["InstanceIds"] = v
}
if v, ok := d.GetOk("query_domain_pattern"); ok {
request["QueryDomainPattern"] = v
}
request["PageSize"] = PageSizeSmall
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewDdoscooClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ddoscoo_domain_resources", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.WebRules", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.WebRules", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Domain"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"black_list": object["BlackList"],
"cc_enabled": object["CcEnabled"],
"cc_rule_enabled": object["CcRuleEnabled"],
"cc_template": object["CcTemplate"],
"cert_name": object["CertName"],
"id": fmt.Sprint(object["Domain"]),
"domain": fmt.Sprint(object["Domain"]),
"http2_enable": object["Http2Enable"],
"https_ext": object["HttpsExt"],
"instance_ids": object["InstanceIds"],
"policy_mode": object["PolicyMode"],
"proxy_enabled": object["ProxyEnabled"],
"real_servers": object["RealServers"],
"rs_type": formatInt(object["RsType"]),
"ssl_ciphers": object["SslCiphers"],
"ssl_protocols": object["SslProtocols"],
"white_list": object["WhiteList"],
}
proxyTypes := make([]map[string]interface{}, 0)
if proxyTypesList, ok := object["ProxyTypes"].([]interface{}); ok {
for _, v := range proxyTypesList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"proxy_ports": m1["ProxyPorts"],
"proxy_type": m1["ProxyType"],
}
proxyTypes = append(proxyTypes, temp1)
}
}
}
mapping["proxy_types"] = proxyTypes
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("resources", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"strconv"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ddoscoo"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDdoscooInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDdoscooInstancesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"base_bandwidth": {
Type: schema.TypeInt,
Computed: true,
},
"bandwidth": {
Type: schema.TypeInt,
Computed: true,
},
"service_bandwidth": {
Type: schema.TypeInt,
Computed: true,
},
"port_count": {
Type: schema.TypeInt,
Computed: true,
},
"domain_count": {
Type: schema.TypeInt,
Computed: true,
},
"remark": {
Type: schema.TypeString,
Computed: true,
},
"ip_mode": {
Type: schema.TypeString,
Computed: true,
},
"debt_status": {
Type: schema.TypeInt,
Computed: true,
},
"edition": {
Type: schema.TypeInt,
Computed: true,
},
"ip_version": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeInt,
Computed: true,
},
"enabled": {
Type: schema.TypeInt,
Computed: true,
},
"expire_time": {
Type: schema.TypeInt,
Computed: true,
},
"create_time": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudDdoscooInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ddoscoo.CreateDescribeInstancesRequest()
request.RegionId = client.RegionId
request.PageSize = strconv.Itoa(PageSizeSmall)
request.PageNumber = "1"
var instances []ddoscoo.Instance
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
if r, err := regexp.Compile(v.(string)); err == nil {
nameRegex = r
}
}
if v, ok := d.GetOk("ids"); ok && len(v.([]interface{})) > 0 {
ids := expandStringList(v.([]interface{}))
request.InstanceIds = &ids
}
// describe ddoscoo instance filtered by name_regex
for {
raw, err := client.WithDdoscooClient(func(ddoscooClient *ddoscoo.Client) (interface{}, error) {
return ddoscooClient.DescribeInstances(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ddoscoo_instances", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ddoscoo.DescribeInstancesResponse)
if len(response.Instances) < 1 {
break
}
for _, item := range response.Instances {
if nameRegex != nil {
if !nameRegex.MatchString(item.Remark) {
continue
}
}
instances = append(instances, item)
}
if len(response.Instances) < PageSizeLarge {
break
}
currentPageNo, err := strconv.Atoi(request.PageNumber)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ddoscoo_instances", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
if page, err := getNextpageNumber(requests.NewInteger(currentPageNo)); err != nil {
return WrapError(err)
} else {
request.PageNumber = string(page)
}
}
// describe instance spec filtered by instanceids
nameMap := make(map[string]string)
var instanceIds []string
for _, instance := range instances {
instanceIds = append(instanceIds, instance.InstanceId)
nameMap[instance.InstanceId] = instance.Remark
}
if len(instanceIds) < 1 {
return WrapError(extractDdoscooInstance(d, nameMap, []ddoscoo.InstanceSpec{}, instances))
}
specReq := ddoscoo.CreateDescribeInstanceSpecsRequest()
specReq.InstanceIds = &instanceIds
raw, err := client.WithDdoscooClient(func(ddoscooClient *ddoscoo.Client) (interface{}, error) {
return ddoscooClient.DescribeInstanceSpecs(specReq)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ddoscoo_instances", specReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(specReq.GetActionName(), raw, specReq.RpcRequest, specReq)
response, _ := raw.(*ddoscoo.DescribeInstanceSpecsResponse)
return WrapError(extractDdoscooInstance(d, nameMap, response.InstanceSpecs, instances))
}
func extractDdoscooInstance(d *schema.ResourceData, nameMap map[string]string, instanceSpecs []ddoscoo.InstanceSpec, instance []ddoscoo.Instance) error {
var instanceIds []string
var names []string
var s []map[string]interface{}
for i, item := range instanceSpecs {
mapping := map[string]interface{}{
"id": item.InstanceId,
"name": nameMap[item.InstanceId],
"bandwidth": item.ElasticBandwidth,
"base_bandwidth": item.BaseBandwidth,
"service_bandwidth": item.BandwidthMbps,
"port_count": item.PortLimit,
"domain_count": item.DomainLimit,
"remark": instance[i].Remark,
"ip_mode": instance[i].IpMode,
"debt_status": instance[i].DebtStatus,
"edition": instance[i].Edition,
"ip_version": instance[i].IpVersion,
"status": instance[i].Status,
"enabled": instance[i].Enabled,
"expire_time": instance[i].ExpireTime,
"create_time": instance[i].CreateTime,
}
instanceIds = append(instanceIds, item.InstanceId)
names = append(names, nameMap[item.InstanceId])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(instanceIds))
if err := d.Set("ids", instanceIds); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDdoscooPorts() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDdoscooPortsRead,
Schema: map[string]*schema.Schema{
"frontend_port": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"frontend_protocol": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"tcp", "udp"}, false),
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ports": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"backend_port": {
Type: schema.TypeString,
Computed: true,
},
"frontend_port": {
Type: schema.TypeString,
Computed: true,
},
"frontend_protocol": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"real_servers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
},
}
}
func dataSourceAlicloudDdoscooPortsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribePort"
request := make(map[string]interface{})
if v, ok := d.GetOk("frontend_port"); ok {
request["FrontendPort"] = v
}
if v, ok := d.GetOk("frontend_protocol"); ok {
request["FrontendProtocol"] = v
}
request["InstanceId"] = d.Get("instance_id")
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewDdoscooClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ddoscoo_ports", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.NetworkRules", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.NetworkRules", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprintf("%v:%v:%v", item["InstanceId"], item["FrontendPort"], item["FrontendProtocol"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"backend_port": fmt.Sprint(object["BackendPort"]),
"frontend_port": fmt.Sprint(object["FrontendPort"]),
"frontend_protocol": fmt.Sprint(object["FrontendProtocol"]),
"instance_id": fmt.Sprint(object["InstanceId"]),
"id": fmt.Sprintf("%v:%v:%v", object["InstanceId"], object["FrontendPort"], object["FrontendProtocol"]),
"real_servers": object["RealServers"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("ports", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDfsAccessGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDfsAccessGroupsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"limit": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"order_by": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"CreateTime", "AccessGroupName"}, false),
},
"order_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ASC", "DESC"}, false),
},
"start_offset": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"access_group_id": {
Type: schema.TypeString,
Computed: true,
},
"access_group_name": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"mount_point_count": {
Type: schema.TypeInt,
Computed: true,
},
"network_type": {
Type: schema.TypeString,
Computed: true,
},
"rule_count": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudDfsAccessGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListAccessGroups"
request := make(map[string]interface{})
if v, ok := d.GetOk("limit"); ok {
request["Limit"] = v
}
if v, ok := d.GetOk("order_by"); ok {
request["OrderBy"] = v
}
if v, ok := d.GetOk("order_type"); ok {
request["OrderType"] = v
}
request["InputRegionId"] = client.RegionId
if v, ok := d.GetOk("start_offset"); ok {
request["StartOffset"] = v
}
var objects []map[string]interface{}
var accessGroupNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
accessGroupNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewAlidfsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-06-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_dfs_access_groups", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.AccessGroups", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.AccessGroups", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if accessGroupNameRegex != nil && !accessGroupNameRegex.MatchString(fmt.Sprint(item["AccessGroupName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["AccessGroupId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["AccessGroupId"]),
"access_group_id": fmt.Sprint(object["AccessGroupId"]),
"access_group_name": object["AccessGroupName"],
"create_time": object["CreateTime"],
"description": object["Description"],
"mount_point_count": formatInt(object["MountPointCount"]),
"network_type": object["NetworkType"],
"rule_count": formatInt(object["RuleCount"]),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["AccessGroupName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudDfsAccessRules() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDfsAccessRulesRead,
Schema: map[string]*schema.Schema{
"access_group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"access_group_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"access_rule_id": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"network_segment": {
Type: schema.TypeString,
Computed: true,
},
"priority": {
Type: schema.TypeInt,
Computed: true,
},
"rw_access_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudDfsAccessRulesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListAccessRules"
request := make(map[string]interface{})
request["AccessGroupId"] = d.Get("access_group_id")
request["InputRegionId"] = client.RegionId
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewAlidfsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-06-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_dfs_access_rules", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.AccessRules", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.AccessRules", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["AccessGroupId"], ":", item["AccessRuleId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"access_group_id": object["AccessGroupId"],
"id": fmt.Sprint(object["AccessGroupId"], ":", object["AccessRuleId"]),
"access_rule_id": fmt.Sprint(object["AccessRuleId"]),
"create_time": object["CreateTime"],
"description": object["Description"],
"network_segment": object["NetworkSegment"],
"priority": formatInt(object["Priority"]),
"rw_access_type": object["RWAccessType"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("rules", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDfsFileSystems() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDfsFileSystemsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"systems": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"file_system_id": {
Type: schema.TypeString,
Computed: true,
},
"file_system_name": {
Type: schema.TypeString,
Computed: true,
},
"mount_point_count": {
Type: schema.TypeInt,
Computed: true,
},
"number_of_directories": {
Type: schema.TypeInt,
Computed: true,
},
"number_of_files": {
Type: schema.TypeInt,
Computed: true,
},
"protocol_type": {
Type: schema.TypeString,
Computed: true,
},
"provisioned_throughput_in_mi_bps": {
Type: schema.TypeInt,
Computed: true,
},
"space_capacity": {
Type: schema.TypeInt,
Computed: true,
},
"storage_package_id": {
Type: schema.TypeString,
Computed: true,
},
"storage_type": {
Type: schema.TypeString,
Computed: true,
},
"throughput_mode": {
Type: schema.TypeString,
Computed: true,
},
"used_space_size": {
Type: schema.TypeFloat,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudDfsFileSystemsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListFileSystems"
request := make(map[string]interface{})
request["InputRegionId"] = client.RegionId
var objects []map[string]interface{}
var fileSystemNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
fileSystemNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewAlidfsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-06-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_dfs_file_systems", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.FileSystems", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.FileSystems", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if fileSystemNameRegex != nil && !fileSystemNameRegex.MatchString(fmt.Sprint(item["FileSystemName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["FileSystemId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": object["CreateTime"],
"description": object["Description"],
"id": fmt.Sprint(object["FileSystemId"]),
"file_system_id": fmt.Sprint(object["FileSystemId"]),
"file_system_name": object["FileSystemName"],
"mount_point_count": object["MountPointCount"],
"number_of_directories": object["NumberOfDirectories"],
"number_of_files": object["NumberOfFiles"],
"protocol_type": object["ProtocolType"],
"provisioned_throughput_in_mi_bps": object["ProvisionedThroughputInMiBps"],
"space_capacity": object["SpaceCapacity"],
"storage_package_id": object["StoragePackageId"],
"storage_type": object["StorageType"],
"throughput_mode": object["ThroughputMode"],
"used_space_size": object["UsedSpaceSize"],
"zone_id": object["ZoneId"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["FileSystemName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("systems", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDfsMountPoints() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDfsMountPointsRead,
Schema: map[string]*schema.Schema{
"file_system_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Inactive"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"points": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"access_group_id": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"file_system_id": {
Type: schema.TypeString,
Computed: true,
},
"mount_point_domain": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"mount_point_id": {
Type: schema.TypeString,
Computed: true,
},
"network_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudDfsMountPointsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListMountPoints"
request := make(map[string]interface{})
request["FileSystemId"] = d.Get("file_system_id")
request["InputRegionId"] = client.RegionId
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewAlidfsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-06-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_dfs_mount_points", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.MountPoints", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.MountPoints", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["FileSystemId"], ":", item["MountPointId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"access_group_id": object["AccessGroupId"],
"create_time": object["CreateTime"],
"description": object["Description"],
"file_system_id": object["FileSystemId"],
"mount_point_domain": object["MountPointDomain"],
"id": fmt.Sprint(object["FileSystemId"], ":", object["MountPointId"]),
"mount_point_id": fmt.Sprint(object["MountPointId"]),
"network_type": object["NetworkType"],
"status": object["Status"],
"vswitch_id": object["VSwitchId"],
"vpc_id": object["VpcId"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("points", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"strconv"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudDfsZones() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDfsZonesRead,
Schema: map[string]*schema.Schema{
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"zones": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
"options": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"storage_type": {
Type: schema.TypeString,
Computed: true,
},
"protocol_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudDfsZonesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "GetRegion"
request := make(map[string]interface{})
request["InputRegionId"] = client.RegionId
var response map[string]interface{}
conn, err := client.NewAlidfsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-06-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_dfs_zones", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.AvailableZones", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.AvailableZones", response)
}
s := make([]map[string]interface{}, 0)
for _, object := range resp.([]interface{}) {
if zoneMap, ok := object.(map[string]interface{}); ok {
mapping := map[string]interface{}{
"zone_id": fmt.Sprint(zoneMap["ZoneId"]),
}
options := make([]interface{}, 0)
for _, optionArg := range zoneMap["Options"].([]interface{}) {
optionMap := optionArg.(map[string]interface{})
singleObj := make(map[string]interface{}, 0)
singleObj["storage_type"] = fmt.Sprint(optionMap["StorageType"])
singleObj["protocol_type"] = fmt.Sprint(optionMap["ProtocolType"])
options = append(options, singleObj)
}
mapping["options"] = options
s = append(s, mapping)
}
}
d.SetId(strconv.FormatInt(time.Now().Unix(), 16))
if err := d.Set("zones", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDirectMailDomains() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDirectMailDomainsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"key_word": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(4, 50),
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"0", "1", "2", "3", "4"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"domains": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cname_auth_status": {
Type: schema.TypeString,
Computed: true,
},
"cname_confirm_status": {
Type: schema.TypeString,
Computed: true,
},
"cname_record": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"default_domain": {
Type: schema.TypeString,
Computed: true,
},
"dns_mx": {
Type: schema.TypeString,
Computed: true,
},
"dns_spf": {
Type: schema.TypeString,
Computed: true,
},
"dns_txt": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"domain_id": {
Type: schema.TypeString,
Computed: true,
},
"domain_name": {
Type: schema.TypeString,
Computed: true,
},
"domain_type": {
Type: schema.TypeString,
Computed: true,
},
"icp_status": {
Type: schema.TypeString,
Computed: true,
},
"mx_auth_status": {
Type: schema.TypeString,
Computed: true,
},
"mx_record": {
Type: schema.TypeString,
Computed: true,
},
"spf_auth_status": {
Type: schema.TypeString,
Computed: true,
},
"spf_record": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tl_domain_name": {
Type: schema.TypeString,
Computed: true,
},
"tracef_record": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudDirectMailDomainsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "QueryDomainByParam"
request := make(map[string]interface{})
request["PageSize"] = PageSizeLarge
request["PageNo"] = 1
if v, ok := d.GetOk("key_word"); ok {
request["KeyWord"] = v
}
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
var objects []map[string]interface{}
var domainNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
domainNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewDmClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-11-23"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_direct_mail_domains", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.data.domain", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.data.domain", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if domainNameRegex != nil && !domainNameRegex.MatchString(fmt.Sprint(item["DomainName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DomainId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNo"] = request["PageNo"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"cname_auth_status": object["CnameAuthStatus"],
"create_time": object["CreateTime"],
"id": fmt.Sprint(object["DomainId"]),
"domain_id": fmt.Sprint(object["DomainId"]),
"domain_name": object["DomainName"],
"icp_status": object["IcpStatus"],
"mx_auth_status": object["MxAuthStatus"],
"spf_auth_status": object["SpfAuthStatus"],
"status": object["DomainStatus"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["DomainName"])
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["DomainId"])
dmService := DmService{client}
getResp, err := dmService.DescribeDirectMailDomain(id)
if err != nil {
return WrapError(err)
}
mapping["cname_confirm_status"] = getResp["CnameConfirmStatus"]
mapping["cname_record"] = getResp["CnameRecord"]
mapping["default_domain"] = getResp["DefaultDomain"]
mapping["dns_mx"] = getResp["DnsMx"]
mapping["dns_spf"] = getResp["DnsSpf"]
mapping["dns_txt"] = getResp["DnsTxt"]
mapping["domain_type"] = getResp["DomainType"]
mapping["mx_record"] = getResp["MxRecord"]
mapping["spf_record"] = getResp["SpfRecord"]
mapping["tl_domain_name"] = getResp["TlDomainName"]
mapping["tracef_record"] = getResp["TracefRecord"]
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("domains", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"encoding/json"
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDirectMailMailAddresses() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDirectMailMailAddressesRead,
Schema: map[string]*schema.Schema{
"key_word": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"sendtype": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"batch", "trigger"}, false),
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"0", "1"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"addresses": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_name": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"daily_count": {
Type: schema.TypeString,
Computed: true,
},
"daily_req_count": {
Type: schema.TypeString,
Computed: true,
},
"domain_status": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"mail_address_id": {
Type: schema.TypeString,
Computed: true,
},
"month_count": {
Type: schema.TypeString,
Computed: true,
},
"month_req_count": {
Type: schema.TypeString,
Computed: true,
},
"reply_address": {
Type: schema.TypeString,
Computed: true,
},
"reply_status": {
Type: schema.TypeString,
Computed: true,
},
"sendtype": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudDirectMailMailAddressesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "QueryMailAddressByParam"
request := make(map[string]interface{})
if v, ok := d.GetOk("key_word"); ok {
request["KeyWord"] = v
}
if v, ok := d.GetOk("sendtype"); ok {
request["Sendtype"] = v
}
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewDmClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-11-23"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_direct_mail_mail_addresses", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.data.mailAddress", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.data.mailAddress", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["MailAddressId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != string(item["AccountStatus"].(json.Number)) {
continue
}
objects = append(objects, item)
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"account_name": object["AccountName"],
"create_time": object["CreateTime"],
"daily_count": object["DailyCount"],
"daily_req_count": object["DailyReqCount"],
"domain_status": object["DomainStatus"],
"id": fmt.Sprint(object["MailAddressId"]),
"mail_address_id": fmt.Sprint(object["MailAddressId"]),
"month_count": object["MonthCount"],
"month_req_count": object["MonthReqCount"],
"reply_address": object["ReplyAddress"],
"reply_status": object["ReplyStatus"],
"sendtype": object["Sendtype"],
"status": object["AccountStatus"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("addresses", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDirectMailReceiverses() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDirectMailReceiversesRead,
Schema: map[string]*schema.Schema{
"key_word": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IntInSlice([]int{0, 1}),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"receiverses": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"receivers_alias": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"receivers_id": {
Type: schema.TypeString,
Computed: true,
},
"receivers_name": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudDirectMailReceiversesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "QueryReceiverByParam"
request := make(map[string]interface{})
request["PageSize"] = PageSizeLarge
request["PageNo"] = 1
if v, ok := d.GetOk("key_word"); ok {
request["KeyWord"] = v
}
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
var objects []map[string]interface{}
var receiversNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
receiversNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewDmClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-11-23"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_direct_mail_receiverses", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.data.receiver", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.data.receiver", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if receiversNameRegex != nil {
if !receiversNameRegex.MatchString(fmt.Sprint(item["ReceiversName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ReceiverId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNo"] = request["PageNo"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": object["CreateTime"],
"description": object["Desc"],
"receivers_alias": object["ReceiversAlias"],
"id": fmt.Sprint(object["ReceiverId"]),
"receivers_id": fmt.Sprint(object["ReceiverId"]),
"receivers_name": object["ReceiversName"],
"status": formatInt(object["ReceiversStatus"]),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["ReceiversName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("receiverses", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDirectMailTags() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDirectMailTagsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"tags": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"tag_id": {
Type: schema.TypeString,
Computed: true,
},
"tag_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudDirectMailTagsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "QueryTagByParam"
request := make(map[string]interface{})
request["PageSize"] = PageSizeLarge
request["PageNo"] = 1
var objects []map[string]interface{}
var tagNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
tagNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewDmClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-11-23"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_direct_mail_tags", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.data.tag", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.data.tag", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if tagNameRegex != nil && !tagNameRegex.MatchString(fmt.Sprint(item["TagName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["TagId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNo"] = request["PageNo"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["TagId"]),
"tag_id": fmt.Sprint(object["TagId"]),
"tag_name": object["TagName"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["TagName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("tags", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDmsEnterpriseInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDmsEnterpriseInstancesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
ConflictsWith: []string{"instance_alias_regex"},
},
"instance_alias_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
ConflictsWith: []string{"name_regex"},
},
"env_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"instance_source": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"instance_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"net_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"search_key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"DELETED", "DISABLE", "NORMAL", "UNAVAILABLE"}, false),
},
"tid": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"data_link_name": {
Type: schema.TypeString,
Computed: true,
},
"database_password": {
Type: schema.TypeString,
Computed: true,
},
"database_user": {
Type: schema.TypeString,
Computed: true,
},
"dba_id": {
Type: schema.TypeString,
Computed: true,
},
"dba_nick_name": {
Type: schema.TypeString,
Computed: true,
},
"ddl_online": {
Type: schema.TypeInt,
Computed: true,
},
"ecs_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"ecs_region": {
Type: schema.TypeString,
Computed: true,
},
"env_type": {
Type: schema.TypeString,
Computed: true,
},
"export_timeout": {
Type: schema.TypeInt,
Computed: true,
},
"host": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_name": {
Type: schema.TypeString,
Computed: true,
},
"instance_alias": {
Type: schema.TypeString,
Computed: true,
},
"instance_source": {
Type: schema.TypeString,
Computed: true,
},
"instance_type": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeInt,
Computed: true,
},
"query_timeout": {
Type: schema.TypeInt,
Computed: true,
},
"safe_rule_id": {
Type: schema.TypeString,
Computed: true,
},
"sid": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"use_dsql": {
Type: schema.TypeInt,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudDmsEnterpriseInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListInstances"
request := make(map[string]interface{})
if v, ok := d.GetOk("env_type"); ok {
request["EnvType"] = v
}
if v, ok := d.GetOk("instance_source"); ok {
request["InstanceSource"] = v
}
if v, ok := d.GetOk("instance_type"); ok {
request["DbType"] = v
}
if v, ok := d.GetOk("net_type"); ok {
request["NetType"] = v
}
if v, ok := d.GetOk("search_key"); ok {
request["SearchKey"] = v
}
if v, ok := d.GetOk("status"); ok {
request["InstanceState"] = v
}
if v, ok := d.GetOk("tid"); ok {
request["Tid"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var instanceNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
instanceNameRegex = r
}
if v, ok := d.GetOk("instance_alias_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
instanceNameRegex = r
}
var response map[string]interface{}
conn, err := client.NewDmsenterpriseClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-11-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_dms_enterprise_instances", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.InstanceList.Instance", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.InstanceList.Instance", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if instanceNameRegex != nil {
if !instanceNameRegex.MatchString(fmt.Sprint(item["InstanceAlias"])) {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["Host"], ":", formatInt(object["Port"])),
"data_link_name": object["DataLinkName"],
"database_password": object["DatabasePassword"],
"database_user": object["DatabaseUser"],
"dba_id": object["DbaId"],
"dba_nick_name": object["DbaNickName"],
"ddl_online": formatInt(object["DdlOnline"]),
"ecs_instance_id": object["EcsInstanceId"],
"ecs_region": object["EcsRegion"],
"env_type": object["EnvType"],
"export_timeout": formatInt(object["ExportTimeout"]),
"host": object["Host"],
"instance_id": object["InstanceId"],
"instance_name": object["InstanceAlias"],
"instance_alias": object["InstanceAlias"],
"instance_source": object["InstanceSource"],
"instance_type": object["InstanceType"],
"port": formatInt(object["Port"]),
"query_timeout": formatInt(object["QueryTimeout"]),
"safe_rule_id": object["SafeRuleId"],
"sid": object["Sid"],
"status": object["State"],
"use_dsql": formatInt(object["UseDsql"]),
"vpc_id": object["VpcId"],
}
ids = append(ids, fmt.Sprint(object["Host"], ":", formatInt(object["Port"])))
names = append(names, object["InstanceAlias"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDmsEnterpriseUsers() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDmsEnterpriseUsersRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"role": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"search_key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"DELETE", "DISABLE", "NORMAL"}, false),
},
"tid": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"users": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"mobile": {
Type: schema.TypeString,
Computed: true,
},
"parent_uid": {
Type: schema.TypeInt,
Computed: true,
},
"role_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeInt},
},
"role_names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"uid": {
Type: schema.TypeString,
Computed: true,
},
"user_id": {
Type: schema.TypeString,
Computed: true,
},
"user_name": {
Type: schema.TypeString,
Computed: true,
},
"nick_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudDmsEnterpriseUsersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListUsers"
request := make(map[string]interface{})
if v, ok := d.GetOk("role"); ok {
request["Role"] = v
}
if v, ok := d.GetOk("search_key"); ok {
request["SearchKey"] = v
}
if v, ok := d.GetOk("status"); ok {
request["UserState"] = v
}
if v, ok := d.GetOk("tid"); ok {
request["Tid"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var userNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
userNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewDmsenterpriseClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-11-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_dms_enterprise_users", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.UserList.User", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.UserList.User", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if userNameRegex != nil {
if !userNameRegex.MatchString(fmt.Sprint(item["NickName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Uid"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"mobile": object["Mobile"],
"parent_uid": formatInt(object["ParentUid"]),
"role_ids": object["RoleIdList"].(map[string]interface{})["RoleIds"],
"role_names": object["RoleNameList"].(map[string]interface{})["RoleNames"],
"status": object["State"],
"id": fmt.Sprint(object["Uid"]),
"uid": fmt.Sprint(object["Uid"]),
"user_id": object["UserId"],
"user_name": object["NickName"],
"nick_name": object["NickName"],
}
ids = append(ids, fmt.Sprint(object["Uid"]))
names = append(names, object["NickName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("users", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"github.com/aliyun/alibaba-cloud-sdk-go/services/alidns"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDnsDomainTxtGuid() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDnsDomainTxtGuidRead,
Schema: map[string]*schema.Schema{
"domain_name": {
Type: schema.TypeString,
Required: true,
},
"type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"ADD_SUB_DOMAIN", "RETRIEVAL"}, false),
},
"lang": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"en", "zh", "jp"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"rr": {
Type: schema.TypeString,
Computed: true,
},
"value": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudDnsDomainTxtGuidRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := alidns.CreateGetTxtRecordForVerifyRequest()
request.RegionId = client.RegionId
domainName := d.Get("domain_name").(string)
request.DomainName = domainName
request.Type = d.Get("type").(string)
if lang, ok := d.GetOk("lang"); ok {
request.Lang = lang.(string)
}
raw, err := client.WithDnsClient(func(dnsclient *alidns.Client) (i interface{}, err error) {
return dnsclient.GetTxtRecordForVerify(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_dns_domain_txt_guid", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response := raw.(*alidns.GetTxtRecordForVerifyResponse)
rr := response.RR
value := response.Value
s := map[string]interface{}{
"rr": rr,
"value": value,
}
ids := []string{domainName, rr, value}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("rr", rr); err != nil {
return WrapError(err)
}
if err := d.Set("value", value); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/alidns"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudDnsGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDnsGroupsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"group_id": {
Type: schema.TypeString,
Computed: true,
},
"group_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudDnsGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := alidns.CreateDescribeDomainGroupsRequest()
var allGroups []alidns.DomainGroup
request.RegionId = client.RegionId
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
for {
raw, err := client.WithDnsClient(func(dnsClient *alidns.Client) (interface{}, error) {
return dnsClient.DescribeDomainGroups(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_dns_groups", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*alidns.DescribeDomainGroupsResponse)
groups := response.DomainGroups.DomainGroup
for _, domainGroup := range groups {
if len(idsMap) > 0 {
if _, ok := idsMap[domainGroup.GroupId]; !ok {
continue
}
}
allGroups = append(allGroups, domainGroup)
}
if len(groups) < PageSizeLarge {
break
}
if page, err := getNextpageNumber(request.PageNumber); err != nil {
return WrapError(err)
} else {
request.PageNumber = page
}
}
var filteredGroups []alidns.DomainGroup
if v, ok := d.GetOk("name_regex"); ok && v.(string) != "" {
r := regexp.MustCompile(v.(string))
for _, group := range allGroups {
if r.MatchString(group.GroupName) {
filteredGroups = append(filteredGroups, group)
}
}
} else {
filteredGroups = allGroups[:]
}
return groupsDecriptionAttributes(d, filteredGroups, meta)
}
func groupsDecriptionAttributes(d *schema.ResourceData, groupTypes []alidns.DomainGroup, meta interface{}) error {
var ids []string
var names []string
var s []map[string]interface{}
for _, group := range groupTypes {
mapping := map[string]interface{}{
"group_id": group.GroupId,
"group_name": group.GroupName,
}
ids = append(ids, group.GroupId)
names = append(names, group.GroupName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/alidns"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDnsRecords() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDnsRecordsRead,
Schema: map[string]*schema.Schema{
"domain_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"host_record_regex": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"value_regex": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
// must be one of [A, NS, MX, TXT, CNAME, SRV, AAAA, CAA, REDIRECT_URL, FORWORD_URL]
ValidateFunc: validation.StringInSlice([]string{"A", "NS", "MX", "TXT", "CNAME", "SRV", "AAAA", "CAA", "REDIRECT_URL", "FORWORD_URL"}, false),
},
"line": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"enable", "disable"}, true),
},
"is_locked": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"urls": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
// Computed values
"records": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"record_id": {
Type: schema.TypeString,
Computed: true,
},
"domain_name": {
Type: schema.TypeString,
Computed: true,
},
"host_record": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"value": {
Type: schema.TypeString,
Computed: true,
},
"ttl": {
Type: schema.TypeFloat,
Computed: true,
},
"priority": {
Type: schema.TypeInt,
Computed: true,
},
"line": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"locked": {
Type: schema.TypeBool,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudDnsRecordsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := alidns.CreateDescribeDomainRecordsRequest()
request.RegionId = client.RegionId
request.DomainName = d.Get("domain_name").(string)
if v, ok := d.GetOk("type"); ok && v.(string) != "" {
request.TypeKeyWord = v.(string)
}
var allRecords []alidns.Record
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
for {
raw, err := client.WithDnsClient(func(dnsClient *alidns.Client) (interface{}, error) {
return dnsClient.DescribeDomainRecords(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_dns_records", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*alidns.DescribeDomainRecordsResponse)
records := response.DomainRecords.Record
for _, record := range records {
allRecords = append(allRecords, record)
}
if len(records) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
var filteredRecords []alidns.Record
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
for _, record := range allRecords {
if v, ok := d.GetOk("line"); ok && v.(string) != "" && strings.ToUpper(record.Line) != strings.ToUpper(v.(string)) {
continue
}
if v, ok := d.GetOk("status"); ok && v.(string) != "" && strings.ToUpper(record.Status) != strings.ToUpper(v.(string)) {
continue
}
if v, ok := d.GetOk("is_locked"); ok && record.Locked != v.(bool) {
continue
}
if v, ok := d.GetOk("host_record_regex"); ok && v.(string) != "" {
r := regexp.MustCompile(v.(string))
if !r.MatchString(record.RR) {
continue
}
}
if v, ok := d.GetOk("value_regex"); ok && v.(string) != "" {
r := regexp.MustCompile(v.(string))
if !r.MatchString(record.Value) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[record.RecordId]; !ok {
continue
}
}
filteredRecords = append(filteredRecords, record)
}
return recordsDecriptionAttributes(d, filteredRecords, meta)
}
func recordsDecriptionAttributes(d *schema.ResourceData, recordTypes []alidns.Record, meta interface{}) error {
var ids []string
var urls []string
var s []map[string]interface{}
for _, record := range recordTypes {
mapping := map[string]interface{}{
"record_id": record.RecordId,
"domain_name": record.DomainName,
"line": record.Line,
"host_record": record.RR,
"type": record.Type,
"value": record.Value,
"status": strings.ToLower(record.Status),
"locked": record.Locked,
"ttl": record.TTL,
"priority": record.Priority,
}
ids = append(ids, record.RecordId)
urls = append(urls, fmt.Sprintf("%v.%v", record.RR, record.DomainName))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("records", s); err != nil {
return WrapError(err)
}
if err := d.Set("urls", urls); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"github.com/aliyun/alibaba-cloud-sdk-go/services/alidns"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
// https://help.aliyun.com/document_detail/69017.html
func dataSourceAlicloudDnsResolutionLines() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDnsResolutionLinesRead,
Schema: map[string]*schema.Schema{
"line_codes": {
Optional: true,
Type: schema.TypeList,
ForceNew: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"line_display_names": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"line_names": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"domain_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"user_client_ip": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"lang": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// computed values
"lines": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"line_code": {
Type: schema.TypeString,
Computed: true,
},
"line_display_name": {
Type: schema.TypeString,
Computed: true,
},
"line_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudDnsResolutionLinesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := alidns.CreateDescribeSupportLinesRequest()
request.RegionId = client.RegionId
request.Lang = d.Get("lang").(string)
request.UserClientIp = d.Get("user_client_ip").(string)
request.DomainName = d.Get("domain_name").(string)
raw, err := client.WithDnsClient(func(dnsClient *alidns.Client) (interface{}, error) {
return dnsClient.DescribeSupportLines(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_dns_support_lines", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*alidns.DescribeSupportLinesResponse)
allLines := response.RecordLines.RecordLine
var filteredLines []alidns.RecordLine
for _, line := range allLines {
if v, ok := d.GetOk("line_codes"); ok {
lineCodes, _ := v.([]interface{})
if !hasEqualString(lineCodes, line.LineCode) {
continue
}
}
if v, ok := d.GetOk("line_display_names"); ok {
lineDisplayNames, _ := v.([]interface{})
if !hasEqualString(lineDisplayNames, line.LineDisplayName) {
continue
}
}
if v, ok := d.GetOk("line_names"); ok {
lineNames, _ := v.([]interface{})
if !hasEqualString(lineNames, line.LineName) {
continue
}
}
filteredLines = append(filteredLines, line)
}
return resolutionLinesDecriptionAttributes(d, filteredLines, meta)
}
func resolutionLinesDecriptionAttributes(d *schema.ResourceData, Lines []alidns.RecordLine, meta interface{}) error {
var s []map[string]interface{}
var lineCodes []string
var lineDisplayNames []string
for _, line := range Lines {
mapping := map[string]interface{}{
"line_code": line.LineCode,
"line_display_name": line.LineDisplayName,
"line_name": line.LineName,
}
lineCodes = append(lineCodes, line.LineCode)
lineDisplayNames = append(lineDisplayNames, line.LineDisplayName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(lineCodes))
if err := d.Set("lines", s); err != nil {
return WrapError(err)
}
if err := d.Set("line_codes", lineCodes); err != nil {
return WrapError(err)
}
if err := d.Set("line_display_names", lineDisplayNames); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
// to check if a slice has a specific string
func hasEqualString(s []interface{}, a string) bool {
var isEqual bool
for _, code := range s {
fatherCode, _ := code.(string)
if fatherCode == a {
isEqual = true
return isEqual
}
}
return isEqual
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/services/drds"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDRDSInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDRDSInstancesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
Deprecated: "Field 'name_regex' is deprecated and will be removed in a future release. Please use 'description_regex' instead.",
},
"description_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
},
// Computed values
"descriptions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeInt,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"network_type": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
"version": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudDRDSInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := drds.CreateDescribeDrdsInstancesRequest()
request.RegionId = client.RegionId
var dbi []drds.Instance
var regexString *regexp.Regexp
nameRegex, nameRegexGot := d.GetOk("name_regex")
descriptionRegex, descriptionRegexGot := d.GetOk("description_regex")
if nameRegexGot {
if r, err := regexp.Compile(nameRegex.(string)); err == nil {
regexString = r
}
} else if descriptionRegexGot {
if r, err := regexp.Compile(descriptionRegex.(string)); err == nil {
regexString = r
}
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[Trim(vv.(string))] = Trim(vv.(string))
}
}
raw, err := client.WithDrdsClient(func(drdsClient *drds.Client) (interface{}, error) {
return drdsClient.DescribeDrdsInstances(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_drds_instances", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*drds.DescribeDrdsInstancesResponse)
for _, item := range response.Instances.Instance {
if regexString != nil {
if !regexString.MatchString(item.Description) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[item.DrdsInstanceId]; !ok {
continue
}
}
dbi = append(dbi, item)
}
return drdsInstancesDescription(d, dbi)
}
func drdsInstancesDescription(d *schema.ResourceData, dbi []drds.Instance) error {
var ids []string
var descriptions []string
var s []map[string]interface{}
for _, item := range dbi {
mapping := map[string]interface{}{
"id": item.DrdsInstanceId,
"description": item.Description,
"type": item.Type,
"create_time": item.CreateTime,
"status": item.Status,
"network_type": item.NetworkType,
"zone_id": item.ZoneId,
"version": item.Version,
}
ids = append(ids, item.DrdsInstanceId)
descriptions = append(descriptions, item.Description)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("descriptions", descriptions); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudDtsConsumerChannels() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDtsConsumerChannelsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"dts_instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"channels": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"consumer_group_id": {
Type: schema.TypeString,
Computed: true,
},
"consumer_group_name": {
Type: schema.TypeString,
Computed: true,
},
"consumer_group_user_name": {
Type: schema.TypeString,
Computed: true,
},
"consumption_checkpoint": {
Type: schema.TypeString,
Computed: true,
},
"message_delay": {
Type: schema.TypeInt,
Computed: true,
},
"unconsumed_data": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudDtsConsumerChannelsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeConsumerChannel"
request := make(map[string]interface{})
request["DtsInstanceId"] = d.Get("dts_instance_id")
request["RegionId"] = client.RegionId
request["PageSize"] = PageSizeMedium
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_dts_consumer_channels", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.ConsumerChannels", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.ConsumerChannels", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(request["DtsInstanceId"], ":", item["ConsumerGroupId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(request["DtsInstanceId"], ":", object["ConsumerGroupId"]),
"consumer_group_id": fmt.Sprint(object["ConsumerGroupId"]),
"consumer_group_name": object["ConsumerGroupName"],
"consumer_group_user_name": object["ConsumerGroupUserName"],
"consumption_checkpoint": fmt.Sprint(object["ConsumptionCheckpoint"]),
"message_delay": formatInt(object["MessageDelay"]),
"unconsumed_data": formatInt(object["UnconsumedData"]),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("channels", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"encoding/json"
"fmt"
"regexp"
"strings"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDtsSubscriptionJobs() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDtsSubscriptionJobsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Abnormal", "Downgrade", "Locked", "Normal", "NotConfigured", "NotStarted", "PreCheckPass", "PrecheckFailed", "Prechecking", "Retrying", "Starting", "Upgrade"}, false),
},
"tags": tagsSchema(),
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"jobs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"checkpoint": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"db_list": {
Type: schema.TypeString,
Computed: true,
},
"dts_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"dts_job_id": {
Type: schema.TypeString,
Computed: true,
},
"dts_job_name": {
Type: schema.TypeString,
Computed: true,
},
"expire_time": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"source_endpoint_database_name": {
Type: schema.TypeString,
Computed: true,
},
"source_endpoint_engine_name": {
Type: schema.TypeString,
Computed: true,
},
"source_endpoint_ip": {
Type: schema.TypeString,
Computed: true,
},
"source_endpoint_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"source_endpoint_instance_type": {
Type: schema.TypeString,
Computed: true,
},
"source_endpoint_oracle_sid": {
Type: schema.TypeString,
Computed: true,
},
"source_endpoint_owner_id": {
Type: schema.TypeString,
Computed: true,
},
"source_endpoint_port": {
Type: schema.TypeString,
Computed: true,
},
"source_endpoint_region": {
Type: schema.TypeString,
Computed: true,
},
"source_endpoint_role": {
Type: schema.TypeString,
Computed: true,
},
"source_endpoint_user_name": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"subscription_data_type_ddl": {
Type: schema.TypeBool,
Computed: true,
},
"subscription_data_type_dml": {
Type: schema.TypeBool,
Computed: true,
},
"subscription_host": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"private_host": {
Type: schema.TypeString,
Computed: true,
},
"public_host": {
Type: schema.TypeString,
Computed: true,
},
"vpc_host": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"subscription_instance_network_type": {
Type: schema.TypeString,
Computed: true,
},
"subscription_instance_vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"subscription_instance_vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudDtsSubscriptionJobsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDtsJobs"
request := make(map[string]interface{})
request["JobType"] = "SUBSCRIBE"
request["RegionId"] = client.RegionId
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var jobNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
jobNameRegex = r
}
idsMap := make(map[string]string)
names := make([]interface{}, 0)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
tagsMap := make(map[string]interface{})
if v, ok := d.GetOk("tags"); ok && len(v.(map[string]interface{})) > 0 {
tagsMap = v.(map[string]interface{})
}
var response map[string]interface{}
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_dts_subscription_jobs", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.DtsJobList", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.DtsJobList", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if item["Status"] == "Starting" {
item["Status"] = "Normal"
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DtsJobId"])]; !ok {
continue
}
}
if len(tagsMap) > 0 {
if len(item["Tags"].(map[string]interface{})["Tag"].([]interface{})) != len(tagsMap) {
continue
}
match := true
for _, tag := range item["Tags"].([]interface{}) {
if v, ok := tagsMap[tag.(map[string]interface{})["TagKey"].(string)]; !ok || v.(string) != tag.(map[string]interface{})["TagValue"].(string) {
match = false
break
}
}
if !match {
continue
}
}
if jobNameRegex != nil && !jobNameRegex.MatchString(fmt.Sprint(item["DtsJobName"])) {
continue
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"checkpoint": object["Checkpoint"],
"create_time": object["CreateTime"],
"db_list": object["DbObject"],
"dts_instance_id": object["DtsInstanceID"],
"id": fmt.Sprint(object["DtsJobId"]),
"dts_job_id": fmt.Sprint(object["DtsJobId"]),
"dts_job_name": object["DtsJobName"],
"expire_time": object["ExpireTime"],
"payment_type": convertDtsPaymentTypeResponse(object["PayType"]),
"source_endpoint_database_name": object["SourceEndpoint"].(map[string]interface{})["DatabaseName"],
"source_endpoint_engine_name": object["SourceEndpoint"].(map[string]interface{})["EngineName"],
"source_endpoint_ip": object["SourceEndpoint"].(map[string]interface{})["Ip"],
"source_endpoint_instance_id": object["SourceEndpoint"].(map[string]interface{})["InstanceID"],
"source_endpoint_instance_type": object["SourceEndpoint"].(map[string]interface{})["InstanceType"],
"source_endpoint_oracle_sid": object["SourceEndpoint"].(map[string]interface{})["OracleSID"],
"source_endpoint_port": object["SourceEndpoint"].(map[string]interface{})["Port"],
"source_endpoint_region": object["SourceEndpoint"].(map[string]interface{})["Region"],
"source_endpoint_user_name": object["SourceEndpoint"].(map[string]interface{})["UserName"],
"status": object["Status"],
}
var jsonData map[string]interface{}
json.Unmarshal([]byte(object["Reserved"].(string)), &jsonData)
if v, ok := jsonData["netType"].(string); ok {
mapping["subscription_instance_network_type"] = strings.ToLower(v)
}
mapping["subscription_instance_vpc_id"] = jsonData["vpcId"]
mapping["subscription_instance_vswitch_id"] = jsonData["vswitchId"]
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.TagList", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["TagKey"].(string)
value := t.(map[string]interface{})["TagValue"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["DtsJobId"])
dtsService := DtsService{client}
getResp, err := dtsService.DescribeDtsSubscriptionJob(id)
if err != nil {
return WrapError(err)
}
mapping["source_endpoint_owner_id"] = getResp["SourceEndpoint"].(map[string]interface{})["AliyunUid"]
mapping["source_endpoint_role"] = getResp["SourceEndpoint"].(map[string]interface{})["RoleName"]
mapping["subscription_data_type_ddl"] = getResp["SubscriptionDataType"].(map[string]interface{})["Ddl"]
mapping["subscription_data_type_dml"] = getResp["SubscriptionDataType"].(map[string]interface{})["Dml"]
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("jobs", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDtsSynchronizationJobs() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDtsSynchronizationJobsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Downgrade", "Failed", "Finished", "InitializeFailed", "Initializing", "Locked", "Modifying", "NotConfigured", "NotStarted", "PreCheckPass", "PrecheckFailed", "Prechecking", "Retrying", "Suspending", "Synchronizing", "Upgrade"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"jobs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"checkpoint": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"data_initialization": {
Type: schema.TypeBool,
Computed: true,
},
"data_synchronization": {
Type: schema.TypeBool,
Computed: true,
},
"db_list": {
Type: schema.TypeString,
Computed: true,
},
"destination_endpoint_data_base_name": {
Type: schema.TypeString,
Computed: true,
},
"destination_endpoint_engine_name": {
Type: schema.TypeString,
Computed: true,
},
"destination_endpoint_ip": {
Type: schema.TypeString,
Computed: true,
},
"destination_endpoint_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"destination_endpoint_instance_type": {
Type: schema.TypeString,
Computed: true,
},
"destination_endpoint_oracle_sid": {
Type: schema.TypeString,
Computed: true,
},
"destination_endpoint_port": {
Type: schema.TypeString,
Computed: true,
},
"destination_endpoint_region": {
Type: schema.TypeString,
Computed: true,
},
"destination_endpoint_user_name": {
Type: schema.TypeString,
Computed: true,
},
"dts_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"dts_job_id": {
Type: schema.TypeString,
Computed: true,
},
"dts_job_name": {
Type: schema.TypeString,
Computed: true,
},
"expire_time": {
Type: schema.TypeString,
Computed: true,
},
"source_endpoint_database_name": {
Type: schema.TypeString,
Computed: true,
},
"source_endpoint_engine_name": {
Type: schema.TypeString,
Computed: true,
},
"source_endpoint_ip": {
Type: schema.TypeString,
Computed: true,
},
"source_endpoint_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"source_endpoint_instance_type": {
Type: schema.TypeString,
Computed: true,
},
"source_endpoint_oracle_sid": {
Type: schema.TypeString,
Computed: true,
},
"source_endpoint_owner_id": {
Type: schema.TypeString,
Computed: true,
},
"source_endpoint_port": {
Type: schema.TypeString,
Computed: true,
},
"source_endpoint_region": {
Type: schema.TypeString,
Computed: true,
},
"source_endpoint_role": {
Type: schema.TypeString,
Computed: true,
},
"source_endpoint_user_name": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"structure_initialization": {
Type: schema.TypeBool,
Computed: true,
},
"synchronization_direction": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudDtsSynchronizationJobsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDtsJobs"
request := make(map[string]interface{})
request["JobType"] = "SYNC"
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var jobNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
jobNameRegex = r
}
status, statusOk := d.GetOk("status")
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_dts_synchronization_jobs", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.DtsJobList", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.DtsJobList", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
// see comment on function DescribeDtsSynchronizationJob
if item["Status"] == "synchronizing" || item["Status"] == "Initializing" {
item["Status"] = "Synchronizing"
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DtsJobId"])]; !ok {
continue
}
}
if jobNameRegex != nil && !jobNameRegex.MatchString(fmt.Sprint(item["DtsJobName"])) {
continue
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
migrationModeObj := object["MigrationMode"].(map[string]interface{})
destinationEndpointObj := object["DestinationEndpoint"].(map[string]interface{})
sourceEndpointObj := object["SourceEndpoint"].(map[string]interface{})
mapping := map[string]interface{}{
"checkpoint": object["Checkpoint"],
"create_time": object["CreateTime"],
"data_initialization": migrationModeObj["DataInitialization"],
"data_synchronization": migrationModeObj["DataSynchronization"],
"structure_initialization": migrationModeObj["StructureInitialization"],
"db_list": object["DbObject"],
"destination_endpoint_data_base_name": destinationEndpointObj["DatabaseName"],
"destination_endpoint_engine_name": destinationEndpointObj["EngineName"],
"destination_endpoint_ip": destinationEndpointObj["Ip"],
"destination_endpoint_instance_id": destinationEndpointObj["InstanceID"],
"destination_endpoint_instance_type": destinationEndpointObj["InstanceType"],
"destination_endpoint_oracle_sid": destinationEndpointObj["OracleSID"],
"destination_endpoint_port": destinationEndpointObj["Port"],
"destination_endpoint_region": destinationEndpointObj["Region"],
"destination_endpoint_user_name": destinationEndpointObj["UserName"],
"dts_instance_id": object["DtsInstanceID"],
"id": fmt.Sprint(object["DtsJobId"]),
"dts_job_id": fmt.Sprint(object["DtsJobId"]),
"dts_job_name": object["DtsJobName"],
"expire_time": object["ExpireTime"],
"source_endpoint_database_name": object["ReverseJob"].(map[string]interface{})["SourceEndpoint"].(map[string]interface{})["DatabaseName"],
"source_endpoint_engine_name": sourceEndpointObj["EngineName"],
"source_endpoint_ip": sourceEndpointObj["Ip"],
"source_endpoint_instance_id": sourceEndpointObj["InstanceID"],
"source_endpoint_instance_type": sourceEndpointObj["InstanceType"],
"source_endpoint_oracle_sid": sourceEndpointObj["OracleSID"],
"source_endpoint_port": sourceEndpointObj["Port"],
"source_endpoint_region": sourceEndpointObj["Region"],
"source_endpoint_user_name": sourceEndpointObj["UserName"],
"status": object["Status"],
"synchronization_direction": object["DtsJobDirection"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["DtsJobId"])
dtsService := DtsService{client}
getResp, err := dtsService.DescribeDtsSynchronizationJob(id)
if err != nil {
return WrapError(err)
}
mapping["source_endpoint_owner_id"] = getResp["SourceEndpoint"].(map[string]interface{})["AliyunUid"]
mapping["source_endpoint_role"] = getResp["SourceEndpoint"].(map[string]interface{})["RoleName"]
if err != nil {
return WrapError(err)
}
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("jobs", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEaisInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEaisInstancesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"instance_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"eais.ei-a6.4xlarge", "eais.ei-a6.2xlarge", "eais.ei-a6.xlarge", "eais.ei-a6.large", "eais.ei-a6.medium"}, false),
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Attaching", "Available", "Detaching", "InUse", "Starting", "Unavailable"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"client_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"client_instance_name": {
Type: schema.TypeString,
Computed: true,
},
"client_instance_type": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_name": {
Type: schema.TypeString,
Computed: true,
},
"instance_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEaisInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeEais"
request := make(map[string]interface{})
if v, ok := d.GetOk("instance_type"); ok {
request["InstanceType"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var instanceNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
instanceNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewEaisClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-24"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_eais_instances", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Instances.Instance", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Instances.Instance", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if instanceNameRegex != nil && !instanceNameRegex.MatchString(fmt.Sprint(item["InstanceName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ElasticAcceleratedInstanceId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"client_instance_id": object["ClientInstanceId"],
"client_instance_name": object["ClientInstanceName"],
"client_instance_type": object["ClientInstanceType"],
"id": fmt.Sprint(object["ElasticAcceleratedInstanceId"]),
"instance_id": fmt.Sprint(object["ElasticAcceleratedInstanceId"]),
"instance_name": object["InstanceName"],
"instance_type": object["InstanceType"],
"status": object["Status"],
"zone_id": object["ZoneId"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["InstanceName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEcdBundles() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEcdBundlesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"bundle_id": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"bundle_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"SYSTEM", "CUSTOM"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"bundles": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"bundle_id": {
Type: schema.TypeString,
Computed: true,
},
"bundle_name": {
Type: schema.TypeString,
Computed: true,
},
"bundle_type": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"desktop_type": {
Type: schema.TypeString,
Computed: true,
},
"desktop_type_attribute": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cpu_count": {
Type: schema.TypeInt,
Computed: true,
},
"gpu_count": {
Type: schema.TypeString,
Computed: true,
},
"gpu_spec": {
Type: schema.TypeString,
Computed: true,
},
"memory_size": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"disks": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"disk_size": {
Type: schema.TypeString,
Computed: true,
},
"disk_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"image_id": {
Type: schema.TypeString,
Computed: true,
},
"os_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEcdBundlesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeBundles"
request := make(map[string]interface{})
if v, ok := d.GetOk("bundle_id"); ok {
request["BundleId"] = v
}
if v, ok := d.GetOk("bundle_type"); ok {
request["BundleType"] = v
}
request["RegionId"] = client.RegionId
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var bundleNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
bundleNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ecd_bundles", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Bundles", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Bundles", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if bundleNameRegex != nil && !bundleNameRegex.MatchString(fmt.Sprint(item["BundleName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["BundleId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["BundleId"]),
"bundle_id": fmt.Sprint(object["BundleId"]),
"bundle_name": object["BundleName"],
"bundle_type": object["BundleType"],
"description": object["Description"],
"desktop_type": object["DesktopType"],
"image_id": object["ImageId"],
"os_type": object["OsType"],
}
disks := make([]map[string]interface{}, 0)
if disksList, ok := object["Disks"].([]interface{}); ok {
for _, v := range disksList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"disk_size": m1["DiskSize"],
"disk_type": m1["DiskType"],
}
disks = append(disks, temp1)
}
}
}
mapping["disks"] = disks
desktopTypeAttributeSli := make([]map[string]interface{}, 0)
if len(object["DesktopTypeAttribute"].(map[string]interface{})) > 0 {
desktopTypeAttribute := object["DesktopTypeAttribute"]
desktopTypeAttributeMap := make(map[string]interface{})
desktopTypeAttributeMap["cpu_count"] = desktopTypeAttribute.(map[string]interface{})["CpuCount"]
desktopTypeAttributeMap["gpu_count"] = desktopTypeAttribute.(map[string]interface{})["GpuCount"]
desktopTypeAttributeMap["gpu_spec"] = desktopTypeAttribute.(map[string]interface{})["GpuSpec"]
desktopTypeAttributeMap["memory_size"] = desktopTypeAttribute.(map[string]interface{})["MemorySize"]
desktopTypeAttributeSli = append(desktopTypeAttributeSli, desktopTypeAttributeMap)
}
mapping["desktop_type_attribute"] = desktopTypeAttributeSli
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["BundleName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("bundles", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEcdCommands() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEcdCommandsRead,
Schema: map[string]*schema.Schema{
"command_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"RunBatScript", "RunPowerShellScript"}, false),
},
"content_encoding": {
Type: schema.TypeString,
Optional: true,
Default: "PlainText",
ValidateFunc: validation.StringInSlice([]string{"Base64", "PlainText"}, false),
},
"desktop_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Pending", "Failed", "PartialFailed", "Running", "Stopped", "Stopping", "Finished", "Success"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"commands": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"command_content": {
Type: schema.TypeString,
Computed: true,
},
"command_type": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"invoke_desktops": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"desktop_id": {
Type: schema.TypeString,
Computed: true,
},
"dropped": {
Type: schema.TypeInt,
Computed: true,
},
"error_code": {
Type: schema.TypeString,
Computed: true,
},
"error_info": {
Type: schema.TypeString,
Computed: true,
},
"exit_code": {
Type: schema.TypeString,
Computed: true,
},
"finish_time": {
Type: schema.TypeString,
Computed: true,
},
"invocation_status": {
Type: schema.TypeString,
Computed: true,
},
"output": {
Type: schema.TypeString,
Computed: true,
},
"repeats": {
Type: schema.TypeInt,
Computed: true,
},
"start_time": {
Type: schema.TypeString,
Computed: true,
},
"stop_time": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"invoke_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEcdCommandsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeInvocations"
request := make(map[string]interface{})
if v, ok := d.GetOk("command_type"); ok {
request["CommandType"] = v
}
if v, ok := d.GetOk("content_encoding"); ok {
request["ContentEncoding"] = v
}
if v, ok := d.GetOk("desktop_id"); ok {
request["DesktopId"] = v
}
request["IncludeOutput"] = "true"
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("status"); ok {
request["InvokeStatus"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ecd_commands", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Invocations", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Invocations", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["InvokeId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"command_content": object["CommandContent"],
"command_type": object["CommandType"],
"create_time": object["CreationTime"],
"id": fmt.Sprint(object["InvokeId"]),
"invoke_id": fmt.Sprint(object["InvokeId"]),
"status": object["InvocationStatus"],
}
invokeDesktops := make([]map[string]interface{}, 0)
if invokeDesktopsList, ok := object["InvokeDesktops"].([]interface{}); ok {
for _, v := range invokeDesktopsList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"desktop_id": m1["DesktopId"],
"dropped": formatInt(m1["Dropped"]),
"error_code": m1["ErrorCode"],
"error_info": m1["ErrorInfo"],
"exit_code": m1["ExitCode"],
"finish_time": m1["FinishTime"],
"invocation_status": m1["InvocationStatus"],
"output": m1["Output"],
"repeats": formatInt(m1["Repeats"]),
"start_time": m1["StartTime"],
"stop_time": m1["StopTime"],
}
invokeDesktops = append(invokeDesktops, temp1)
}
}
}
mapping["invoke_desktops"] = invokeDesktops
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("commands", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEcdDesktops() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEcdDesktopsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"desktop_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"office_site_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"policy_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"end_user_ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Deleted", "Expired", "Pending", "Running", "Starting", "Stopped", "Stopping"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"desktops": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cpu": {
Type: schema.TypeInt,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"desktop_id": {
Type: schema.TypeString,
Computed: true,
},
"desktop_name": {
Type: schema.TypeString,
Computed: true,
},
"desktop_type": {
Type: schema.TypeString,
Computed: true,
},
"directory_id": {
Type: schema.TypeString,
Computed: true,
},
"end_user_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"expired_time": {
Type: schema.TypeString,
Computed: true,
},
"image_id": {
Type: schema.TypeString,
Computed: true,
},
"memory": {
Type: schema.TypeString,
Computed: true,
},
"network_interface_id": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"policy_group_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"system_disk_size": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEcdDesktopsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDesktops"
request := make(map[string]interface{})
if v, ok := d.GetOk("desktop_name"); ok {
request["DesktopName"] = v
}
if v, ok := d.GetOk("office_site_id"); ok {
request["OfficeSiteId"] = v
}
if v, ok := d.GetOk("policy_group_id"); ok {
request["PolicyGroupId"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("status"); ok {
request["DesktopStatus"] = v
}
if m, ok := d.GetOk("end_user_ids"); ok {
for k, v := range m.([]interface{}) {
request[fmt.Sprintf("EndUserId.%d", k+1)] = v.(string)
}
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var desktopNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
desktopNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ecd_desktops", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Desktops", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Desktops", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if desktopNameRegex != nil && !desktopNameRegex.MatchString(fmt.Sprint(item["DesktopName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DesktopId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"cpu": formatInt(object["Cpu"]),
"create_time": object["CreationTime"],
"id": fmt.Sprint(object["DesktopId"]),
"desktop_id": fmt.Sprint(object["DesktopId"]),
"desktop_name": object["DesktopName"],
"desktop_type": object["DesktopType"],
"directory_id": object["DirectoryId"],
"expired_time": object["ExpiredTime"],
"end_user_ids": object["EndUserIds"],
"image_id": object["ImageId"],
"memory": fmt.Sprint(object["Memory"]),
"network_interface_id": object["NetworkInterfaceId"],
"payment_type": convertEcdDesktopPaymentTypeResponse(object["ChargeType"]),
"policy_group_id": object["PolicyGroupId"],
"status": object["DesktopStatus"],
"system_disk_size": formatInt(object["SystemDiskSize"]),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["DesktopName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("desktops", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEcdImages() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEcdImagesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"image_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"CUSTOM", "SYSTEM"}, false),
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "CreateFailed", "Creating"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"images": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"data_disk_size": {
Type: schema.TypeInt,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"gpu_category": {
Type: schema.TypeBool,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"image_id": {
Type: schema.TypeString,
Computed: true,
},
"image_name": {
Type: schema.TypeString,
Computed: true,
},
"image_type": {
Type: schema.TypeString,
Computed: true,
},
"os_type": {
Type: schema.TypeString,
Computed: true,
},
"progress": {
Type: schema.TypeString,
Computed: true,
},
"size": {
Type: schema.TypeInt,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEcdImagesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeImages"
request := make(map[string]interface{})
if v, ok := d.GetOk("image_type"); ok {
request["ImageType"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("status"); ok {
request["ImageStatus"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var imageNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
imageNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ecd_images", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Images", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Images", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if imageNameRegex != nil && !imageNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ImageId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": object["CreationTime"],
"data_disk_size": formatInt(object["DataDiskSize"]),
"description": object["Description"],
"gpu_category": object["GpuCategory"],
"id": fmt.Sprint(object["ImageId"]),
"image_id": fmt.Sprint(object["ImageId"]),
"image_name": object["Name"],
"image_type": object["ImageType"],
"os_type": object["OsType"],
"progress": object["Progress"],
"size": formatInt(object["Size"]),
"status": object["Status"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("images", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEcdNasFileSystems() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEcdNasFileSystemsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"office_site_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Deleted", "Deleting", "Invalid", "Pending", "Running", "Stopped"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"systems": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"capacity": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"file_system_id": {
Type: schema.TypeString,
Computed: true,
},
"file_system_type": {
Type: schema.TypeString,
Computed: true,
},
"metered_size": {
Type: schema.TypeString,
Computed: true,
},
"mount_target_domain": {
Type: schema.TypeString,
Computed: true,
},
"mount_target_status": {
Type: schema.TypeString,
Computed: true,
},
"nas_file_system_name": {
Type: schema.TypeString,
Computed: true,
},
"office_site_id": {
Type: schema.TypeString,
Computed: true,
},
"office_site_name": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"storage_type": {
Type: schema.TypeString,
Computed: true,
},
"support_acl": {
Type: schema.TypeBool,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEcdNasFileSystemsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeNASFileSystems"
request := make(map[string]interface{})
if v, ok := d.GetOk("office_site_id"); ok {
request["OfficeSiteId"] = v
}
request["RegionId"] = client.RegionId
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var nasFileSystemNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
nasFileSystemNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ecd_nas_file_systems", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.FileSystems", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.FileSystems", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if nasFileSystemNameRegex != nil && !nasFileSystemNameRegex.MatchString(fmt.Sprint(item["FileSystemName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["FileSystemId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["FileSystemStatus"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"capacity": fmt.Sprint(object["Capacity"]),
"create_time": object["CreateTime"],
"description": object["Description"],
"id": fmt.Sprint(object["FileSystemId"]),
"file_system_id": fmt.Sprint(object["FileSystemId"]),
"file_system_type": object["FileSystemType"],
"metered_size": fmt.Sprint(object["MeteredSize"]),
"mount_target_domain": object["MountTargetDomain"],
"mount_target_status": object["MountTargetStatus"],
"nas_file_system_name": object["FileSystemName"],
"office_site_id": object["OfficeSiteId"],
"office_site_name": object["OfficeSiteName"],
"status": object["FileSystemStatus"],
"storage_type": object["StorageType"],
"support_acl": object["SupportAcl"],
"zone_id": object["ZoneId"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["FileSystemName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("systems", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEcdNetworkPackages() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEcdNetworkPackagesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Creating", "InUse", "Released", "Releasing"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"packages": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"bandwidth": {
Type: schema.TypeInt,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"expired_time": {
Type: schema.TypeString,
Computed: true,
},
"internet_charge_type": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"network_package_id": {
Type: schema.TypeString,
Computed: true,
},
"office_site_id": {
Type: schema.TypeString,
Computed: true,
},
"office_site_name": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEcdNetworkPackagesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeNetworkPackages"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ecd_network_packages", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.NetworkPackages", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.NetworkPackages", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["NetworkPackageId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["NetworkPackageStatus"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"bandwidth": formatInt(object["Bandwidth"]),
"create_time": object["CreateTime"],
"expired_time": object["ExpiredTime"],
"internet_charge_type": object["InternetChargeType"],
"id": fmt.Sprint(object["NetworkPackageId"]),
"network_package_id": fmt.Sprint(object["NetworkPackageId"]),
"office_site_id": object["OfficeSiteId"],
"office_site_name": object["OfficeSiteName"],
"status": object["NetworkPackageStatus"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("packages", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEcdPolicyGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEcdPolicyGroupsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"AVAILABLE", "CREATING"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"authorize_access_policy_rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cidr_ip": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"authorize_security_policy_rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cidr_ip": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"ip_protocol": {
Type: schema.TypeString,
Computed: true,
},
"policy": {
Type: schema.TypeString,
Computed: true,
},
"port_range": {
Type: schema.TypeString,
Computed: true,
},
"priority": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"clipboard": {
Type: schema.TypeString,
Computed: true,
},
"domain_list": {
Type: schema.TypeString,
Computed: true,
},
"eds_count": {
Type: schema.TypeInt,
Computed: true,
},
"html_access": {
Type: schema.TypeString,
Computed: true,
},
"html_file_transfer": {
Type: schema.TypeString,
Computed: true,
},
"local_drive": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"policy_group_id": {
Type: schema.TypeString,
Computed: true,
},
"policy_group_name": {
Type: schema.TypeString,
Computed: true,
},
"policy_group_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"usb_redirect": {
Type: schema.TypeString,
Computed: true,
},
"visual_quality": {
Type: schema.TypeString,
Computed: true,
},
"watermark": {
Type: schema.TypeString,
Computed: true,
},
"watermark_transparency": {
Type: schema.TypeString,
Computed: true,
},
"watermark_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEcdPolicyGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribePolicyGroups"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var policyGroupNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
policyGroupNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ecd_policy_groups", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.DescribePolicyGroups", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.DescribePolicyGroups", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if policyGroupNameRegex != nil && !policyGroupNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["PolicyGroupId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["PolicyStatus"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"clipboard": object["Clipboard"],
"domain_list": object["DomainList"],
"eds_count": formatInt(object["EdsCount"]),
"html_access": object["Html5Access"],
"html_file_transfer": object["Html5FileTransfer"],
"local_drive": object["LocalDrive"],
"id": fmt.Sprint(object["PolicyGroupId"]),
"policy_group_id": fmt.Sprint(object["PolicyGroupId"]),
"policy_group_name": object["Name"],
"policy_group_type": object["PolicyGroupType"],
"status": object["PolicyStatus"],
"usb_redirect": object["UsbRedirect"],
"visual_quality": object["VisualQuality"],
"watermark": object["Watermark"],
"watermark_transparency": object["WatermarkTransparency"],
"watermark_type": object["WatermarkType"],
}
authorizeAccessPolicyRules := make([]map[string]interface{}, 0)
if authorizeAccessPolicyRulesList, ok := object["AuthorizeAccessPolicyRules"].([]interface{}); ok {
for _, v := range authorizeAccessPolicyRulesList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"cidr_ip": m1["CidrIp"],
"description": m1["Description"],
}
authorizeAccessPolicyRules = append(authorizeAccessPolicyRules, temp1)
}
}
}
mapping["authorize_access_policy_rules"] = authorizeAccessPolicyRules
if v, ok := object["AuthorizeSecurityPolicyRules"].([]interface{}); ok {
authorizeSecurityPolicyRules := make([]map[string]interface{}, 0)
for _, val := range v {
item := val.(map[string]interface{})
temp := map[string]interface{}{
"cidr_ip": item["CidrIp"],
"description": item["Description"],
"ip_protocol": item["IpProtocol"],
"policy": item["Policy"],
"port_range": item["PortRange"],
"priority": item["Priority"],
"type": item["Type"],
}
authorizeSecurityPolicyRules = append(authorizeSecurityPolicyRules, temp)
}
mapping["authorize_security_policy_rules"] = authorizeSecurityPolicyRules
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEcdSimpleOfficeSites() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEcdSimpleOfficeSitesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"REGISTERED", "REGISTERING"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"sites": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"bandwidth": {
Type: schema.TypeInt,
Computed: true,
Deprecated: "Field 'bandwidth' has been deprecated from provider version 1.142.0.",
},
"cen_id": {
Type: schema.TypeString,
Computed: true,
},
"cidr_block": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"custom_security_group_id": {
Type: schema.TypeString,
Computed: true,
},
"desktop_access_type": {
Type: schema.TypeString,
Computed: true,
},
"desktop_vpc_endpoint": {
Type: schema.TypeString,
Computed: true,
},
"dns_address": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"dns_user_name": {
Type: schema.TypeString,
Computed: true,
},
"domain_name": {
Type: schema.TypeString,
Computed: true,
},
"domain_password": {
Type: schema.TypeString,
Computed: true,
},
"domain_user_name": {
Type: schema.TypeString,
Computed: true,
},
"enable_admin_access": {
Type: schema.TypeBool,
Computed: true,
},
"enable_cross_desktop_access": {
Type: schema.TypeBool,
Computed: true,
},
"enable_internet_access": {
Type: schema.TypeBool,
Computed: true,
Deprecated: "Field 'enable_internet_access' has been deprecated from provider version 1.142.0.",
},
"file_system_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"mfa_enabled": {
Type: schema.TypeBool,
Computed: true,
},
"network_package_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"office_site_id": {
Type: schema.TypeString,
Computed: true,
},
"office_site_type": {
Type: schema.TypeString,
Computed: true,
},
"simple_office_site_name": {
Type: schema.TypeString,
Computed: true,
},
"sso_enabled": {
Type: schema.TypeBool,
Computed: true,
},
"sso_status": {
Type: schema.TypeBool,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"sub_dns_address": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"sub_domain_name": {
Type: schema.TypeString,
Computed: true,
},
"trust_password": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEcdSimpleOfficeSitesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeOfficeSites"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var simpleOfficeSiteNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
simpleOfficeSiteNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ecd_simple_office_sites", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.OfficeSites", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.OfficeSites", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if simpleOfficeSiteNameRegex != nil && !simpleOfficeSiteNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["OfficeSiteId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
// todo: bandwidth depends on network_package resource, you can find it in alicloud_ecd_network_packages
//"bandwidth": formatInt(object["Bandwidth"]),
//"enable_internet_access": object["EnableInternetAccess"],
"cen_id": object["CenId"],
"cidr_block": object["CidrBlock"],
"create_time": object["CreationTime"],
"custom_security_group_id": object["CustomSecurityGroupId"],
"desktop_access_type": convertDesktopAccessType(object["DesktopAccessType"].(string)),
"desktop_vpc_endpoint": object["DesktopVpcEndpoint"],
"dns_address": object["DnsAddress"],
"dns_user_name": object["DnsUserName"],
"domain_name": object["DomainName"],
"domain_password": object["DomainPassword"],
"domain_user_name": object["DomainUserName"],
"enable_admin_access": object["EnableAdminAccess"],
"enable_cross_desktop_access": object["EnableCrossDesktopAccess"],
"enable_internet_access": object["EnableInternetAccess"],
"file_system_ids": object["FileSystemIds"],
"mfa_enabled": object["MfaEnabled"],
"network_package_id": object["NetworkPackageId"],
"id": object["OfficeSiteId"],
"office_site_id": object["OfficeSiteId"],
"office_site_type": object["OfficeSiteType"],
"simple_office_site_name": object["Name"],
"sso_enabled": object["SsoEnabled"],
"sso_status": response["SsoStatus"],
"status": object["Status"],
"sub_dns_address": object["SubDnsAddress"],
"sub_domain_name": object["SubDomainName"],
"trust_password": object["TrustPassword"],
"vswitch_ids": object["VSwitchIds"],
"vpc_id": object["VpcId"],
}
ids = append(ids, fmt.Sprint(object["OfficeSiteId"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("sites", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"strconv"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEcdUsers() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEcdUsersRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Unlocked", "Locked"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"users": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"email": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"end_user_id": {
Type: schema.TypeString,
Computed: true,
},
"phone": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEcdUsersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeUsers"
request := make(map[string]interface{})
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
if statusOk {
status = convertEcdUserStatusRequest(status.(string))
}
var response map[string]interface{}
conn, err := client.NewEdsuserClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-03-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"Forbidden"}) {
conn.Endpoint = String(connectivity.EcdOpenAPIEndpointUser)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ecd_users", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Users", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Users", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["EndUserId"])]; !ok {
continue
}
}
if statusOk && status != "" && status != strconv.Itoa(formatInt(item["Status"])) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"email": object["Email"],
"id": fmt.Sprint(object["Id"]),
"end_user_id": fmt.Sprint(object["EndUserId"]),
"phone": object["Phone"],
"status": convertEcdUserStatusResponse(strconv.Itoa(formatInt(object["Status"]))),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("users", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEciContainerGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEciContainerGroupsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"container_group_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"limit": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Pending", "Running", "ScheduleFailed", "Scheduling", "Succeeded"}, false),
},
"tags": tagsSchema(),
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"with_event": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"container_group_id": {
Type: schema.TypeString,
Computed: true,
},
"container_group_name": {
Type: schema.TypeString,
Computed: true,
},
"containers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"args": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"commands": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"cpu": {
Type: schema.TypeFloat,
Computed: true,
},
"environment_vars": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Computed: true,
},
"value": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"gpu": {
Type: schema.TypeInt,
Computed: true,
},
"image": {
Type: schema.TypeString,
Computed: true,
},
"image_pull_policy": {
Type: schema.TypeString,
Computed: true,
},
"memory": {
Type: schema.TypeFloat,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"ports": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"port": {
Type: schema.TypeInt,
Computed: true,
},
"protocol": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"ready": {
Type: schema.TypeBool,
Computed: true,
},
"restart_count": {
Type: schema.TypeInt,
Computed: true,
},
"volume_mounts": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"mount_path": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"read_only": {
Type: schema.TypeBool,
Computed: true,
},
},
},
},
"working_dir": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"cpu": {
Type: schema.TypeFloat,
Computed: true,
},
"discount": {
Type: schema.TypeInt,
Computed: true,
},
"dns_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name_servers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"options": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Computed: true,
},
"value": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"searches": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"eci_security_context": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"sysctls": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Computed: true,
},
"value": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
"eni_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"events": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"count": {
Type: schema.TypeInt,
Computed: true,
},
"first_timestamp": {
Type: schema.TypeString,
Computed: true,
},
"last_timestamp": {
Type: schema.TypeString,
Computed: true,
},
"message": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"reason": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"expired_time": {
Type: schema.TypeString,
Computed: true,
},
"failed_time": {
Type: schema.TypeString,
Computed: true,
},
"host_aliases": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"hostnames": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"ip": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"init_containers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"args": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"commands": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"cpu": {
Type: schema.TypeFloat,
Computed: true,
},
"environment_vars": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Computed: true,
},
"value": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"gpu": {
Type: schema.TypeInt,
Computed: true,
},
"image": {
Type: schema.TypeString,
Computed: true,
},
"image_pull_policy": {
Type: schema.TypeString,
Computed: true,
},
"memory": {
Type: schema.TypeFloat,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"ports": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"port": {
Type: schema.TypeInt,
Computed: true,
},
"protocol": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"ready": {
Type: schema.TypeBool,
Computed: true,
},
"restart_count": {
Type: schema.TypeInt,
Computed: true,
},
"volume_mounts": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"mount_path": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"read_only": {
Type: schema.TypeBool,
Computed: true,
},
},
},
},
"working_dir": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"instance_type": {
Type: schema.TypeString,
Computed: true,
},
"internet_ip": {
Type: schema.TypeString,
Computed: true,
},
"intranet_ip": {
Type: schema.TypeString,
Computed: true,
},
"ipv6_address": {
Type: schema.TypeString,
Computed: true,
},
"memory": {
Type: schema.TypeFloat,
Computed: true,
},
"ram_role_name": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"restart_policy": {
Type: schema.TypeString,
Computed: true,
},
"security_group_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"succeeded_time": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"volumes": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"config_file_volume_config_file_to_paths": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"content": {
Type: schema.TypeString,
Computed: true,
},
"path": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"disk_volume_disk_id": {
Type: schema.TypeString,
Computed: true,
},
"disk_volume_fs_type": {
Type: schema.TypeString,
Computed: true,
},
"flex_volume_driver": {
Type: schema.TypeString,
Computed: true,
},
"flex_volume_fs_type": {
Type: schema.TypeString,
Computed: true,
},
"flex_volume_options": {
Type: schema.TypeString,
Computed: true,
},
"nfs_volume_path": {
Type: schema.TypeString,
Computed: true,
},
"nfs_volume_read_only": {
Type: schema.TypeBool,
Computed: true,
},
"nfs_volume_server": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudEciContainerGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeContainerGroups"
request := make(map[string]interface{})
if v, ok := d.GetOk("container_group_name"); ok {
request["ContainerGroupName"] = v
}
if v, ok := d.GetOk("limit"); ok {
request["Limit"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
if v, ok := d.GetOk("tags"); ok {
tags := make([]map[string]interface{}, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, map[string]interface{}{
"Key": key,
"Value": value.(string),
})
}
request["Tag"] = tags
}
if v, ok := d.GetOk("vswitch_id"); ok {
request["VSwitchId"] = v
}
if v, ok := d.GetOkExists("with_event"); ok {
request["WithEvent"] = v
}
if v, ok := d.GetOk("zone_id"); ok {
request["ZoneId"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var containerGroupNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
containerGroupNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewEciClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-08-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_eci_container_groups", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.ContainerGroups", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.ContainerGroups", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if containerGroupNameRegex != nil {
if !containerGroupNameRegex.MatchString(fmt.Sprint(item["ContainerGroupName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ContainerGroupId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["ContainerGroupId"]),
"container_group_id": fmt.Sprint(object["ContainerGroupId"]),
"container_group_name": object["ContainerGroupName"],
"cpu": object["Cpu"],
"discount": formatInt(object["Discount"]),
"eni_instance_id": object["EniInstanceId"],
"expired_time": object["ExpiredTime"],
"failed_time": object["FailedTime"],
"instance_type": object["InstanceType"],
"internet_ip": object["InternetIp"],
"intranet_ip": object["IntranetIp"],
"ipv6_address": object["Ipv6Address"],
"memory": object["Memory"],
"ram_role_name": object["RamRoleName"],
"resource_group_id": object["ResourceGroupId"],
"security_group_id": object["SecurityGroupId"],
"status": object["Status"],
"succeeded_time": object["SucceededTime"],
"vswitch_id": object["VSwitchId"],
"vpc_id": object["VpcId"],
"zone_id": object["ZoneId"],
}
containers := make([]map[string]interface{}, 0)
if containersList, ok := object["Containers"].([]interface{}); ok {
for _, v := range containersList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"args": m1["Args"],
"commands": m1["Commands"],
"cpu": m1["Cpu"],
"gpu": m1["Gpu"],
"image": m1["Image"],
"image_pull_policy": m1["ImagePullPolicy"],
"memory": m1["Memory"],
"name": m1["Name"],
"ready": m1["Ready"],
"restart_count": m1["RestartCount"],
"working_dir": m1["WorkingDir"],
}
if m1["EnvironmentVars"] != nil {
environmentVarsMaps := make([]map[string]interface{}, 0)
for _, environmentVarsValue := range m1["EnvironmentVars"].([]interface{}) {
environmentVars := environmentVarsValue.(map[string]interface{})
environmentVarsMap := map[string]interface{}{
"key": environmentVars["Key"],
"value": environmentVars["Value"],
}
environmentVarsMaps = append(environmentVarsMaps, environmentVarsMap)
}
temp1["environment_vars"] = environmentVarsMaps
}
if m1["Ports"] != nil {
portsMaps := make([]map[string]interface{}, 0)
for _, portsValue := range m1["Ports"].([]interface{}) {
ports := portsValue.(map[string]interface{})
portsMap := map[string]interface{}{
"port": ports["Port"],
"protocol": ports["Protocol"],
}
portsMaps = append(portsMaps, portsMap)
}
temp1["ports"] = portsMaps
}
if m1["VolumeMounts"] != nil {
volumeMountsMaps := make([]map[string]interface{}, 0)
for _, volumeMountsValue := range m1["VolumeMounts"].([]interface{}) {
volumeMounts := volumeMountsValue.(map[string]interface{})
volumeMountsMap := map[string]interface{}{
"mount_path": volumeMounts["MountPath"],
"name": volumeMounts["Name"],
"read_only": volumeMounts["ReadOnly"],
}
volumeMountsMaps = append(volumeMountsMaps, volumeMountsMap)
}
temp1["volume_mounts"] = volumeMountsMaps
}
containers = append(containers, temp1)
}
}
}
mapping["containers"] = containers
events := make([]map[string]interface{}, 0)
if eventsList, ok := object["Events"].([]interface{}); ok {
for _, v := range eventsList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"count": m1["Count"],
"first_timestamp": m1["FirstTimestamp"],
"last_timestamp": m1["LastTimestamp"],
"message": m1["Message"],
"name": m1["Name"],
"reason": m1["Reason"],
"type": m1["Type"],
}
events = append(events, temp1)
}
}
}
mapping["events"] = events
hostAliases := make([]map[string]interface{}, 0)
if hostAliasesList, ok := object["HostAliases"].([]interface{}); ok {
for _, v := range hostAliasesList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"hostnames": m1["Hostnames"],
"ip": m1["Ip"],
}
hostAliases = append(hostAliases, temp1)
}
}
}
mapping["host_aliases"] = hostAliases
initContainers := make([]map[string]interface{}, 0)
if initContainersList, ok := object["InitContainers"].([]interface{}); ok {
for _, v := range initContainersList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"args": m1["Args"],
"commands": m1["Command"],
"cpu": m1["Cpu"],
"gpu": m1["Gpu"],
"image": m1["Image"],
"image_pull_policy": m1["ImagePullPolicy"],
"memory": m1["Memory"],
"name": m1["Name"],
"ready": m1["Ready"],
"restart_count": m1["RestartCount"],
"working_dir": m1["WorkingDir"],
}
if m1["EnvironmentVars"] != nil {
environmentVarsMaps := make([]map[string]interface{}, 0)
for _, environmentVarsValue := range m1["EnvironmentVars"].([]interface{}) {
environmentVars := environmentVarsValue.(map[string]interface{})
environmentVarsMap := map[string]interface{}{
"key": environmentVars["Key"],
"value": environmentVars["Value"],
}
environmentVarsMaps = append(environmentVarsMaps, environmentVarsMap)
}
temp1["environment_vars"] = environmentVarsMaps
}
if m1["Ports"] != nil {
portsMaps := make([]map[string]interface{}, 0)
for _, portsValue := range m1["Ports"].([]interface{}) {
ports := portsValue.(map[string]interface{})
portsMap := map[string]interface{}{
"port": ports["Port"],
"protocol": ports["Protocol"],
}
portsMaps = append(portsMaps, portsMap)
}
temp1["ports"] = portsMaps
}
if m1["VolumeMounts"] != nil {
volumeMountsMaps := make([]map[string]interface{}, 0)
for _, volumeMountsValue := range m1["VolumeMounts"].([]interface{}) {
volumeMounts := volumeMountsValue.(map[string]interface{})
volumeMountsMap := map[string]interface{}{
"mount_path": volumeMounts["MountPath"],
"name": volumeMounts["Name"],
"read_only": volumeMounts["ReadOnly"],
}
volumeMountsMaps = append(volumeMountsMaps, volumeMountsMap)
}
temp1["volume_mounts"] = volumeMountsMaps
}
initContainers = append(initContainers, temp1)
}
}
}
mapping["init_containers"] = initContainers
volumes := make([]map[string]interface{}, 0)
if volumesList, ok := object["Volumes"].([]interface{}); ok {
for _, v := range volumesList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"disk_volume_disk_id": m1["DiskVolumeDiskId"],
"disk_volume_fs_type": m1["DiskVolumeFsType"],
"flex_volume_driver": m1["FlexVolumeDriver"],
"flex_volume_fs_type": m1["FlexVolumeFsType"],
"flex_volume_options": m1["FlexVolumeOptions"],
"nfs_volume_path": m1["NFSVolumePath"],
"nfs_volume_read_only": m1["NFSVolumeReadOnly"],
"nfs_volume_server": m1["NFSVolumeServer"],
"name": m1["Name"],
"type": m1["Type"],
}
if m1["ConfigFileVolumeConfigFileToPaths"] != nil {
configFileVolumeConfigFileToPathsMaps := make([]map[string]interface{}, 0)
for _, configFileVolumeConfigFileToPathsValue := range m1["ConfigFileVolumeConfigFileToPaths"].([]interface{}) {
configFileVolumeConfigFileToPaths := configFileVolumeConfigFileToPathsValue.(map[string]interface{})
configFileVolumeConfigFileToPathsMap := map[string]interface{}{
"content": configFileVolumeConfigFileToPaths["Content"],
"path": configFileVolumeConfigFileToPaths["Path"],
}
configFileVolumeConfigFileToPathsMaps = append(configFileVolumeConfigFileToPathsMaps, configFileVolumeConfigFileToPathsMap)
}
temp1["config_file_volume_config_file_to_paths"] = configFileVolumeConfigFileToPathsMaps
}
volumes = append(volumes, temp1)
}
}
}
mapping["volumes"] = volumes
eciSecurityContextSli := make([]map[string]interface{}, 0)
if len(object["EciSecurityContext"].(map[string]interface{})) > 0 {
eciSecurityContext := object["EciSecurityContext"]
eciSecurityContextMap := make(map[string]interface{})
sysctlsSli := make([]map[string]interface{}, 0)
if len(eciSecurityContext.(map[string]interface{})["Sysctls"].([]interface{})) > 0 {
for _, sysctls := range eciSecurityContext.(map[string]interface{})["Sysctls"].([]interface{}) {
sysctlsMap := make(map[string]interface{})
sysctlsMap["name"] = sysctls.(map[string]interface{})["Name"]
sysctlsMap["value"] = sysctls.(map[string]interface{})["Value"]
sysctlsSli = append(sysctlsSli, sysctlsMap)
}
}
eciSecurityContextMap["sysctls"] = sysctlsSli
eciSecurityContextSli = append(eciSecurityContextSli, eciSecurityContextMap)
}
mapping["eci_security_context"] = eciSecurityContextSli
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["Key"].(string)
value := t.(map[string]interface{})["Value"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["ContainerGroupId"]))
names = append(names, object["ContainerGroupName"])
s = append(s, mapping)
continue
}
eciService := EciService{client}
id := fmt.Sprint(object["ContainerGroupId"])
getResp, err := eciService.DescribeEciContainerGroup(id)
if err != nil {
return WrapError(err)
}
mapping["restart_policy"] = getResp["RestartPolicy"]
ids = append(ids, fmt.Sprint(object["ContainerGroupId"]))
names = append(names, object["ContainerGroupName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/services/eci"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEciImageCaches() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEciImageCachesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"image": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"image_cache_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"snapshot_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Creating", "Failed", "Preparing", "Ready"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"caches": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"container_group_id": {
Type: schema.TypeString,
Computed: true,
},
"events": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"count": {
Type: schema.TypeInt,
Computed: true,
},
"first_timestamp": {
Type: schema.TypeString,
Computed: true,
},
"last_timestamp": {
Type: schema.TypeString,
Computed: true,
},
"message": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"expire_date_time": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"image_cache_id": {
Type: schema.TypeString,
Computed: true,
},
"image_cache_name": {
Type: schema.TypeString,
Computed: true,
},
"images": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"progress": {
Type: schema.TypeString,
Computed: true,
},
"snapshot_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEciImageCachesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := eci.CreateDescribeImageCachesRequest()
if v, ok := d.GetOk("image"); ok {
request.Image = v.(string)
}
if v, ok := d.GetOk("image_cache_name"); ok {
request.ImageCacheName = v.(string)
}
request.RegionId = client.RegionId
if v, ok := d.GetOk("snapshot_id"); ok {
request.SnapshotId = v.(string)
}
var objects []eci.DescribeImageCachesImageCache0
var imageCacheNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
imageCacheNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response *eci.DescribeImageCachesResponse
raw, err := client.WithEciClient(func(eciClient *eci.Client) (interface{}, error) {
return eciClient.DescribeImageCaches(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_eci_image_caches", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ = raw.(*eci.DescribeImageCachesResponse)
for _, item := range response.ImageCaches {
if imageCacheNameRegex != nil {
if !imageCacheNameRegex.MatchString(item.ImageCacheName) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[item.ImageCacheId]; !ok {
continue
}
}
if statusOk && status != "" && status != item.Status {
continue
}
objects = append(objects, item)
}
ids := make([]string, len(objects))
names := make([]string, len(objects))
s := make([]map[string]interface{}, len(objects))
for i, object := range objects {
mapping := map[string]interface{}{
"container_group_id": object.ContainerGroupId,
"expire_date_time": object.ExpireDateTime,
"id": object.ImageCacheId,
"image_cache_id": object.ImageCacheId,
"image_cache_name": object.ImageCacheName,
"images": object.Images,
"progress": object.Progress,
"snapshot_id": object.SnapshotId,
"status": object.Status,
}
var eventsList []map[string]interface{}
for _, v := range object.Events {
eventsList = append(eventsList, map[string]interface{}{
"count": v.Count,
"first_timestamp": v.FirstTimestamp,
"last_timestamp": v.LastTimestamp,
"message": v.Message,
"name": v.Name,
"type": v.Type,
})
}
mapping["events"] = eventsList
ids[i] = object.ImageCacheId
names = append(names, object.ImageCacheName)
s[i] = mapping
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("caches", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEciVirtualNodes() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEciVirtualNodesRead,
Schema: map[string]*schema.Schema{
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"security_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Cleaned", "Failed", "Pending", "Ready"}, false),
},
"tags": tagsSchema(),
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"virtual_node_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"nodes": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cpu": {
Type: schema.TypeInt,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"eni_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"events": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"count": {
Type: schema.TypeInt,
Computed: true,
},
"first_timestamp": {
Type: schema.TypeString,
Computed: true,
},
"last_timestamp": {
Type: schema.TypeString,
Computed: true,
},
"message": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"reason": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"internet_ip": {
Type: schema.TypeString,
Computed: true,
},
"intranet_ip": {
Type: schema.TypeString,
Computed: true,
},
"memory": {
Type: schema.TypeInt,
Computed: true,
},
"ram_role_name": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"security_group_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"virtual_node_id": {
Type: schema.TypeString,
Computed: true,
},
"virtual_node_name": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEciVirtualNodesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeVirtualNodes"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("security_group_id"); ok {
request["SecurityGroupId"] = v
}
if v, ok := d.GetOk("vswitch_id"); ok {
request["VSwitchId"] = v
}
if v, ok := d.GetOk("virtual_node_name"); ok {
request["VirtualNodeName"] = v
}
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
var objects []map[string]interface{}
var virtualNodeNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
virtualNodeNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
if v, ok := d.GetOk("tags"); ok {
index := 1
for key, value := range v.(map[string]interface{}) {
request[fmt.Sprintf("Tag.%d.Key", index)] = key
request[fmt.Sprintf("Tag.%d.Value", index)] = value.(string)
index = index + 1
}
}
var response map[string]interface{}
conn, err := client.NewEciClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-08-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_eci_virtual_nodes", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.VirtualNodes", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.VirtualNodes", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if virtualNodeNameRegex != nil && !virtualNodeNameRegex.MatchString(fmt.Sprint(item["VirtualNodeName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["VirtualNodeId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"cpu": formatInt(object["Cpu"]),
"create_time": object["CreationTime"],
"eni_instance_id": object["EniInstanceId"],
"internet_ip": object["InternetIp"],
"intranet_ip": object["IntranetIp"],
"memory": formatInt(object["Memory"]),
"ram_role_name": object["RamRoleName"],
"resource_group_id": object["ResourceGroupId"],
"security_group_id": object["SecurityGroupId"],
"status": object["Status"],
"vswitch_id": object["VSwitchId"],
"id": fmt.Sprint(object["VirtualNodeId"]),
"virtual_node_id": fmt.Sprint(object["VirtualNodeId"]),
"virtual_node_name": object["VirtualNodeName"],
"vpc_id": object["VpcId"],
"zone_id": object["ZoneId"],
}
events := make([]map[string]interface{}, 0)
if eventsList, ok := object["Events"].([]interface{}); ok {
for _, v := range eventsList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"count": formatInt(m1["Count"]),
"first_timestamp": m1["FirstTimestamp"],
"last_timestamp": m1["LastTimestamp"],
"message": m1["Message"],
"name": m1["Name"],
"reason": m1["Reason"],
"type": m1["Type"],
}
events = append(events, temp1)
}
}
}
mapping["events"] = events
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["Key"].(string)
value := t.(map[string]interface{})["Value"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["VirtualNodeName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("nodes", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"sort"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudEciZones() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEciZonesRead,
Schema: map[string]*schema.Schema{
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"zones": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"zone_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"region_endpoint": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEciZonesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeRegions"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
var objects []map[string]interface{}
zoneIds := make([]string, 0)
var response map[string]interface{}
conn, err := client.NewEciClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-08-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_eci_zones", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Regions", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Regions", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
objects = append(objects, item)
}
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"zone_ids": object["RecommendZones"],
"region_endpoint": object["RegionEndpoint"],
}
if v, ok := mapping["zone_ids"].([]string); ok {
zoneIds = append(zoneIds, v...)
}
s = append(s, mapping)
}
if len(zoneIds) > 0 {
sort.Strings(zoneIds)
}
d.SetId(dataResourceIdHash(zoneIds))
if err := d.Set("zones", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEcpKeyPairs() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEcpKeyPairsRead,
Schema: map[string]*schema.Schema{
"key_pair_finger_print": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"pairs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key_pair_finger_print": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"key_pair_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEcpKeyPairsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListKeyPairs"
request := make(map[string]interface{})
if v, ok := d.GetOk("key_pair_finger_print"); ok {
request["KeyPairFingerPrint"] = v
}
request["RegionId"] = client.RegionId
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var keyPairNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
keyPairNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewCloudphoneClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-12-30"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ecp_key_pairs", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.KeyPairs.KeyPair", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.KeyPairs.KeyPair", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if keyPairNameRegex != nil && !keyPairNameRegex.MatchString(fmt.Sprint(item["KeyPairName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["KeyPairName"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"key_pair_finger_print": object["KeyPairFingerPrint"],
"id": fmt.Sprint(object["KeyPairName"]),
"key_pair_name": fmt.Sprint(object["KeyPairName"]),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["KeyPairName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("pairs", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEcsAutoSnapshotPolicies() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEcsAutoSnapshotPoliciesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Expire", "Normal"}, false),
},
"tags": tagsSchema(),
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"policies": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"auto_snapshot_policy_id": {
Type: schema.TypeString,
Computed: true,
},
"copied_snapshots_retention_days": {
Type: schema.TypeInt,
Computed: true,
},
"disk_nums": {
Type: schema.TypeInt,
Computed: true,
},
"enable_cross_region_copy": {
Type: schema.TypeBool,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"repeat_weekdays": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"retention_days": {
Type: schema.TypeInt,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"target_copy_regions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"time_points": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"volume_nums": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEcsAutoSnapshotPoliciesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeAutoSnapshotPolicyEx"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("tags"); ok {
tags := make([]map[string]interface{}, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, map[string]interface{}{
"Key": key,
"Value": value.(string),
})
}
request["Tag"] = tags
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
nameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ecs_auto_snapshot_policies", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.AutoSnapshotPolicies.AutoSnapshotPolicy", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.AutoSnapshotPolicies.AutoSnapshotPolicy", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if nameRegex != nil {
if !nameRegex.MatchString(fmt.Sprint(item["AutoSnapshotPolicyName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["AutoSnapshotPolicyId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
repeatWeekdays := object["RepeatWeekdays"]
if repeatWeekdays != nil {
if repeatWeekdays, err = convertJsonStringToList(repeatWeekdays.(string)); err != nil {
return WrapError(err)
}
}
targetCopyRegions := object["TargetCopyRegions"]
if targetCopyRegions != nil {
if targetCopyRegions, err = convertJsonStringToList(targetCopyRegions.(string)); err != nil {
return WrapError(err)
}
}
timePoints := object["TimePoints"]
if timePoints != nil {
if timePoints, err = convertJsonStringToList(timePoints.(string)); err != nil {
return WrapError(err)
}
}
mapping := map[string]interface{}{
"id": fmt.Sprint(object["AutoSnapshotPolicyId"]),
"auto_snapshot_policy_id": fmt.Sprint(object["AutoSnapshotPolicyId"]),
"copied_snapshots_retention_days": formatInt(object["CopiedSnapshotsRetentionDays"]),
"disk_nums": formatInt(object["DiskNums"]),
"enable_cross_region_copy": object["EnableCrossRegionCopy"],
"name": object["AutoSnapshotPolicyName"],
"repeat_weekdays": repeatWeekdays,
"retention_days": formatInt(object["RetentionDays"]),
"status": object["Status"],
"target_copy_regions": targetCopyRegions,
"time_points": timePoints,
"volume_nums": formatInt(object["VolumeNums"]),
}
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags.Tag", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["TagKey"].(string)
value := t.(map[string]interface{})["TagValue"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
ids = append(ids, fmt.Sprint(object["AutoSnapshotPolicyId"]))
names = append(names, object["AutoSnapshotPolicyName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("policies", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEcsCommands() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEcsCommandsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"content_encoding": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"command_provider": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"RunBatScript", "RunPowerShellScript", "RunShellScript"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"commands": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"command_content": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"command_id": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"enable_parameter": {
Type: schema.TypeBool,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"parameter_names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"timeout": {
Type: schema.TypeInt,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"working_dir": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEcsCommandsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeCommands"
request := make(map[string]interface{})
if v, ok := d.GetOk("content_encoding"); ok {
request["ContentEncoding"] = v
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("name"); ok {
request["Name"] = v
}
if v, ok := d.GetOk("command_provider"); ok {
request["Provider"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("type"); ok {
request["Type"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
nameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ecs_commands", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Commands.Command", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Commands.Command", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if nameRegex != nil {
if !nameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["CommandId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"command_content": object["CommandContent"],
"id": fmt.Sprint(object["CommandId"]),
"command_id": fmt.Sprint(object["CommandId"]),
"description": object["Description"],
"enable_parameter": object["EnableParameter"],
"name": object["Name"],
"parameter_names": object["ParameterNames"].(map[string]interface{})["ParameterName"],
"timeout": object["Timeout"],
"type": object["Type"],
"working_dir": object["WorkingDir"],
}
ids = append(ids, fmt.Sprint(object["CommandId"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("commands", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEcsDedicatedHostClusters() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEcsDedicatedHostClustersRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"dedicated_host_cluster_ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"dedicated_host_cluster_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"tags": tagsSchema(),
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"clusters": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"dedicated_host_cluster_id": {
Type: schema.TypeString,
Computed: true,
},
"dedicated_host_cluster_name": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
"dedicated_host_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"dedicated_host_cluster_capacity": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"total_memory": {
Type: schema.TypeInt,
Computed: true,
},
"available_memory": {
Type: schema.TypeInt,
Computed: true,
},
"available_vcpus": {
Type: schema.TypeInt,
Computed: true,
},
"total_vcpus": {
Type: schema.TypeInt,
Computed: true,
},
"local_storage_capacities": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"available_disk": {
Type: schema.TypeInt,
Computed: true,
},
"data_disk_category": {
Type: schema.TypeString,
Computed: true,
},
"total_disk": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudEcsDedicatedHostClustersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDedicatedHostClusters"
request := make(map[string]interface{})
if v, ok := d.GetOk("dedicated_host_cluster_ids"); ok {
request["DedicatedHostClusterIds"] = convertListToJsonString(v.([]interface{}))
}
if v, ok := d.GetOk("dedicated_host_cluster_name"); ok {
request["DedicatedHostClusterName"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("zone_id"); ok {
request["ZoneId"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var dedicatedHostClusterNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
dedicatedHostClusterNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
tagsMap := make(map[string]interface{})
if v, ok := d.GetOk("tags"); ok && len(v.(map[string]interface{})) > 0 {
tagsMap = v.(map[string]interface{})
}
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ecs_dedicated_host_clusters", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.DedicatedHostClusters.DedicatedHostCluster", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.DedicatedHostClusters.DedicatedHostCluster", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if dedicatedHostClusterNameRegex != nil && !dedicatedHostClusterNameRegex.MatchString(fmt.Sprint(item["DedicatedHostClusterName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DedicatedHostClusterId"])]; !ok {
continue
}
}
if len(tagsMap) > 0 {
if _, ok := item["Tags"].(map[string]interface{}); !ok {
continue
}
tagsItem := tagsToMap(item["Tags"].(map[string]interface{})["Tag"])
if len(tagsItem) != len(tagsMap) {
continue
}
match := true
for key, value := range tagsItem {
if v, ok := tagsMap[key]; !ok || v.(string) != value {
match = false
break
}
}
if !match {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["DedicatedHostClusterId"]),
"dedicated_host_cluster_id": fmt.Sprint(object["DedicatedHostClusterId"]),
"dedicated_host_cluster_name": object["DedicatedHostClusterName"],
"description": object["Description"],
"resource_group_id": object["ResourceGroupId"],
"zone_id": object["ZoneId"],
"dedicated_host_ids": object["DedicatedHostIds"].(map[string]interface{})["DedicatedHostId"],
}
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags.Tag", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["TagKey"].(string)
value := t.(map[string]interface{})["TagValue"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
dedicatedHostClusterCapacity := make([]map[string]interface{}, 0)
if dedicatedHostClusterCapacityArr, ok := object["DedicatedHostClusterCapacity"].(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"total_memory": formatInt(dedicatedHostClusterCapacityArr["TotalMemory"]),
"available_memory": formatInt(dedicatedHostClusterCapacityArr["AvailableMemory"]),
"available_vcpus": formatInt(dedicatedHostClusterCapacityArr["AvailableVcpus"]),
"total_vcpus": formatInt(dedicatedHostClusterCapacityArr["TotalVcpus"]),
}
localStorageCapacity := make([]map[string]interface{}, 0)
if localStorageCapacitiesArr, ok := dedicatedHostClusterCapacityArr["LocalStorageCapacities"].(map[string]interface{}); ok {
if localStorageCapacityList, ok := localStorageCapacitiesArr["LocalStorageCapacity"].([]interface{}); ok {
for _, v := range localStorageCapacityList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"available_disk": formatInt(m1["AvailableDisk"]),
"data_disk_category": m1["DataDiskCategory"],
"total_disk": formatInt(m1["TotalDisk"]),
}
localStorageCapacity = append(localStorageCapacity, temp1)
}
}
}
}
temp1["local_storage_capacities"] = localStorageCapacity
dedicatedHostClusterCapacity = append(dedicatedHostClusterCapacity, temp1)
}
mapping["dedicated_host_cluster_capacity"] = dedicatedHostClusterCapacity
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["DedicatedHostClusterName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("clusters", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEcsDedicatedHosts() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEcsDedicatedHostsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"dedicated_host_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"dedicated_host_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"dedicated_host_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"operation_locks": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"lock_reason": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
},
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "Creating", "PermanentFailure", "Released", "UnderAssessment"}, false),
},
"tags": tagsSchema(),
"zone_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"hosts": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"action_on_maintenance": {
Type: schema.TypeString,
Computed: true,
},
"auto_placement": {
Type: schema.TypeString,
Computed: true,
},
"auto_release_time": {
Type: schema.TypeString,
Computed: true,
},
"capacity": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"available_local_storage": {
Type: schema.TypeInt,
Computed: true,
},
"available_memory": {
Type: schema.TypeFloat,
Computed: true,
},
"available_vcpus": {
Type: schema.TypeInt,
Computed: true,
},
"available_vgpus": {
Type: schema.TypeInt,
Computed: true,
},
"local_storage_category": {
Type: schema.TypeString,
Computed: true,
},
"total_local_storage": {
Type: schema.TypeInt,
Computed: true,
},
"total_memory": {
Type: schema.TypeFloat,
Computed: true,
},
"total_vcpus": {
Type: schema.TypeInt,
Computed: true,
},
"total_vgpus": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"cores": {
Type: schema.TypeInt,
Computed: true,
},
"cpu_over_commit_ratio": {
Type: schema.TypeFloat,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"dedicated_host_id": {
Type: schema.TypeString,
Computed: true,
},
"dedicated_host_name": {
Type: schema.TypeString,
Computed: true,
},
"dedicated_host_type": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"expired_time": {
Type: schema.TypeString,
Computed: true,
},
"gpu_spec": {
Type: schema.TypeString,
Computed: true,
},
"machine_id": {
Type: schema.TypeString,
Computed: true,
},
"network_attributes": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"slb_udp_timeout": {
Type: schema.TypeInt,
Computed: true,
},
"udp_timeout": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"operation_locks": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"lock_reason": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"physical_gpus": {
Type: schema.TypeInt,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"sale_cycle": {
Type: schema.TypeString,
Computed: true,
},
"sockets": {
Type: schema.TypeInt,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"supported_custom_instance_type_families": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"supported_instance_type_families": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"supported_instance_types_list": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEcsDedicatedHostsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDedicatedHosts"
request := make(map[string]interface{})
if v, ok := d.GetOk("dedicated_host_name"); ok {
request["DedicatedHostName"] = v
}
if v, ok := d.GetOk("dedicated_host_type"); ok {
request["DedicatedHostType"] = v
}
if v, ok := d.GetOk("dedicated_host_id"); ok {
request["DedicatedHostId"] = v
}
if v, ok := d.GetOk("operation_locks"); ok {
operationLocksMaps := make([]map[string]interface{}, 0)
for _, operationLocks := range v.([]interface{}) {
operationLocksMap := make(map[string]interface{})
operationLocksArg := operationLocks.(map[string]interface{})
operationLocksMap["LockReason"] = operationLocksArg["lock_reason"]
operationLocksMaps = append(operationLocksMaps, operationLocksMap)
}
request["OperationLocks"] = operationLocksMaps
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
if v, ok := d.GetOk("tags"); ok {
tags := make([]map[string]interface{}, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, map[string]interface{}{
"Key": key,
"Value": value.(string),
})
}
request["Tag"] = tags
}
if v, ok := d.GetOk("zone_id"); ok {
request["ZoneId"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var dedicatedHostNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
dedicatedHostNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ecs_dedicated_hosts", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.DedicatedHosts.DedicatedHost", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.DedicatedHosts.DedicatedHost", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if dedicatedHostNameRegex != nil {
if !dedicatedHostNameRegex.MatchString(fmt.Sprint(item["DedicatedHostName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DedicatedHostId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"action_on_maintenance": object["ActionOnMaintenance"],
"auto_placement": object["AutoPlacement"],
"auto_release_time": object["AutoReleaseTime"],
"cores": formatInt(object["Cores"]),
"cpu_over_commit_ratio": object["CpuOverCommitRatio"],
"id": fmt.Sprint(object["DedicatedHostId"]),
"dedicated_host_id": fmt.Sprint(object["DedicatedHostId"]),
"dedicated_host_name": object["DedicatedHostName"],
"dedicated_host_type": object["DedicatedHostType"],
"description": object["Description"],
"expired_time": object["ExpiredTime"],
"gpu_spec": object["GPUSpec"],
"machine_id": object["MachineId"],
"payment_type": object["ChargeType"],
"physical_gpus": formatInt(object["PhysicalGpus"]),
"resource_group_id": object["ResourceGroupId"],
"sale_cycle": object["SaleCycle"],
"sockets": formatInt(object["Sockets"]),
"status": object["Status"],
"supported_custom_instance_type_families": object["SupportedCustomInstanceTypeFamilies"].(map[string]interface{})["SupportedCustomInstanceTypeFamily"],
"supported_instance_type_families": object["SupportedInstanceTypeFamilies"].(map[string]interface{})["SupportedInstanceTypeFamily"],
"supported_instance_types_list": object["SupportedInstanceTypesList"].(map[string]interface{})["SupportedInstanceTypesList"],
"zone_id": object["ZoneId"],
}
operationLock := make([]map[string]interface{}, 0)
if operationLockList, ok := object["OperationLocks"].(map[string]interface{})["OperationLock"].([]interface{}); ok {
for _, v := range operationLockList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"lock_reason": m1["LockReason"],
}
operationLock = append(operationLock, temp1)
}
}
}
mapping["operation_locks"] = operationLock
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags.Tag", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["TagKey"].(string)
value := t.(map[string]interface{})["TagValue"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
ids = append(ids, fmt.Sprint(object["DedicatedHostId"]))
names = append(names, object["DedicatedHostName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("hosts", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEcsDeploymentSets() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEcsDeploymentSetsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"deployment_set_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"strategy": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Availability"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"sets": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"deployment_set_id": {
Type: schema.TypeString,
Computed: true,
},
"deployment_set_name": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"domain": {
Type: schema.TypeString,
Computed: true,
},
"granularity": {
Type: schema.TypeString,
Computed: true,
},
"instance_amount": {
Type: schema.TypeInt,
Computed: true,
},
"instance_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"strategy": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEcsDeploymentSetsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDeploymentSets"
request := make(map[string]interface{})
if v, ok := d.GetOk("deployment_set_name"); ok {
request["DeploymentSetName"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("strategy"); ok {
request["Strategy"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var deploymentSetNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
deploymentSetNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ecs_deployment_sets", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.DeploymentSets.DeploymentSet", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.DeploymentSets.DeploymentSet", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if deploymentSetNameRegex != nil && !deploymentSetNameRegex.MatchString(fmt.Sprint(item["DeploymentSetName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DeploymentSetId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": object["CreationTime"],
"deployment_set_id": object["DeploymentSetId"],
"deployment_set_name": object["DeploymentSetName"],
"description": object["DeploymentSetDescription"],
"domain": convertEcsDeploymentSetDomainResponse(object["Domain"]),
"granularity": convertEcsDeploymentSetGranularityResponse(object["Granularity"]),
"instance_amount": formatInt(object["InstanceAmount"]),
"strategy": object["DeploymentStrategy"],
}
if v, ok := object["InstanceIds"].(map[string]interface{}); ok {
mapping["instance_ids"] = v["InstanceId"]
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["DeploymentSetName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("sets", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEcsDisks() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEcsDisksRead,
Schema: map[string]*schema.Schema{
"additional_attributes": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"auto_snapshot_policy_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"category": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"cloud", "cloud_efficiency", "cloud_essd", "cloud_ssd", "ephemeral_ssd"}, false),
},
"delete_auto_snapshot": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"delete_with_instance": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"disk_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"disk_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"system", "data", "all"}, false),
},
"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"system", "data", "all"}, false),
Deprecated: "Field 'type' has been deprecated from provider version 1.122.0. New field 'disk_type' instead.",
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"enable_auto_snapshot": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: true,
},
"enable_automated_snapshot_policy": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"enable_shared": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"encrypted": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"on", "off"}, false),
},
"instance_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"kms_key_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"operation_locks": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"lock_reason": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
},
},
"payment_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo", "Subscription"}, false),
},
"portable": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"snapshot_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Attaching", "Available", "Creating", "Detaching", "In_use", "Migrating", "ReIniting", "Transferring"}, false),
},
"tags": tagsSchema(),
"zone_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"availability_zone": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Deprecated: "Field 'availability_zone' has been deprecated from provider version 1.122.0. New field 'zone_id' instead",
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"page_number": {
Type: schema.TypeInt,
Optional: true,
},
"page_size": {
Type: schema.TypeInt,
Optional: true,
},
"disks": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"attached_time": {
Type: schema.TypeString,
Computed: true,
},
"auto_snapshot_policy_id": {
Type: schema.TypeString,
Computed: true,
},
"category": {
Type: schema.TypeString,
Computed: true,
},
"delete_auto_snapshot": {
Type: schema.TypeBool,
Computed: true,
},
"delete_with_instance": {
Type: schema.TypeBool,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"detached_time": {
Type: schema.TypeString,
Computed: true,
},
"device": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"disk_id": {
Type: schema.TypeString,
Computed: true,
},
"disk_name": {
Type: schema.TypeString,
Computed: true,
},
"enable_auto_snapshot": {
Type: schema.TypeBool,
Computed: true,
},
"enable_automated_snapshot_policy": {
Type: schema.TypeBool,
Computed: true,
},
"encrypted": {
Type: schema.TypeString,
Computed: true,
},
"expired_time": {
Type: schema.TypeString,
Computed: true,
},
"iops": {
Type: schema.TypeInt,
Computed: true,
},
"iops_read": {
Type: schema.TypeInt,
Computed: true,
},
"iops_write": {
Type: schema.TypeInt,
Computed: true,
},
"image_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"kms_key_id": {
Type: schema.TypeString,
Computed: true,
},
"mount_instance_num": {
Type: schema.TypeInt,
Computed: true,
},
"mount_instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"attached_time": {
Type: schema.TypeString,
Computed: true,
},
"device": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"operation_locks": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"lock_reason": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"performance_level": {
Type: schema.TypeString,
Computed: true,
},
"portable": {
Type: schema.TypeBool,
Computed: true,
},
"product_code": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"size": {
Type: schema.TypeInt,
Computed: true,
},
"snapshot_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
"availability_zone": {
Type: schema.TypeString,
Computed: true,
},
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"creation_time": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"disk_type": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"total_count": {
Type: schema.TypeInt,
Computed: true,
},
},
}
}
func dataSourceAlicloudEcsDisksRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDisks"
request := make(map[string]interface{})
if v, ok := d.GetOk("additional_attributes"); ok {
request["AdditionalAttributes"] = convertListToJsonString(v.(*schema.Set).List())
}
if v, ok := d.GetOk("auto_snapshot_policy_id"); ok {
request["AutoSnapshotPolicyId"] = v
}
if v, ok := d.GetOk("category"); ok {
request["Category"] = v
}
if v, ok := d.GetOkExists("delete_auto_snapshot"); ok {
request["DeleteAutoSnapshot"] = v
}
if v, ok := d.GetOkExists("delete_with_instance"); ok {
request["DeleteWithInstance"] = v
}
if v, ok := d.GetOk("disk_name"); ok {
request["DiskName"] = v
}
if v, ok := d.GetOk("disk_type"); ok {
request["DiskType"] = v
} else if v, ok := d.GetOk("type"); ok {
request["DiskType"] = v
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
if v, ok := d.GetOkExists("enable_auto_snapshot"); ok {
request["EnableAutoSnapshot"] = v
}
if v, ok := d.GetOkExists("enable_automated_snapshot_policy"); ok {
request["EnableAutomatedSnapshotPolicy"] = v
}
if v, ok := d.GetOkExists("enable_shared"); ok {
request["EnableShared"] = v
}
if v, ok := d.GetOkExists("encrypted"); ok {
if v == string(OnFlag) {
request["Encrypted"] = true
} else {
request["Encrypted"] = false
}
}
if v, ok := d.GetOk("instance_id"); ok {
request["InstanceId"] = v
}
if v, ok := d.GetOk("kms_key_id"); ok {
request["KMSKeyId"] = v
}
if v, ok := d.GetOk("operation_locks"); ok {
operationLocksMaps := make([]map[string]interface{}, 0)
for _, operationLocks := range v.([]interface{}) {
operationLocksMap := make(map[string]interface{})
operationLocksArg := operationLocks.(map[string]interface{})
operationLocksMap["LockReason"] = operationLocksArg["lock_reason"]
operationLocksMaps = append(operationLocksMaps, operationLocksMap)
}
request["OperationLocks"] = operationLocksMaps
}
if v, ok := d.GetOk("payment_type"); ok {
request["DiskChargeType"] = convertEcsDiskPaymentTypeRequest(v.(string))
}
if v, ok := d.GetOkExists("portable"); ok {
request["Portable"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("snapshot_id"); ok {
request["SnapshotId"] = v
}
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
if v, ok := d.GetOk("tags"); ok {
tags := make([]map[string]interface{}, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, map[string]interface{}{
"Key": key,
"Value": value.(string),
})
}
request["Tag"] = tags
}
if v, ok := d.GetOk("zone_id"); ok {
request["ZoneId"] = v
} else if v, ok := d.GetOk("availability_zone"); ok {
request["ZoneId"] = v
}
if v, ok := d.GetOk("page_number"); ok && v.(int) > 0 {
request["PageNumber"] = v.(int)
} else {
request["PageNumber"] = 1
}
if v, ok := d.GetOk("page_size"); ok && v.(int) > 0 {
request["PageSize"] = v.(int)
} else {
request["PageSize"] = PageSizeLarge
}
var objects []interface{}
var diskNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
diskNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ecs_disks", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Disks.Disk", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Disks.Disk", response)
}
result, _ := resp.([]interface{})
if isPagingRequest(d) {
objects = result
break
}
for _, v := range result {
item := v.(map[string]interface{})
if diskNameRegex != nil {
if !diskNameRegex.MatchString(fmt.Sprint(item["DiskName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DiskId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, v := range objects {
object := v.(map[string]interface{})
mapping := map[string]interface{}{
"attached_time": object["AttachedTime"],
"auto_snapshot_policy_id": object["AutoSnapshotPolicyId"],
"category": object["Category"],
"delete_auto_snapshot": object["DeleteAutoSnapshot"],
"delete_with_instance": object["DeleteWithInstance"],
"description": object["Description"],
"detached_time": object["DetachedTime"],
"device": object["Device"],
"id": fmt.Sprint(object["DiskId"]),
"disk_id": fmt.Sprint(object["DiskId"]),
"disk_name": object["DiskName"],
"enable_auto_snapshot": object["EnableAutoSnapshot"],
"enable_automated_snapshot_policy": object["EnableAutomatedSnapshotPolicy"],
"encrypted": string(OnFlag),
"expired_time": object["ExpiredTime"],
"iops": formatInt(object["IOPS"]),
"iops_read": formatInt(object["IOPSRead"]),
"iops_write": formatInt(object["IOPSWrite"]),
"image_id": object["ImageId"],
"instance_id": object["InstanceId"],
"kms_key_id": object["KMSKeyId"],
"mount_instance_num": formatInt(object["MountInstanceNum"]),
"payment_type": convertEcsDiskPaymentTypeResponse(object["DiskChargeType"].(string)),
"performance_level": object["PerformanceLevel"],
"portable": object["Portable"],
"product_code": object["ProductCode"],
"resource_group_id": object["ResourceGroupId"],
"size": formatInt(object["Size"]),
"snapshot_id": object["SourceSnapshotId"],
"status": object["Status"],
"zone_id": object["ZoneId"],
"availability_zone": object["ZoneId"],
"disk_type": object["Type"],
"type": object["Type"],
"region_id": object["RegionId"],
"creation_time": object["CreationTime"],
"name": object["DiskName"],
}
if !object["Encrypted"].(bool) {
mapping["encrypted"] = string(OffFlag)
}
mountInstance := make([]map[string]interface{}, 0)
if mountInstances, ok := object["MountInstances"]; ok {
if mountInstanceList, ok := mountInstances.(map[string]interface{})["MountInstance"].([]interface{}); ok {
for _, v := range mountInstanceList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"attached_time": m1["AttachedTime"],
"device": m1["Device"],
"instance_id": m1["InstanceId"],
}
mountInstance = append(mountInstance, temp1)
}
}
}
}
mapping["mount_instances"] = mountInstance
operationLock := make([]map[string]interface{}, 0)
if operationLockList, ok := object["OperationLocks"].(map[string]interface{})["OperationLock"].([]interface{}); ok {
for _, v := range operationLockList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"lock_reason": m1["LockReason"],
}
operationLock = append(operationLock, temp1)
}
}
}
mapping["operation_locks"] = operationLock
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags.Tag", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["TagKey"].(string)
value := t.(map[string]interface{})["TagValue"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
ids = append(ids, fmt.Sprint(object["DiskId"]))
names = append(names, object["DiskName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("disks", s); err != nil {
return WrapError(err)
}
if err := d.Set("total_count", formatInt(response["TotalCount"])); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEcsHpcClusters() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEcsHpcClustersRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"clusters": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"hpc_cluster_id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEcsHpcClustersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeHpcClusters"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
nameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("DescribeHpcClusters")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ecs_hpc_clusters", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.HpcClusters.HpcCluster", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.HpcClusters.HpcCluster", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if nameRegex != nil {
if !nameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["HpcClusterId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"description": object["Description"],
"id": fmt.Sprint(object["HpcClusterId"]),
"hpc_cluster_id": fmt.Sprint(object["HpcClusterId"]),
"name": object["Name"],
}
ids = append(ids, fmt.Sprint(object["HpcClusterId"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("clusters", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEcsKeyPairs() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEcsKeyPairsRead,
Schema: map[string]*schema.Schema{
"finger_print": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"tags": tagsSchema(),
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"pairs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"finger_print": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"key_pair_name": {
Type: schema.TypeString,
Computed: true,
},
"key_name": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{Schema: outputInstancesSchema()},
},
},
},
},
"key_pairs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"finger_print": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"key_pair_name": {
Type: schema.TypeString,
Computed: true,
},
"key_name": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{Schema: outputInstancesSchema()},
},
},
},
Deprecated: "Field 'key_pairs' has been deprecated from provider version 1.121.0. New field 'pairs' instead.",
},
},
}
}
func dataSourceAlicloudEcsKeyPairsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeKeyPairs"
request := make(map[string]interface{})
if v, ok := d.GetOk("finger_print"); ok {
request["KeyPairFingerPrint"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("tags"); ok {
tags := make([]map[string]interface{}, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, map[string]interface{}{
"Key": key,
"Value": value.(string),
})
}
request["Tag"] = tags
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var keyPairNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
keyPairNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
objectMap := make(map[string][]map[string]interface{})
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ecs_key_pairs", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.KeyPairs.KeyPair", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.KeyPairs.KeyPair", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if keyPairNameRegex != nil {
if !keyPairNameRegex.MatchString(fmt.Sprint(item["KeyPairName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["KeyPairName"])]; !ok {
continue
}
}
objects = append(objects, item)
objectMap[item["KeyPairName"].(string)] = make([]map[string]interface{}, 0)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
action = "DescribeInstances"
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ecs_key_pairs", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Instances.Instance", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Instances.Instance", response)
}
result, _ := resp.([]interface{})
for _, inst := range result {
itemInst := inst.(map[string]interface{})
if itemInst["KeyPairName"] != nil {
if _, ok := objectMap[itemInst["KeyPairName"].(string)]; ok {
publicIp := itemInst["EipAddress"].(map[string]interface{})["IpAddress"]
if publicIp == "" && len(itemInst["PublicIpAddress"].(map[string]interface{})["IpAddress"].([]interface{})) > 0 {
publicIp = itemInst["PublicIpAddress"].(map[string]interface{})["IpAddress"].([]interface{})[0]
}
var privateIp string
if len(itemInst["InnerIpAddress"].(map[string]interface{})["IpAddress"].([]interface{})) > 0 {
privateIp = itemInst["InnerIpAddress"].(map[string]interface{})["IpAddress"].([]interface{})[0].(string)
} else if len(itemInst["VpcAttributes"].(map[string]interface{})["PrivateIpAddress"].(map[string]interface{})["IpAddress"].([]interface{})) > 0 {
privateIp = itemInst["VpcAttributes"].(map[string]interface{})["PrivateIpAddress"].(map[string]interface{})["IpAddress"].([]interface{})[0].(string)
}
mapping := map[string]interface{}{
"availability_zone": itemInst["ZoneId"],
"instance_id": itemInst["InstanceId"],
"instance_name": itemInst["InstanceName"],
"vswitch_id": itemInst["VpcAttributes"].(map[string]interface{})["VSwitchId"],
"public_ip": publicIp,
"private_ip": privateIp,
}
val := objectMap[itemInst["KeyPairName"].(string)]
val = append(val, mapping)
objectMap[itemInst["KeyPairName"].(string)] = val
}
}
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"finger_print": object["KeyPairFingerPrint"],
"id": fmt.Sprint(object["KeyPairName"]),
"key_pair_name": fmt.Sprint(object["KeyPairName"]),
"key_name": object["KeyPairName"],
"resource_group_id": object["ResourceGroupId"],
"instances": objectMap[object["KeyPairName"].(string)],
}
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags.Tag", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["TagKey"].(string)
value := t.(map[string]interface{})["TagValue"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
ids = append(ids, fmt.Sprint(object["KeyPairName"]))
names = append(names, object["KeyPairName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("key_pairs", s); err != nil {
return WrapError(err)
}
if err := d.Set("pairs", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEcsLaunchTemplates() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEcsLaunchTemplatesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"launch_template_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"template_tags": tagsSchema(),
"template_resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"templates": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"auto_release_time": {
Type: schema.TypeString,
Computed: true,
},
"created_by": {
Type: schema.TypeString,
Computed: true,
},
"data_disks": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"category": {
Type: schema.TypeString,
Computed: true,
},
"delete_with_instance": {
Type: schema.TypeBool,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"encrypted": {
Type: schema.TypeBool,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"performance_level": {
Type: schema.TypeString,
Computed: true,
},
"size": {
Type: schema.TypeInt,
Computed: true,
},
"snapshot_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"default_version_number": {
Type: schema.TypeInt,
Computed: true,
},
"deployment_set_id": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"enable_vm_os_config": {
Type: schema.TypeBool,
Computed: true,
},
"host_name": {
Type: schema.TypeString,
Computed: true,
},
"image_id": {
Type: schema.TypeString,
Computed: true,
},
"image_owner_alias": {
Type: schema.TypeString,
Computed: true,
},
"instance_charge_type": {
Type: schema.TypeString,
Computed: true,
},
"instance_name": {
Type: schema.TypeString,
Computed: true,
},
"instance_type": {
Type: schema.TypeString,
Computed: true,
},
"internet_charge_type": {
Type: schema.TypeString,
Computed: true,
},
"internet_max_bandwidth_in": {
Type: schema.TypeInt,
Computed: true,
},
"internet_max_bandwidth_out": {
Type: schema.TypeInt,
Computed: true,
},
"io_optimized": {
Type: schema.TypeString,
Computed: true,
},
"key_pair_name": {
Type: schema.TypeString,
Computed: true,
},
"latest_version_number": {
Type: schema.TypeInt,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"launch_template_id": {
Type: schema.TypeString,
Computed: true,
},
"launch_template_name": {
Type: schema.TypeString,
Computed: true,
},
"modified_time": {
Type: schema.TypeString,
Computed: true,
},
"network_interfaces": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"primary_ip": {
Type: schema.TypeString,
Computed: true,
},
"security_group_id": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"network_type": {
Type: schema.TypeString,
Computed: true,
},
"password_inherit": {
Type: schema.TypeBool,
Computed: true,
},
"period": {
Type: schema.TypeInt,
Computed: true,
},
"private_ip_address": {
Type: schema.TypeString,
Computed: true,
},
"ram_role_name": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"security_enhancement_strategy": {
Type: schema.TypeString,
Computed: true,
},
"security_group_id": {
Type: schema.TypeString,
Computed: true,
},
"security_group_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"spot_duration": {
Type: schema.TypeString,
Computed: true,
},
"spot_price_limit": {
Type: schema.TypeFloat,
Computed: true,
},
"spot_strategy": {
Type: schema.TypeString,
Computed: true,
},
"system_disk": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"category": {
Type: schema.TypeString,
Computed: true,
},
"delete_with_instance": {
Type: schema.TypeBool,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"iops": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"performance_level": {
Type: schema.TypeString,
Computed: true,
},
"size": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"template_tags": {
Type: schema.TypeMap,
Computed: true,
},
"user_data": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"version_description": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudEcsLaunchTemplatesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeLaunchTemplates"
request := make(map[string]interface{})
if v, ok := d.GetOk("launch_template_name"); ok {
request["LaunchTemplateName"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("template_tags"); ok {
tags := make([]map[string]interface{}, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, map[string]interface{}{
"Key": key,
"Value": value.(string),
})
}
request["TemplateTag"] = tags
}
if v, ok := d.GetOk("template_resource_group_id"); ok {
request["TemplateResourceGroupId"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var launchTemplateNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
launchTemplateNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ecs_launch_templates", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.LaunchTemplateSets.LaunchTemplateSet", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.LaunchTemplateSets.LaunchTemplateSet", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if launchTemplateNameRegex != nil {
if !launchTemplateNameRegex.MatchString(fmt.Sprint(item["LaunchTemplateName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["LaunchTemplateId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"created_by": object["CreatedBy"],
"default_version_number": object["DefaultVersionNumber"],
"latest_version_number": object["LatestVersionNumber"],
"id": fmt.Sprint(object["LaunchTemplateId"]),
"launch_template_id": fmt.Sprint(object["LaunchTemplateId"]),
"launch_template_name": object["LaunchTemplateName"],
"modified_time": object["ModifiedTime"],
"resource_group_id": object["ResourceGroupId"],
}
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags.Tag", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["TagKey"].(string)
value := t.(map[string]interface{})["TagValue"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["template_tags"] = tags
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["LaunchTemplateId"]))
names = append(names, object["LaunchTemplateName"])
s = append(s, mapping)
continue
}
ecsService := EcsService{client}
id := fmt.Sprint(object["LaunchTemplateId"])
getResp, err := ecsService.DescribeLaunchTemplateVersions(id)
if err != nil {
return WrapError(err)
}
describeLaunchTemplateVersionsObject := make(map[string]interface{})
for _, version := range getResp {
if version.(map[string]interface{})["VersionNumber"] == object["LatestVersionNumber"] {
describeLaunchTemplateVersionsObject = version.(map[string]interface{})
}
}
mapping["auto_release_time"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["AutoReleaseTime"]
dataDisk := make([]map[string]interface{}, 0)
if dataDiskList, ok := describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["DataDisks"].(map[string]interface{})["DataDisk"].([]interface{}); ok {
for _, v := range dataDiskList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"category": m1["Category"],
"delete_with_instance": m1["DeleteWithInstance"],
"description": m1["Description"],
"encrypted": m1["Encrypted"],
"name": m1["DiskName"],
"performance_level": m1["PerformanceLevel"],
"size": m1["Size"],
"snapshot_id": m1["SnapshotId"],
}
dataDisk = append(dataDisk, temp1)
}
}
}
mapping["data_disks"] = dataDisk
mapping["deployment_set_id"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["DeploymentSetId"]
mapping["description"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["Description"]
mapping["enable_vm_os_config"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["EnableVmOsConfig"]
mapping["host_name"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["HostName"]
mapping["image_id"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["ImageId"]
mapping["image_owner_alias"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["ImageOwnerAlias"]
mapping["instance_charge_type"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["InstanceChargeType"]
mapping["instance_name"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["InstanceName"]
mapping["instance_type"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["InstanceType"]
mapping["internet_charge_type"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["InternetChargeType"]
mapping["internet_max_bandwidth_in"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["InternetMaxBandwidthIn"]
mapping["internet_max_bandwidth_out"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["InternetMaxBandwidthOut"]
mapping["io_optimized"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["IoOptimized"]
mapping["key_pair_name"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["KeyPairName"]
networkInterface := make([]map[string]interface{}, 0)
if networkInterfaceList, ok := describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["NetworkInterfaces"].(map[string]interface{})["NetworkInterface"].([]interface{}); ok {
for _, v := range networkInterfaceList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"description": m1["Description"],
"name": m1["NetworkInterfaceName"],
"primary_ip": m1["PrimaryIpAddress"],
"security_group_id": m1["SecurityGroupId"],
"vswitch_id": m1["VSwitchId"],
}
networkInterface = append(networkInterface, temp1)
}
}
}
mapping["network_interfaces"] = networkInterface
mapping["network_type"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["NetworkType"]
mapping["password_inherit"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["PasswordInherit"]
mapping["period"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["Period"]
mapping["private_ip_address"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["PrivateIpAddress"]
mapping["ram_role_name"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["RamRoleName"]
mapping["security_enhancement_strategy"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SecurityEnhancementStrategy"]
mapping["security_group_id"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SecurityGroupId"]
if describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SecurityGroupIds"] != nil {
mapping["security_group_ids"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SecurityGroupIds"].(map[string]interface{})["SecurityGroupId"]
}
mapping["spot_duration"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SpotDuration"]
mapping["spot_price_limit"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SpotPriceLimit"]
mapping["spot_strategy"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SpotStrategy"]
systemDiskSli := make([]map[string]interface{}, 0)
systemDiskMap := make(map[string]interface{})
systemDiskMap["category"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SystemDisk.Category"]
systemDiskMap["delete_with_instance"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SystemDisk.DeleteWithInstance"]
systemDiskMap["description"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SystemDisk.Description"]
systemDiskMap["iops"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SystemDisk.Iops"]
systemDiskMap["name"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SystemDisk.DiskName"]
systemDiskMap["performance_level"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SystemDisk.PerformanceLevel"]
systemDiskMap["size"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SystemDisk.Size"]
systemDiskSli = append(systemDiskSli, systemDiskMap)
mapping["system_disk"] = systemDiskSli
mapping["user_data"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["UserData"]
mapping["vswitch_id"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["VSwitchId"]
mapping["version_description"] = describeLaunchTemplateVersionsObject["VersionDescription"]
mapping["vpc_id"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["VpcId"]
mapping["zone_id"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["ZoneId"]
ids = append(ids, fmt.Sprint(object["LaunchTemplateId"]))
names = append(names, object["LaunchTemplateName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("templates", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEcsNetworkInterfaces() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEcsNetworkInterfacesRead,
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"network_interface_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Deprecated: "Field 'name' has been deprecated from provider version 1.123.1. New field 'network_interface_name' instead",
},
"primary_ip_address": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"private_ip": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Deprecated: "Field 'private_ip' has been deprecated from provider version 1.123.1. New field 'primary_ip_address' instead",
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"security_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"service_managed": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Attaching", "Available", "CreateFailed", "Creating", "Deleting", "Detaching", "InUse", "Linked", "Linking", "Unlinking"}, false),
},
"tags": tagsSchema(),
"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Primary", "Secondary"}, false),
},
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"interfaces": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"mac": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"network_interface_id": {
Type: schema.TypeString,
Computed: true,
},
"network_interface_name": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"primary_ip_address": {
Type: schema.TypeString,
Computed: true,
},
"private_ip": {
Type: schema.TypeString,
Computed: true,
},
"private_ip_addresses": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"private_ips": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"queue_number": {
Type: schema.TypeInt,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"security_group_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"service_id": {
Type: schema.TypeInt,
Computed: true,
},
"service_managed": {
Type: schema.TypeBool,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
"creation_time": {
Type: schema.TypeString,
Computed: true,
},
"security_groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
},
}
}
func dataSourceAlicloudEcsNetworkInterfacesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeNetworkInterfaces"
request := make(map[string]interface{})
if v, ok := d.GetOk("instance_id"); ok {
request["InstanceId"] = v
}
if v, ok := d.GetOk("network_interface_name"); ok {
request["NetworkInterfaceName"] = v
} else if v, ok := d.GetOk("name"); ok {
request["NetworkInterfaceName"] = v
}
if v, ok := d.GetOk("primary_ip_address"); ok {
request["PrimaryIpAddress"] = v
} else if v, ok := d.GetOk("private_ip"); ok {
request["PrimaryIpAddress"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("security_group_id"); ok {
request["SecurityGroupId"] = v
}
if v, ok := d.GetOkExists("service_managed"); ok {
request["ServiceManaged"] = v
}
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
if v, ok := d.GetOk("tags"); ok {
tags := make([]map[string]interface{}, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, map[string]interface{}{
"Key": key,
"Value": value.(string),
})
}
request["Tag"] = tags
}
if v, ok := d.GetOk("type"); ok {
request["Type"] = v
}
if v, ok := d.GetOk("vswitch_id"); ok {
request["VSwitchId"] = v
}
if v, ok := d.GetOk("vpc_id"); ok {
request["VpcId"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var networkInterfaceNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
networkInterfaceNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ecs_network_interfaces", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.NetworkInterfaceSets.NetworkInterfaceSet", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.NetworkInterfaceSets.NetworkInterfaceSet", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if networkInterfaceNameRegex != nil {
if !networkInterfaceNameRegex.MatchString(fmt.Sprint(item["NetworkInterfaceName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["NetworkInterfaceId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"description": object["Description"],
"instance_id": object["InstanceId"],
"mac": object["MacAddress"],
"id": fmt.Sprint(object["NetworkInterfaceId"]),
"network_interface_id": fmt.Sprint(object["NetworkInterfaceId"]),
"network_interface_name": object["NetworkInterfaceName"],
"name": object["NetworkInterfaceName"],
"primary_ip_address": object["PrivateIpAddress"],
"private_ip": object["PrivateIpAddress"],
"queue_number": formatInt(object["QueueNumber"]),
"resource_group_id": object["ResourceGroupId"],
"security_group_ids": object["SecurityGroupIds"].(map[string]interface{})["SecurityGroupId"],
"service_id": formatInt(object["ServiceID"]),
"service_managed": object["ServiceManaged"],
"status": object["Status"],
"type": object["Type"],
"vswitch_id": object["VSwitchId"],
"vpc_id": object["VpcId"],
"zone_id": object["ZoneId"],
"creation_time": object["CreationTime"],
"security_groups": object["SecurityGroupIds"].(map[string]interface{})["SecurityGroupId"],
}
if v := object["PrivateIpSets"].(map[string]interface{})["PrivateIpSet"].([]interface{}); len(v) > 0 {
privateIps := make([]interface{}, 0, len(object["PrivateIpSets"].(map[string]interface{})["PrivateIpSet"].([]interface{})))
for _, v := range object["PrivateIpSets"].(map[string]interface{})["PrivateIpSet"].([]interface{}) {
if !v.(map[string]interface{})["Primary"].(bool) {
privateIps = append(privateIps, v.(map[string]interface{})["PrivateIpAddress"])
}
}
mapping["private_ip_addresses"] = privateIps
mapping["private_ips"] = privateIps
}
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags.Tag", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["TagKey"].(string)
value := t.(map[string]interface{})["TagValue"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
ids = append(ids, fmt.Sprint(object["NetworkInterfaceId"]))
names = append(names, object["NetworkInterfaceName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("interfaces", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEcsPrefixLists() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEcsPrefixListsRead,
Schema: map[string]*schema.Schema{
"address_family": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"IPv4", "IPv6"}, false),
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"lists": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"address_family": {
Type: schema.TypeString,
Computed: true,
},
"association_count": {
Type: schema.TypeInt,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"entry": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cidr": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"max_entries": {
Type: schema.TypeInt,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"prefix_list_id": {
Type: schema.TypeString,
Computed: true,
},
"prefix_list_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudEcsPrefixListsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribePrefixLists"
request := make(map[string]interface{})
if v, ok := d.GetOk("address_family"); ok {
request["AddressFamily"] = v
}
if v, ok := d.GetOk("prefix_list_name"); ok {
request["PrefixListName"] = v
}
request["RegionId"] = client.RegionId
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var prefixListNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
prefixListNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ecs_prefix_lists", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.PrefixLists.PrefixList", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.PrefixLists.PrefixList", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if prefixListNameRegex != nil && !prefixListNameRegex.MatchString(fmt.Sprint(item["PrefixListName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["PrefixListId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"address_family": object["AddressFamily"],
"association_count": formatInt(object["AssociationCount"]),
"create_time": object["CreationTime"],
"max_entries": formatInt(object["MaxEntries"]),
"id": fmt.Sprint(object["PrefixListId"]),
"prefix_list_id": fmt.Sprint(object["PrefixListId"]),
"prefix_list_name": object["PrefixListName"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["PrefixListName"])
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["PrefixListId"])
ecsService := EcsService{client}
getResp, err := ecsService.DescribeEcsPrefixList(id)
if err != nil {
return WrapError(err)
}
mapping["description"] = getResp["Description"]
entry := make([]map[string]interface{}, 0)
if entryList, ok := getResp["Entries"].(map[string]interface{})["Entry"].([]interface{}); ok {
for _, v := range entryList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"cidr": m1["Cidr"],
"description": m1["Description"],
}
entry = append(entry, temp1)
}
}
}
mapping["entry"] = entry
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("lists", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEcsSnapshots() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEcsSnapshotsRead,
Schema: map[string]*schema.Schema{
"category": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"flash", "standard"}, false),
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"encrypted": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"kms_key_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"snapshot_link_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"snapshot_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"snapshot_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"auto", "user", "all"}, false),
Default: "all",
},
"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"source_disk_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"System", "Data"}, false),
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"accomplished", "failed", "progressing", "all"}, false),
},
"tags": tagsSchema(),
"usage": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"image", "disk", "image_disk", "none"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"snapshots": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"category": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"disk_id": {
Type: schema.TypeString,
Computed: true,
},
"encrypted": {
Type: schema.TypeBool,
Computed: true,
},
"instant_access": {
Type: schema.TypeBool,
Computed: true,
},
"instant_access_retention_days": {
Type: schema.TypeInt,
Computed: true,
},
"product_code": {
Type: schema.TypeString,
Computed: true,
},
"progress": {
Type: schema.TypeString,
Computed: true,
},
"remain_time": {
Type: schema.TypeInt,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"retention_days": {
Type: schema.TypeInt,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"snapshot_id": {
Type: schema.TypeString,
Computed: true,
},
"snapshot_name": {
Type: schema.TypeString,
Computed: true,
},
"snapshot_sn": {
Type: schema.TypeString,
Computed: true,
},
"snapshot_type": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"source_disk_size": {
Type: schema.TypeString,
Computed: true,
},
"source_disk_type": {
Type: schema.TypeString,
Computed: true,
},
"source_storage_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"usage": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"source_disk_id": {
Type: schema.TypeString,
Computed: true,
},
"creation_time": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEcsSnapshotsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeSnapshots"
request := make(map[string]interface{})
if v, ok := d.GetOk("category"); ok {
request["Category"] = v
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
if v, ok := d.GetOkExists("encrypted"); ok {
request["Encrypted"] = v
}
if v, ok := d.GetOk("kms_key_id"); ok {
request["KMSKeyId"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("snapshot_link_id"); ok {
request["SnapshotLinkId"] = v
}
if v, ok := d.GetOk("snapshot_name"); ok {
request["SnapshotName"] = v
}
if v, ok := d.GetOk("snapshot_type"); ok {
request["SnapshotType"] = v
}
if v, ok := d.GetOk("type"); ok {
request["SnapshotType"] = v
}
if v, ok := d.GetOk("source_disk_type"); ok {
request["SourceDiskType"] = v
}
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
if v, ok := d.GetOk("tags"); ok {
tags := make([]map[string]interface{}, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, map[string]interface{}{
"Key": key,
"Value": value.(string),
})
}
request["Tag"] = tags
}
if v, ok := d.GetOk("usage"); ok {
request["Usage"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var snapshotNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
snapshotNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ecs_snapshots", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Snapshots.Snapshot", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Snapshots.Snapshot", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if snapshotNameRegex != nil {
if !snapshotNameRegex.MatchString(fmt.Sprint(item["SnapshotName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["SnapshotId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"category": object["Category"],
"description": object["Description"],
"disk_id": object["SourceDiskId"],
"encrypted": object["Encrypted"],
"instant_access": object["InstantAccess"],
"instant_access_retention_days": formatInt(object["InstantAccessRetentionDays"]),
"product_code": object["ProductCode"],
"progress": object["Progress"],
"remain_time": formatInt(object["RemainTime"]),
"resource_group_id": object["ResourceGroupId"],
"retention_days": formatInt(object["RetentionDays"]),
"id": fmt.Sprint(object["SnapshotId"]),
"snapshot_id": fmt.Sprint(object["SnapshotId"]),
"snapshot_name": object["SnapshotName"],
"snapshot_sn": object["SnapshotSN"],
"snapshot_type": object["SnapshotType"],
"type": object["SnapshotType"],
"source_disk_size": object["SourceDiskSize"],
"source_disk_type": object["SourceDiskType"],
"source_storage_type": object["SourceStorageType"],
"status": object["Status"],
"usage": object["Usage"],
"source_disk_id": object["SourceDiskId"],
"creation_time": object["CreationTime"],
"name": object["SnapshotName"],
}
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags.Tag", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["TagKey"].(string)
value := t.(map[string]interface{})["TagValue"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
ids = append(ids, fmt.Sprint(object["SnapshotId"]))
names = append(names, object["SnapshotName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("snapshots", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/services/edas"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEdasApplications() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEdasApplicationsRead,
Schema: map[string]*schema.Schema{
"output_file": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"applications": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"app_name": {
Type: schema.TypeString,
Computed: true,
},
"app_id": {
Type: schema.TypeString,
Computed: true,
},
"application_type": {
Type: schema.TypeString,
Computed: true,
},
"build_package_id": {
Type: schema.TypeInt,
Computed: true,
},
"cluster_id": {
Type: schema.TypeString,
Computed: true,
},
"cluster_type": {
Type: schema.TypeInt,
Computed: true,
},
"region_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEdasApplicationsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
request := edas.CreateListApplicationRequest()
request.RegionId = client.RegionId
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, id := range v.([]interface{}) {
if id == nil {
continue
}
idsMap[Trim(id.(string))] = Trim(id.(string))
}
}
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.ListApplication(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_edas_applications", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*edas.ListApplicationResponse)
if response.Code != 200 {
return WrapError(Error(response.Message))
}
var filteredApps []edas.ApplicationInListApplication
nameRegex, ok := d.GetOk("name_regex")
if (ok && nameRegex.(string) != "") || (len(idsMap) > 0) {
var r *regexp.Regexp
if nameRegex != "" {
r, err = regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
}
for _, app := range response.ApplicationList.Application {
if r != nil && !r.MatchString(app.Name) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[app.AppId]; !ok {
continue
}
}
filteredApps = append(filteredApps, app)
}
} else {
filteredApps = response.ApplicationList.Application
}
return edasApplicationAttributes(d, filteredApps)
}
func edasApplicationAttributes(d *schema.ResourceData, apps []edas.ApplicationInListApplication) error {
var appIds []string
var s []map[string]interface{}
var names []string
for _, app := range apps {
mapping := map[string]interface{}{
"app_name": app.Name,
"app_id": app.AppId,
"application_type": app.ApplicationType,
"build_package_id": app.BuildPackageId,
"cluster_id": app.ClusterId,
"cluster_type": app.ClusterType,
"region_id": app.RegionId,
}
appIds = append(appIds, app.AppId)
names = append(names, app.Name)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(appIds))
if err := d.Set("ids", appIds); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("applications", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/services/edas"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEdasClusters() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEdasClustersRead,
Schema: map[string]*schema.Schema{
"logical_region_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"clusters": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cluster_id": {
Type: schema.TypeString,
Computed: true,
},
"cluster_name": {
Type: schema.TypeString,
Computed: true,
},
"cluster_type": {
Type: schema.TypeInt,
Computed: true,
},
"create_time": {
Type: schema.TypeInt,
Computed: true,
},
"update_time": {
Type: schema.TypeInt,
Computed: true,
},
"cpu": {
Type: schema.TypeInt,
Computed: true,
},
"cpu_used": {
Type: schema.TypeInt,
Computed: true,
},
"mem": {
Type: schema.TypeInt,
Computed: true,
},
"mem_used": {
Type: schema.TypeInt,
Computed: true,
},
"network_mode": {
Type: schema.TypeInt,
Computed: true,
},
"node_num": {
Type: schema.TypeInt,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"region_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEdasClustersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
logicalRegionId := d.Get("logical_region_id").(string)
request := edas.CreateListClusterRequest()
request.LogicalRegionId = logicalRegionId
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, id := range v.([]interface{}) {
if id == nil {
continue
}
idsMap[Trim(id.(string))] = Trim(id.(string))
}
}
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.ListCluster(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_edas_clusters", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*edas.ListClusterResponse)
if response.Code != 200 {
return WrapError(Error(response.Message))
}
var filteredClusters []edas.Cluster
nameRegex, ok := d.GetOk("name_regex")
if (ok && nameRegex.(string) != "") || (len(idsMap) > 0) {
var r *regexp.Regexp
if nameRegex != "" {
r, err = regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
}
for _, cluster := range response.ClusterList.Cluster {
if r != nil && !r.MatchString(cluster.ClusterName) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[cluster.ClusterId]; !ok {
continue
}
}
filteredClusters = append(filteredClusters, cluster)
}
} else {
filteredClusters = response.ClusterList.Cluster
}
return edasClusterDescriptionAttributes(d, filteredClusters)
}
func edasClusterDescriptionAttributes(d *schema.ResourceData, clusters []edas.Cluster) error {
var ids []string
var names []string
var s []map[string]interface{}
for _, cluster := range clusters {
mapping := map[string]interface{}{
"cluster_id": cluster.ClusterId,
"cluster_name": cluster.ClusterName,
"cluster_type": cluster.ClusterType,
"create_time": cluster.CreateTime,
"update_time": cluster.UpdateTime,
"cpu": cluster.Cpu,
"cpu_used": cluster.CpuUsed,
"mem": cluster.Mem,
"mem_used": cluster.MemUsed,
"network_mode": cluster.NetworkMode,
"node_num": cluster.NodeNum,
"vpc_id": cluster.VpcId,
"region_id": cluster.RegionId,
}
ids = append(ids, cluster.ClusterId)
s = append(s, mapping)
names = append(names, cluster.ClusterName)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("clusters", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/services/edas"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEdasDeployGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEdasDeployGroupsRead,
Schema: map[string]*schema.Schema{
"app_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"group_id": {
Type: schema.TypeString,
Computed: true,
},
"group_name": {
Type: schema.TypeString,
Computed: true,
},
"group_type": {
Type: schema.TypeInt,
Computed: true,
},
"create_time": {
Type: schema.TypeInt,
Computed: true,
},
"update_time": {
Type: schema.TypeInt,
Computed: true,
},
"app_id": {
Type: schema.TypeString,
Computed: true,
},
"cluster_id": {
Type: schema.TypeString,
Computed: true,
},
"package_version_id": {
Type: schema.TypeString,
Computed: true,
},
"app_version_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEdasDeployGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
regionId := client.RegionId
appId := d.Get("app_id").(string)
request := edas.CreateListDeployGroupRequest()
request.RegionId = regionId
request.AppId = appId
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.ListDeployGroup(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_edas_deploy_groups", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*edas.ListDeployGroupResponse)
if response.Code != 200 {
return WrapError(Error(response.Message))
}
var filteredGroups []edas.DeployGroup
nameRegex, ok := d.GetOk("name_regex")
if ok && nameRegex.(string) != "" {
var r *regexp.Regexp
if nameRegex != "" {
r, err = regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
}
for _, group := range response.DeployGroupList.DeployGroup {
if r != nil && !r.MatchString(group.GroupName) {
continue
}
filteredGroups = append(filteredGroups, group)
}
} else {
filteredGroups = response.DeployGroupList.DeployGroup
}
return edasDeployGroupAttributes(d, filteredGroups)
}
func edasDeployGroupAttributes(d *schema.ResourceData, groups []edas.DeployGroup) error {
var ids []string
var s []map[string]interface{}
var names []string
for _, group := range groups {
mapping := map[string]interface{}{
"group_id": group.GroupId,
"group_name": group.GroupName,
"group_type": group.GroupType,
"create_time": group.CreateTime,
"update_time": group.UpdateTime,
"app_id": group.AppId,
"cluster_id": group.ClusterId,
"package_version_id": group.PackageVersionId,
"app_version_id": group.AppVersionId,
}
ids = append(ids, group.GroupId)
s = append(s, mapping)
names = append(names, group.GroupName)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"fmt"
"log"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEdasService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEdasServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudEdasServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("EdasServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateInstance"
request := map[string]interface{}{
"ProductCode": "edas",
"SubscriptionType": "PayAsYouGo",
"ProductType": "edaspostpay",
"Parameter.1.Code": "env",
"Parameter.1.Value": "env_public",
}
conn, err := client.NewBssopenapiClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-14"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"NotApplicable"}) {
conn.Endpoint = String(connectivity.BssOpenAPIEndpointInternational)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, nil)
if err != nil {
if IsExpectedErrors(err, []string{"SYSTEM.SALE_VALIDATE_NO_SPECIFIC_CODE_FAILED"}) {
d.SetId("EdasServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_edas_service", "CreateInstance", AlibabaCloudSdkGoERROR)
}
if response["Success"] != nil && !response["Success"].(bool) {
if response["Code"] != nil && response["Code"].(string) == "SYSTEM.SALE_VALIDATE_NO_SPECIFIC_CODE_FAILED" {
d.SetId("EdasServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(fmt.Errorf("%s", response), DataDefaultErrorMsg, "alicloud_edas_service", "CreateInstance", AlibabaCloudSdkGoERROR)
}
if response["Data"] != nil {
d.SetId(fmt.Sprintf("%v", response["Data"].(map[string]interface{})["OrderId"]))
} else {
log.Printf("[ERROR] When opening EDAS service, invoking CreateInstance got an nil data. Response: %s.", response)
d.SetId("EdasServiceHasBeenOpened")
}
d.Set("status", "Opened")
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudEhpcJobTemplates() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEhpcJobTemplatesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"templates": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"array_request": {
Type: schema.TypeString,
Computed: true,
},
"clock_time": {
Type: schema.TypeString,
Computed: true,
},
"command_line": {
Type: schema.TypeString,
Computed: true,
},
"gpu": {
Type: schema.TypeInt,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"job_template_id": {
Type: schema.TypeString,
Computed: true,
},
"job_template_name": {
Type: schema.TypeString,
Computed: true,
},
"mem": {
Type: schema.TypeString,
Computed: true,
},
"node": {
Type: schema.TypeInt,
Computed: true,
},
"package_path": {
Type: schema.TypeString,
Computed: true,
},
"priority": {
Type: schema.TypeInt,
Computed: true,
},
"queue": {
Type: schema.TypeString,
Computed: true,
},
"re_runable": {
Type: schema.TypeBool,
Computed: true,
},
"runas_user": {
Type: schema.TypeString,
Computed: true,
},
"stderr_redirect_path": {
Type: schema.TypeString,
Computed: true,
},
"stdout_redirect_path": {
Type: schema.TypeString,
Computed: true,
},
"task": {
Type: schema.TypeInt,
Computed: true,
},
"thread": {
Type: schema.TypeInt,
Computed: true,
},
"variables": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEhpcJobTemplatesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListJobTemplates"
request := make(map[string]interface{})
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewEhpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2018-04-12"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ehpc_job_templates", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Templates.JobTemplates", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Templates.JobTemplates", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Id"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"array_request": object["ArrayRequest"],
"clock_time": object["ClockTime"],
"command_line": object["CommandLine"],
"gpu": formatInt(object["Gpu"]),
"id": fmt.Sprint(object["Id"]),
"job_template_id": fmt.Sprint(object["Id"]),
"job_template_name": object["Name"],
"mem": object["Mem"],
"node": formatInt(object["Node"]),
"package_path": object["PackagePath"],
"priority": formatInt(object["Priority"]),
"queue": object["Queue"],
"re_runable": object["ReRunable"],
"runas_user": object["RunasUser"],
"stderr_redirect_path": object["StderrRedirectPath"],
"stdout_redirect_path": object["StdoutRedirectPath"],
"task": formatInt(object["Task"]),
"thread": formatInt(object["Thread"]),
"variables": object["Variables"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("templates", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEipAddresses() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEipAddressesRead,
Schema: map[string]*schema.Schema{
"ip_addresses": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
ForceNew: true,
MinItems: 1,
Deprecated: "Field 'ip_addresses' has been deprecated from provider version 1.126.0 and it will be removed in the future version. Please use the new attribute 'ip_address' instead.",
},
"in_use": {
Type: schema.TypeBool,
Optional: true,
Removed: "Field 'in_use' has been removed from provider version 1.126.0.",
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"address_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"associated_instance_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"associated_instance_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"include_reservation_data": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"ip_address": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"isp": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"BGP", "BGP_PRO"}, false),
},
"lock_reason": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"payment_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo", "Subscription"}, false),
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"segment_instance_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Associating", "Available", "InUse", "Unassociating"}, false),
},
"tags": tagsSchema(),
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"addresses": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"address_name": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"allocation_id": {
Type: schema.TypeString,
Computed: true,
},
"available_regions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"bandwidth": {
Type: schema.TypeString,
Computed: true,
},
"bandwidth_package_bandwidth": {
Type: schema.TypeString,
Computed: true,
},
"bandwidth_package_id": {
Type: schema.TypeString,
Computed: true,
},
"bandwidth_package_type": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"deletion_protection": {
Type: schema.TypeBool,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"expired_time": {
Type: schema.TypeString,
Computed: true,
},
"has_reservation_data": {
Type: schema.TypeString,
Computed: true,
},
"hd_monitor_status": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_region_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_type": {
Type: schema.TypeString,
Computed: true,
},
"internet_charge_type": {
Type: schema.TypeString,
Computed: true,
},
"ip_address": {
Type: schema.TypeString,
Computed: true,
},
"isp": {
Type: schema.TypeString,
Computed: true,
},
"operation_locks": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"reservation_active_time": {
Type: schema.TypeString,
Computed: true,
},
"reservation_bandwidth": {
Type: schema.TypeString,
Computed: true,
},
"reservation_internet_charge_type": {
Type: schema.TypeString,
Computed: true,
},
"reservation_order_type": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"second_limited": {
Type: schema.TypeBool,
Computed: true,
},
"segment_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
},
},
},
"eips": {
Type: schema.TypeList,
Computed: true,
Deprecated: "Field 'eips' has been deprecated from provider version 1.126.0 and it will be removed in the future version. Please use the new attribute 'addresses' instead.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"ip_address": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_type": {
Type: schema.TypeString,
Computed: true,
},
"bandwidth": {
Type: schema.TypeString,
Computed: true,
},
"internet_charge_type": {
Type: schema.TypeString,
Computed: true,
},
"creation_time": {
Type: schema.TypeString,
Computed: true,
},
"deletion_protection": {
Type: schema.TypeBool,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
},
}
}
func dataSourceAlicloudEipAddressesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeEipAddresses"
request := make(map[string]interface{})
if v, ok := d.GetOk("address_name"); ok {
request["EipName"] = v
}
if v, ok := d.GetOk("associated_instance_id"); ok {
request["AssociatedInstanceId"] = v
}
if v, ok := d.GetOk("associated_instance_type"); ok {
request["AssociatedInstanceType"] = v
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
if v, ok := d.GetOkExists("include_reservation_data"); ok {
request["IncludeReservationData"] = v
}
if v, ok := d.GetOk("ip_address"); ok {
request["EipAddress"] = v
}
if v, ok := d.GetOk("isp"); ok {
request["ISP"] = v
}
if v, ok := d.GetOk("lock_reason"); ok {
request["LockReason"] = v
}
if v, ok := d.GetOk("payment_type"); ok {
request["ChargeType"] = convertEipAddressPaymentTypeRequest(v)
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("segment_instance_id"); ok {
request["SegmentInstanceId"] = v
}
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var addressNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
addressNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
ipsMap := make(map[string]string)
if v, ok := d.GetOk("ip_addresses"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
tagsMap := make(map[string]interface{})
if v, ok := d.GetOk("tags"); ok && len(v.(map[string]interface{})) > 0 {
tagsMap = v.(map[string]interface{})
}
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_eip_addresses", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.EipAddresses.EipAddress", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.EipAddresses.EipAddress", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if addressNameRegex != nil {
if !addressNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["AllocationId"])]; !ok {
continue
}
}
if len(ipsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["IpAddress"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
eips := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"address_name": object["Name"],
"id": fmt.Sprint(object["AllocationId"]),
"allocation_id": fmt.Sprint(object["AllocationId"]),
"available_regions": object["AvailableRegions"].(map[string]interface{})["AvailableRegion"],
"bandwidth": object["Bandwidth"],
"bandwidth_package_bandwidth": object["BandwidthPackageBandwidth"],
"bandwidth_package_id": object["BandwidthPackageId"],
"bandwidth_package_type": object["BandwidthPackageType"],
"create_time": object["AllocationTime"],
"deletion_protection": object["DeletionProtection"],
"description": object["Descritpion"],
"expired_time": object["ExpiredTime"],
"has_reservation_data": fmt.Sprint(object["HasReservationData"]),
"hd_monitor_status": object["HDMonitorStatus"],
"instance_id": object["InstanceId"],
"instance_region_id": object["InstanceRegionId"],
"instance_type": object["InstanceType"],
"internet_charge_type": object["InternetChargeType"],
"ip_address": object["IpAddress"],
"isp": object["ISP"],
"payment_type": convertEipAddressPaymentTypeResponse(object["ChargeType"]),
"reservation_active_time": object["ReservationActiveTime"],
"reservation_bandwidth": object["ReservationBandwidth"],
"reservation_internet_charge_type": object["ReservationInternetChargeType"],
"reservation_order_type": object["ReservationOrderType"],
"resource_group_id": object["ResourceGroupId"],
"second_limited": object["SecondLimited"],
"segment_instance_id": object["SegmentInstanceId"],
"status": object["Status"],
}
eipMapping := map[string]interface{}{
"id": object["AllocationId"],
"status": object["Status"],
"ip_address": object["IpAddress"],
"bandwidth": object["Bandwidth"],
"instance_id": object["InstanceId"],
"instance_type": object["InstanceType"],
"internet_charge_type": object["InternetChargeType"],
"creation_time": object["AllocationTime"],
"deletion_protection": object["DeletionProtection"],
}
if v := object["OperationLocks"].(map[string]interface{})["LockReason"].([]interface{}); len(v) > 0 {
mapping["operation_locks"] = v[0].(map[string]interface{})["LockReason"]
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["AllocationId"]))
names = append(names, object["Name"])
s = append(s, mapping)
eips = append(eips, eipMapping)
continue
}
vpcService := VpcService{client}
id := fmt.Sprint(object["AllocationId"])
getResp, err := vpcService.ListTagResources(id, "EIP")
if err != nil {
return WrapError(err)
}
mapping["tags"] = tagsToMap(getResp)
march := false
for tagKey, tagValue := range tagsToMap(getResp) {
if v, ok := tagsMap[tagKey]; ok && v == tagValue {
march = true
break
}
}
if !march && len(tagsMap) > 0 {
continue
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
eips = append(eips, eipMapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("addresses", s); err != nil {
return WrapError(err)
}
if err := d.Set("eips", eips); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEipanycastAnycastEipAddresses() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEipanycastAnycastEipAddressesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"anycast_eip_address_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"bind_instance_ids": {
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"business_status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"internet_charge_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "PayByTraffic",
},
"ip_address": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"payment_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo"}, false),
Default: "PayAsYouGo",
},
"service_location": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Allocated", "Associated", "Associating", "Unassociating"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"addresses": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ali_uid": {
Type: schema.TypeInt,
Computed: true,
},
"anycast_eip_address_name": {
Type: schema.TypeString,
Computed: true,
},
"anycast_eip_bind_info_list": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"bind_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"bind_instance_region_id": {
Type: schema.TypeString,
Computed: true,
},
"bind_instance_type": {
Type: schema.TypeString,
Computed: true,
},
"bind_time": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"anycast_id": {
Type: schema.TypeString,
Computed: true,
},
"bandwidth": {
Type: schema.TypeInt,
Computed: true,
},
"bid": {
Type: schema.TypeString,
Computed: true,
},
"business_status": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"internet_charge_type": {
Type: schema.TypeString,
Computed: true,
},
"ip_address": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"service_location": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEipanycastAnycastEipAddressesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListAnycastEipAddresses"
request := make(map[string]interface{})
if v, ok := d.GetOk("anycast_eip_address_name"); ok {
request["Name"] = v
}
if v, ok := d.GetOk("bind_instance_ids"); ok {
request["BindInstanceIds"] = convertListToJsonString(v.(*schema.Set).List())
}
if v, ok := d.GetOk("business_status"); ok {
request["BusinessStatus"] = v
}
if v, ok := d.GetOk("internet_charge_type"); ok {
request["InternetChargeType"] = v
}
if v, ok := d.GetOk("ip_address"); ok {
request["AnycastEipAddress"] = v
}
if v, ok := d.GetOk("payment_type"); ok {
request["InstanceChargeType"] = convertEipanycastAnycastEipAddressPaymentTypeRequest(v.(string))
}
if v, ok := d.GetOk("service_location"); ok {
request["ServiceLocation"] = v
}
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var anycastEipAddressNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
anycastEipAddressNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewEipanycastClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_eipanycast_anycast_eip_addresses", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.AnycastList", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.AnycastList", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if anycastEipAddressNameRegex != nil {
if !anycastEipAddressNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["AnycastId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"ali_uid": object["AliUid"],
"anycast_eip_address_name": object["Name"],
"id": fmt.Sprint(object["AnycastId"]),
"anycast_id": fmt.Sprint(object["AnycastId"]),
"bandwidth": formatInt(object["Bandwidth"]),
"bid": object["Bid"],
"business_status": object["BusinessStatus"],
"description": object["Description"],
"internet_charge_type": object["InternetChargeType"],
"ip_address": object["IpAddress"],
"payment_type": convertEipanycastAnycastEipAddressPaymentTypeResponse(object["InstanceChargeType"].(string)),
"service_location": object["ServiceLocation"],
"status": object["Status"],
}
anycastEipBindInfoList := make([]map[string]interface{}, 0)
if anycastEipBindInfoListList, ok := object["AnycastEipBindInfoList"].([]interface{}); ok {
for _, v := range anycastEipBindInfoListList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"bind_instance_id": m1["BindInstanceId"],
"bind_instance_region_id": m1["BindInstanceRegionId"],
"bind_instance_type": m1["BindInstanceType"],
"bind_time": m1["BindTime"],
}
anycastEipBindInfoList = append(anycastEipBindInfoList, temp1)
}
}
}
mapping["anycast_eip_bind_info_list"] = anycastEipBindInfoList
ids = append(ids, fmt.Sprint(object["AnycastId"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("addresses", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"encoding/json"
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/elasticsearch"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudElasticsearch() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudElasticsearchRead,
Schema: map[string]*schema.Schema{
"description_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"version": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{
"5.5.3_with_X-Pack",
"6.3.2_with_X-Pack",
"6.7.0_with_X-Pack",
}, false),
},
"tags": tagsSchema(),
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"descriptions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"instance_charge_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"data_node_amount": {
Type: schema.TypeInt,
Computed: true,
},
"data_node_spec": {
Type: schema.TypeString,
Computed: true,
},
"data_node_disk_size": {
Type: schema.TypeInt,
Computed: true,
},
"data_node_disk_type": {
Type: schema.TypeString,
Computed: true,
},
"version": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"created_at": {
Type: schema.TypeString,
Computed: true,
},
"updated_at": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudElasticsearchRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := elasticsearch.CreateListInstanceRequest()
request.RegionId = client.RegionId
request.EsVersion = d.Get("version").(string)
request.Size = requests.NewInteger(PageSizeLarge)
request.Page = requests.NewInteger(1)
if v, ok := d.GetOk("tags"); ok {
var reqTags []map[string]string
for k, v := range v.(map[string]interface{}) {
reqTags = append(reqTags, map[string]string{
"tagKey": k,
"tagValue": v.(string),
})
}
reqTagsStr, err := json.Marshal(reqTags)
if err != nil {
return WrapError(err)
}
request.Tags = string(reqTagsStr)
}
var instances []elasticsearch.Instance
for {
raw, err := client.WithElasticsearchClient(func(elasticsearchClient *elasticsearch.Client) (interface{}, error) {
return elasticsearchClient.ListInstance(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_elasticsearch_instances", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*elasticsearch.ListInstanceResponse)
if len(response.Result) < 1 {
break
}
for _, item := range response.Result {
instances = append(instances, item)
}
if len(response.Result) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.Page)
if err != nil {
return WrapError(err)
}
request.Page = page
}
var filteredInstances []elasticsearch.Instance
var descriptionRegex *regexp.Regexp
if v, ok := d.GetOk("description_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
descriptionRegex = r
}
// ids
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
for _, instance := range instances {
if descriptionRegex != nil && !descriptionRegex.MatchString(instance.Description) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[instance.InstanceId]; !ok {
continue
}
}
filteredInstances = append(filteredInstances, instance)
}
return WrapError(extractInstance(d, filteredInstances))
}
func extractInstance(d *schema.ResourceData, instances []elasticsearch.Instance) error {
var ids []string
var descriptions []string
var s []map[string]interface{}
for _, item := range instances {
mapping := map[string]interface{}{
"id": item.InstanceId,
"description": item.Description,
"instance_charge_type": getChargeType(item.PaymentType),
"data_node_amount": item.NodeAmount,
"data_node_spec": item.NodeSpec.Spec,
"data_node_disk_size": item.NodeSpec.Disk,
"data_node_disk_type": item.NodeSpec.DiskType,
"status": item.Status,
"version": item.EsVersion,
"created_at": item.CreatedAt,
"updated_at": item.UpdatedAt,
"vswitch_id": item.NetworkConfig.VswitchId,
"tags": elasticsearchTagsToMap(item.Tags),
}
ids = append(ids, item.InstanceId)
descriptions = append(descriptions, item.Description)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("descriptions", descriptions); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"sort"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/services/elasticsearch"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudElaticsearchZones() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudElaticsearchZonesRead,
Schema: map[string]*schema.Schema{
"multi": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"zones": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"multi_zone_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
},
}
}
func dataSourceAlicloudElaticsearchZonesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
multi := d.Get("multi").(bool)
var zoneIds []string
request := elasticsearch.CreateGetRegionConfigurationRequest()
request.RegionId = client.RegionId
raw, err := client.WithElasticsearchClient(func(elasticsearchClient *elasticsearch.Client) (interface{}, error) {
return elasticsearchClient.GetRegionConfiguration(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_elasticsearch_zones", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.GetActionName(), request)
zones, _ := raw.(*elasticsearch.GetRegionConfigurationResponse)
for _, zoneID := range zones.Result.Zones {
if multi && strings.Contains(zoneID, MULTI_IZ_SYMBOL) {
zoneIds = append(zoneIds, zoneID)
continue
}
if !multi && !strings.Contains(zoneID, MULTI_IZ_SYMBOL) {
zoneIds = append(zoneIds, zoneID)
continue
}
}
if len(zoneIds) > 0 {
sort.Strings(zoneIds)
}
var s []map[string]interface{}
if !multi {
for _, zoneId := range zoneIds {
mapping := map[string]interface{}{"id": zoneId}
s = append(s, mapping)
}
} else {
for _, zoneId := range zoneIds {
mapping := map[string]interface{}{
"id": zoneId,
"multi_zone_ids": splitMultiZoneId(zoneId),
}
s = append(s, mapping)
}
}
d.SetId(dataResourceIdHash(zoneIds))
if err := d.Set("zones", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", zoneIds); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEmrClusters() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEmrClustersRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"cluster_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"cluster_type_list": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"create_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"MANUAL", "ON-DEMAND"}, false),
},
"default_status": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"deposit_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"HALF_MANAGED", "MANAGED"}, false),
},
"is_desc": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"machine_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "ECS",
ValidateFunc: validation.StringInSlice([]string{"DOCKER", "ECS", "ECS_FROM_ECM_HOSTPOOL", "PYHSICAL_MACHINE"}, false),
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status_list": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"ABNORMAL", "CREATE_FAILED", "CREATING", "IDLE", "RELEASED", "RELEASE_FAILED", "RELEASING", "RUNNING", "WAIT_FOR_PAY"}, false),
},
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"page_number": {
Type: schema.TypeInt,
Optional: true,
},
"page_size": {
Type: schema.TypeInt,
Optional: true,
Default: 50,
},
"clusters": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"access_info": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"zk_links": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"link": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
"auto_scaling_allowed": {
Type: schema.TypeBool,
Computed: true,
},
"auto_scaling_by_load_allowed": {
Type: schema.TypeBool,
Computed: true,
},
"auto_scaling_enable": {
Type: schema.TypeBool,
Computed: true,
},
"auto_scaling_spot_with_limit_allowed": {
Type: schema.TypeBool,
Computed: true,
},
"bootstrap_action_list": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"arg": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"path": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"bootstrap_failed": {
Type: schema.TypeBool,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"cluster_id": {
Type: schema.TypeString,
Computed: true,
},
"cluster_name": {
Type: schema.TypeString,
Computed: true,
},
"create_resource": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"create_type": {
Type: schema.TypeString,
Computed: true,
},
"deposit_type": {
Type: schema.TypeString,
Computed: true,
},
"eas_enable": {
Type: schema.TypeBool,
Computed: true,
},
"expired_time": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"has_uncompleted_order": {
Type: schema.TypeBool,
Computed: true,
},
"extra_info": {
Type: schema.TypeString,
Computed: true,
},
"high_availability_enable": {
Type: schema.TypeBool,
Computed: true,
},
"host_group_list": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"band_width": {
Type: schema.TypeString,
Computed: true,
},
"charge_type": {
Type: schema.TypeString,
Computed: true,
},
"cpu_core": {
Type: schema.TypeInt,
Computed: true,
},
"disk_capacity": {
Type: schema.TypeInt,
Computed: true,
},
"disk_count": {
Type: schema.TypeInt,
Computed: true,
},
"disk_type": {
Type: schema.TypeString,
Computed: true,
},
"host_group_change_type": {
Type: schema.TypeString,
Computed: true,
},
"host_group_id": {
Type: schema.TypeString,
Computed: true,
},
"host_group_name": {
Type: schema.TypeString,
Computed: true,
},
"host_group_type": {
Type: schema.TypeString,
Computed: true,
},
"instance_type": {
Type: schema.TypeString,
Computed: true,
},
"memory_capacity": {
Type: schema.TypeInt,
Computed: true,
},
"node_count": {
Type: schema.TypeInt,
Computed: true,
},
"nodes": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"disk_infos": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"device": {
Type: schema.TypeString,
Computed: true,
},
"disk_id": {
Type: schema.TypeString,
Computed: true,
},
"disk_name": {
Type: schema.TypeString,
Computed: true,
},
"size": {
Type: schema.TypeInt,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"emr_expired_time": {
Type: schema.TypeString,
Computed: true,
},
"expired_time": {
Type: schema.TypeString,
Computed: true,
},
"inner_ip": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"pub_ip": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"support_ipv6": {
Type: schema.TypeBool,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"period": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"host_pool_info": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"hp_biz_id": {
Type: schema.TypeString,
Computed: true,
},
"hp_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"image_id": {
Type: schema.TypeString,
Computed: true,
},
"local_meta_db": {
Type: schema.TypeBool,
Computed: true,
},
"machine_type": {
Type: schema.TypeString,
Computed: true,
},
"meta_store_type": {
Type: schema.TypeString,
Computed: true,
},
"net_type": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"period": {
Type: schema.TypeInt,
Computed: true,
},
"relate_cluster_info": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cluster_id": {
Type: schema.TypeString,
Computed: true,
},
"cluster_name": {
Type: schema.TypeString,
Computed: true,
},
"cluster_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"resize_disk_enable": {
Type: schema.TypeBool,
Computed: true,
},
"running_time": {
Type: schema.TypeInt,
Computed: true,
},
"security_group_id": {
Type: schema.TypeString,
Computed: true,
},
"security_group_name": {
Type: schema.TypeString,
Computed: true,
},
"software_info": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cluster_type": {
Type: schema.TypeString,
Computed: true,
},
"emr_ver": {
Type: schema.TypeString,
Computed: true,
},
"softwares": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"display_name": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"only_display": {
Type: schema.TypeBool,
Computed: true,
},
"start_tpe": {
Type: schema.TypeInt,
Computed: true,
},
"version": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
"start_time": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"stop_time": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"user_defined_emr_ecs_role": {
Type: schema.TypeString,
Computed: true,
},
"user_id": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"total_count": {
Type: schema.TypeInt,
Computed: true,
},
},
}
}
func dataSourceAlicloudEmrClustersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListClusters"
request := make(map[string]interface{})
if v, ok := d.GetOk("cluster_name"); ok {
request["Name"] = v
}
if v, ok := d.GetOk("cluster_type_list"); ok {
request["ClusterTypeList"] = v
}
if v, ok := d.GetOk("create_type"); ok {
request["CreateType"] = v
}
if v, ok := d.GetOkExists("default_status"); ok {
request["DefaultStatus"] = v
}
if v, ok := d.GetOk("deposit_type"); ok {
request["DepositType"] = v
}
if v, ok := d.GetOkExists("is_desc"); ok {
request["IsDesc"] = v
}
if v, ok := d.GetOk("machine_type"); ok {
request["MachineType"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("status_list"); ok {
request["StatusList"] = v
}
if v, ok := d.GetOk("vpc_id"); ok {
request["VpcId"] = v
}
if v, ok := d.GetOk("page_number"); ok && v.(int) > 0 {
request["PageNumber"] = v.(int)
} else {
request["PageNumber"] = 1
}
if v, ok := d.GetOk("page_size"); ok && v.(int) > 0 {
request["PageSize"] = v.(int)
} else {
request["PageSize"] = PageSizeLarge
}
var clusterNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
clusterNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewEmrClient()
if err != nil {
return WrapError(err)
}
var objects []interface{}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_emr_clusters", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Clusters.ClusterInfo", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Clusters.ClusterInfo", response)
}
result, _ := resp.([]interface{})
if isPagingRequest(d) {
objects = result
break
}
for _, v := range result {
item := v.(map[string]interface{})
if clusterNameRegex != nil && !clusterNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Id"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, v := range objects {
object := v.(map[string]interface{})
mapping := map[string]interface{}{
"id": fmt.Sprint(object["Id"]),
"cluster_id": fmt.Sprint(object["Id"]),
"cluster_name": object["Name"],
"create_resource": object["CreateResource"],
"create_time": fmt.Sprint(object["CreateTime"]),
"deposit_type": object["DepositType"],
"expired_time": fmt.Sprint(object["ExpiredTime"]),
"machine_type": object["MachineType"],
"meta_store_type": object["MetaStoreType"],
"payment_type": object["ChargeType"],
"period": formatInt(object["Period"]),
"running_time": formatInt(object["RunningTime"]),
"status": object["Status"],
"type": object["Type"],
"has_uncompleted_order": object["HasUncompletedOrder"],
}
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags.Tag", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["TagKey"].(string)
value := t.(map[string]interface{})["TagValue"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["Id"])
emrService := EmrService{client}
getResp, err := emrService.DescribeClusterBasicInfo(id)
if err != nil {
return WrapError(err)
}
mapping["auto_scaling_allowed"] = getResp["AutoScalingAllowed"]
mapping["auto_scaling_by_load_allowed"] = getResp["AutoScalingByLoadAllowed"]
mapping["auto_scaling_spot_with_limit_allowed"] = getResp["AutoScalingSpotWithLimitAllowed"]
bootstrapAction := make([]map[string]interface{}, 0)
if bootstrapActionList, ok := getResp["BootstrapActionList"].(map[string]interface{})["BootstrapAction"].([]interface{}); ok {
for _, v := range bootstrapActionList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"arg": m1["Arg"],
"name": m1["Name"],
"path": m1["Path"],
}
bootstrapAction = append(bootstrapAction, temp1)
}
}
}
mapping["bootstrap_action_list"] = bootstrapAction
softwareInfo := make([]map[string]interface{}, 0)
if softwareInfoList, ok := getResp["SoftwareInfo"].(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"emr_ver": softwareInfoList["EmrVer"],
"cluster_type": softwareInfoList["ClusterType"],
}
if softwareInfoList["Softwares"] != nil {
softwareMaps := make([]map[string]interface{}, 0)
for _, softwareValue := range softwareInfoList["Softwares"].(map[string]interface{})["Software"].([]interface{}) {
software := softwareValue.(map[string]interface{})
softwareMap := map[string]interface{}{
"start_tpe": software["StartTpe"],
"version": software["Version"],
"display_name": software["DisplayName"],
"only_display": software["OnlyDisplay"],
"name": software["Name"],
}
softwareMaps = append(softwareMaps, softwareMap)
}
temp1["softwares"] = softwareMaps
}
softwareInfo = append(softwareInfo, temp1)
}
mapping["software_info"] = softwareInfo
hostPoolInfo := make([]map[string]interface{}, 0)
if hostPoolInfoList, ok := getResp["HostPoolInfo"].(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"hp_biz_id": hostPoolInfoList["HpBizId"],
"hp_name": hostPoolInfoList["HpName"],
}
hostPoolInfo = append(hostPoolInfo, temp1)
}
mapping["host_pool_info"] = hostPoolInfo
relateClusterInfo := make([]map[string]interface{}, 0)
if relateClusterInfoList, ok := getResp["RelateClusterInfo"].(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"cluster_id": relateClusterInfoList["ClusterId"],
"cluster_name": relateClusterInfoList["ClusterName"],
"cluster_type": relateClusterInfoList["ClusterType"],
"status": relateClusterInfoList["Status"],
}
relateClusterInfo = append(relateClusterInfo, temp1)
}
mapping["relate_cluster_info"] = relateClusterInfo
mapping["bootstrap_failed"] = getResp["BootstrapFailed"]
mapping["create_type"] = getResp["CreateType"]
mapping["eas_enable"] = getResp["EasEnable"]
mapping["extra_info"] = getResp["ExtraInfo"]
mapping["image_id"] = getResp["ImageId"]
mapping["local_meta_db"] = getResp["LocalMetaDb"]
mapping["net_type"] = getResp["NetType"]
mapping["security_group_id"] = getResp["SecurityGroupId"]
mapping["security_group_name"] = getResp["SecurityGroupName"]
mapping["start_time"] = getResp["StartTime"]
mapping["stop_time"] = getResp["StopTime"]
mapping["user_defined_emr_ecs_role"] = getResp["UserDefinedEmrEcsRole"]
mapping["user_id"] = getResp["UserId"]
mapping["vswitch_id"] = getResp["VSwitchId"]
mapping["vpc_id"] = getResp["VpcId"]
mapping["zone_id"] = getResp["ZoneId"]
emrService = EmrService{client}
getResp1, err := emrService.DataSourceDescribeEmrCluster(id)
if err != nil {
return WrapError(err)
}
mapping["access_info"] = getResp1["AccessInfo"]
accessInfos := make([]map[string]interface{}, 0)
if accessInfosList, ok := getResp1["AccessInfo"].([]interface{}); ok {
for _, v := range accessInfosList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{}
if m1["ZKLinks"] != nil {
accessInfosMaps := make([]map[string]interface{}, 0)
for _, accessInfosValue := range m1["ZKLinks"].([]interface{}) {
accessInfo := accessInfosValue.(map[string]interface{})
accessInfosMap := map[string]interface{}{
"link": accessInfo["Link"],
"port": accessInfo["Port"],
}
accessInfosMaps = append(accessInfosMaps, accessInfosMap)
}
temp1["zk_links"] = accessInfosMaps
}
accessInfos = append(accessInfos, temp1)
}
}
}
mapping["access_info"] = accessInfos
mapping["auto_scaling_enable"] = getResp1["AutoScalingEnable"]
mapping["high_availability_enable"] = getResp1["HighAvailabilityEnable"]
hostGroup := make([]map[string]interface{}, 0)
if hostGroupList, ok := getResp1["HostGroupList"].(map[string]interface{})["HostGroup"].([]interface{}); ok {
for _, v := range hostGroupList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"band_width": m1["BandWidth"],
"charge_type": m1["ChargeType"],
"cpu_core": formatInt(m1["CpuCore"]),
"disk_capacity": formatInt(m1["DiskCapacity"]),
"disk_count": formatInt(m1["DiskCount"]),
"disk_type": m1["DiskType"],
"host_group_change_type": m1["HostGroupChangeType"],
"host_group_id": m1["HostGroupId"],
"host_group_name": m1["HostGroupName"],
"host_group_type": m1["HostGroupType"],
"instance_type": m1["InstanceType"],
"memory_capacity": formatInt(m1["MemoryCapacity"]),
"node_count": formatInt(m1["NodeCount"]),
"period": m1["Period"],
}
if m1["Nodes"] != nil {
nodesMaps := make([]map[string]interface{}, 0)
for _, nodesValue := range m1["Nodes"].(map[string]interface{})["Node"].([]interface{}) {
nodes := nodesValue.(map[string]interface{})
nodesMap := map[string]interface{}{
"create_time": nodes["CreateTime"],
"status": nodes["Status"],
"emr_expired_time": nodes["EmrExpiredTime"],
"support_ipv6": nodes["SupportIpV6"],
"zone_id": nodes["ZoneId"],
"inner_ip": nodes["InnerIp"],
"instance_id": nodes["InstanceId"],
"expired_time": nodes["ExpiredTime"],
"pub_ip": nodes["PubIp"],
}
if nodes["DiskInfos"] != nil {
deskInfoMaps := make([]map[string]interface{}, 0)
for _, diskInfosValue := range nodes["DiskInfos"].(map[string]interface{})["DiskInfo"].([]interface{}) {
disks := diskInfosValue.(map[string]interface{})
disksMap := map[string]interface{}{
"device": disks["Device"],
"disk_id": disks["DiskId"],
"disk_name": disks["DiskName"],
"size": disks["Size"],
"type": disks["Type"],
}
deskInfoMaps = append(deskInfoMaps, disksMap)
}
nodesMap["disk_infos"] = deskInfoMaps
}
nodesMaps = append(nodesMaps, nodesMap)
}
temp1["nodes"] = nodesMaps
}
hostGroup = append(hostGroup, temp1)
}
}
}
mapping["host_group_list"] = hostGroup
mapping["resize_disk_enable"] = getResp1["ResizeDiskEnable"]
emrService = EmrService{client}
getResp2, err := emrService.ListTagResources(id, "cluster")
if err != nil {
return WrapError(err)
}
mapping["tags"] = tagsToMap(getResp2)
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("clusters", s); err != nil {
return WrapError(err)
}
if err := d.Set("total_count", formatInt(response["TotalCount"])); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/services/emr"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEmrDiskTypes() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEmrDiskTypesRead,
Schema: map[string]*schema.Schema{
"destination_resource": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
"Zone",
"Network",
"InstanceType",
"SystemDisk",
"DataDisk",
}, false),
},
"cluster_type": {
Type: schema.TypeString,
Required: true,
},
"instance_charge_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
"PostPaid",
"PrePaid",
}, false),
},
"instance_type": {
Type: schema.TypeString,
Required: true,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"types": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"value": {
Type: schema.TypeString,
Computed: true,
},
"min": {
Type: schema.TypeInt,
Computed: true,
},
"max": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEmrDiskTypesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := emr.CreateListEmrAvailableResourceRequest()
if dstRes, ok := d.GetOk("destination_resource"); ok {
request.DestinationResource = strings.TrimSpace(dstRes.(string))
}
if typ, ok := d.GetOk("cluster_type"); ok {
request.ClusterType = strings.TrimSpace(typ.(string))
}
if chargeType, ok := d.GetOk("instance_charge_type"); ok {
request.InstanceChargeType = strings.TrimSpace(chargeType.(string))
}
if instanceType, ok := d.GetOk("instance_type"); ok {
request.InstanceType = strings.TrimSpace(instanceType.(string))
}
if zoneID, ok := d.GetOk("zone_id"); ok {
request.ZoneId = strings.TrimSpace(zoneID.(string))
}
raw, err := client.WithEmrClient(func(emrClient *emr.Client) (interface{}, error) {
return emrClient.ListEmrAvailableResource(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_emr_disk_types", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
var resources []emr.SupportedResource
resourceResponse, _ := raw.(*emr.ListEmrAvailableResourceResponse)
for _, zoneInfo := range resourceResponse.EmrZoneInfoList.EmrZoneInfo {
resourceInfo := zoneInfo.EmrResourceInfoList.EmrResourceInfo
if len(resourceInfo) > 0 {
resources = resourceInfo[0].SupportedResourceList.SupportedResource
}
}
return emrClusterDiskTypesAttributes(d, resources)
}
func emrClusterDiskTypesAttributes(d *schema.ResourceData, resources []emr.SupportedResource) error {
var ids []string
var s []map[string]interface{}
for _, resource := range resources {
mapping := map[string]interface{}{
"min": resource.Min,
"max": resource.Max,
"value": resource.Value,
}
ids = append(ids, resource.Value)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("types", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"sort"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/services/emr"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEmrInstanceTypes() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEmrInstanceTypesRead,
Schema: map[string]*schema.Schema{
"destination_resource": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
"Zone",
"Network",
"InstanceType",
"SystemDisk",
"DataDisk",
}, false),
},
"cluster_type": {
Type: schema.TypeString,
Required: true,
},
"instance_type": {
Type: schema.TypeString,
Optional: true,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
},
"support_local_storage": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"instance_charge_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
"PostPaid",
"PrePaid",
}, false),
},
"support_node_type": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"types": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"local_storage_capacity": {
Type: schema.TypeInt,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEmrInstanceTypesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := emr.CreateListEmrAvailableResourceRequest()
request.RegionId = string(client.Region)
if dstRes, ok := d.GetOk("destination_resource"); ok {
request.DestinationResource = strings.TrimSpace(dstRes.(string))
}
if typ, ok := d.GetOk("cluster_type"); ok {
request.ClusterType = strings.TrimSpace(typ.(string))
}
if instanceType, ok := d.GetOk("instance_type"); ok {
request.InstanceType = strings.TrimSpace(instanceType.(string))
}
if chargeType, ok := d.GetOk("instance_charge_type"); ok {
request.InstanceChargeType = strings.TrimSpace(chargeType.(string))
}
raw, err := client.WithEmrClient(func(emrClient *emr.Client) (interface{}, error) {
return emrClient.ListEmrAvailableResource(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_emr_instance_types",
request.GetActionName(), AlibabaCloudSdkGoERROR)
}
supportedResources := make(map[string][]emr.SupportedResource)
resourceResponse, _ := raw.(*emr.ListEmrAvailableResourceResponse)
for _, zoneInfo := range resourceResponse.EmrZoneInfoList.EmrZoneInfo {
resourceInfo := zoneInfo.EmrResourceInfoList.EmrResourceInfo
if len(resourceInfo) == 1 {
supportedResources[zoneInfo.ZoneId] = resourceInfo[0].SupportedResourceList.SupportedResource
}
}
return emrClusterInstanceTypesAttributes(d, supportedResources)
}
func emrClusterInstanceTypesAttributes(d *schema.ResourceData,
supportedResources map[string][]emr.SupportedResource) error {
var ids []string
var zoneIDs []string
var s []map[string]interface{}
optZoneID := d.Get("zone_id").(string)
for k, v := range supportedResources {
if k == "" || len(v) == 0 { // ignore empty zoneId or empty emr instance type of the specific zoneId
continue
} else if optZoneID != "" && k != optZoneID { // get supported resources of a specific zoneId
continue
} else if optZoneID != "" && k == optZoneID {
zoneIDs = append(zoneIDs, k)
break
}
zoneIDs = append(zoneIDs, k)
}
sort.Strings(zoneIDs)
localStorage := d.Get("support_local_storage").(bool)
supportNodeType := d.Get("support_node_type").([]interface{})
nodeTypeFilter := func(filter []interface{}, source []string) bool {
if len(source) == 0 {
return false
}
sourceMapping := make(map[string]struct{})
for _, s := range source {
sourceMapping[s] = struct{}{}
}
for _, f := range filter {
if _, ok := sourceMapping[f.(string)]; !ok {
return false
}
}
return true
}
for _, zoneID := range zoneIDs {
mapping := map[string]interface{}{
"zone_id": zoneID,
}
if v, ok := supportedResources[zoneID]; ok {
selector := make(map[string]interface{})
selectFunc := func(m map[string]interface{}, tpe emr.SupportedResource, localStorage bool) {
prefix := "ecs.i2." // use those instance types first to localStorage
if localStorage {
prefix = "ecs.g5." // use those instance types first to cloudStorage
}
if preID, ok := selector["id"]; !ok {
selector["id"] = tpe.EmrInstanceType.InstanceType
selector["cpu_core_count"] = tpe.EmrInstanceType.CpuCoreCount
if localStorage {
selector["local_storage_capacity"] = tpe.EmrInstanceType.LocalStorageCapacity
}
} else if !strings.HasPrefix(tpe.EmrInstanceType.InstanceType, prefix) {
if !strings.HasPrefix(preID.(string), prefix) &&
selector["cpu_core_count"].(int) > tpe.EmrInstanceType.CpuCoreCount {
selector["id"] = tpe.EmrInstanceType.InstanceType
selector["cpu_core_count"] = tpe.EmrInstanceType.CpuCoreCount
if localStorage {
selector["local_storage_capacity"] = tpe.EmrInstanceType.LocalStorageCapacity
}
}
return
} else if !strings.HasPrefix(preID.(string), prefix) {
selector["id"] = tpe.EmrInstanceType.InstanceType
selector["cpu_core_count"] = tpe.EmrInstanceType.CpuCoreCount
if localStorage {
selector["local_storage_capacity"] = tpe.EmrInstanceType.LocalStorageCapacity
}
} else if selector["cpu_core_count"].(int) > tpe.EmrInstanceType.CpuCoreCount {
selector["id"] = tpe.EmrInstanceType.InstanceType
selector["cpu_core_count"] = tpe.EmrInstanceType.CpuCoreCount
if localStorage {
selector["local_storage_capacity"] = tpe.EmrInstanceType.LocalStorageCapacity
}
}
}
for _, tpe := range v {
if nodeTypeFilter(supportNodeType, tpe.SupportNodeTypeList.SupportNodeType) == false {
continue
}
if localStorage == true && tpe.EmrInstanceType.LocalStorageAmount > 0 {
selectFunc(selector, tpe, true)
} else if localStorage == false && tpe.EmrInstanceType.LocalStorageAmount == 0 {
selectFunc(selector, tpe, false)
}
}
if v, ok := selector["id"]; !ok {
continue
} else {
mapping["id"] = v
}
if v, ok := selector["local_storage_capacity"]; ok {
mapping["local_storage_capacity"] = v
}
ids = append(ids, selector["id"].(string))
s = append(s, mapping)
}
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("types", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/emr"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudEmrMainVersions() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEmrMainVersionsRead,
Schema: map[string]*schema.Schema{
"emr_version": {
Type: schema.TypeString,
Optional: true,
},
"cluster_type": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"main_versions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"emr_version": {
Type: schema.TypeString,
Computed: true,
},
"cluster_types": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"image_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
}
}
func dataSourceAlicloudEmrMainVersionsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := emr.CreateListEmrMainVersionRequest()
if emrVersion, ok := d.GetOk("emr_version"); ok {
request.EmrVersion = strings.TrimSpace(emrVersion.(string))
}
request.PageSize = requests.NewInteger(PageSizeLarge)
raw, err := client.WithEmrClient(func(emrClient *emr.Client) (interface{}, error) {
return emrClient.ListEmrMainVersion(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_emr_main_versions", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
var (
mainVersions []emr.EmrMainVersion
clusterTypes = make(map[string][]string)
)
response, _ := raw.(*emr.ListEmrMainVersionResponse)
if response != nil {
// get clusterInfo of specific emr version
var (
versionRequest = emr.CreateDescribeEmrMainVersionRequest()
versionResponse *emr.DescribeEmrMainVersionResponse
versionRaw interface{}
)
clusterTypeFilter := func(filter []interface{}, source []emr.ClusterTypeInfo) (result []string) {
if len(source) == 0 {
return
}
if len(filter) == 0 {
for _, c := range source {
result = append(result, c.ClusterType)
}
return
}
sourceMapping := make(map[string]struct{})
for _, s := range source {
sourceMapping[s.ClusterType] = struct{}{}
}
for _, f := range filter {
if _, ok := sourceMapping[f.(string)]; !ok {
return nil
}
result = append(result, f.(string))
}
return
}
for _, v := range response.EmrMainVersionList.EmrMainVersion {
if v.EmrVersion == "" {
continue
}
versionRequest.EmrVersion = v.EmrVersion
wait := incrementalWait(1*time.Second, 1*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
versionRaw, err = client.WithEmrClient(func(emrClient *emr.Client) (interface{}, error) {
return emrClient.DescribeEmrMainVersion(versionRequest)
})
if err != nil {
if IsExpectedErrors(err, []string{"Throttling.User"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
versionResponse, _ = versionRaw.(*emr.DescribeEmrMainVersionResponse)
return nil
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_emr_main_versions", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
versionResponse, _ = versionRaw.(*emr.DescribeEmrMainVersionResponse)
if versionResponse == nil {
continue
}
var (
clusterTypeInfo = versionResponse.EmrMainVersion.ClusterTypeInfoList.ClusterTypeInfo
types []string
)
// filter by specific clusterType
if types = clusterTypeFilter(d.Get("cluster_type").([]interface{}), clusterTypeInfo); len(types) == 0 {
continue
}
clusterTypes[v.EmrVersion] = types
}
mainVersions = response.EmrMainVersionList.EmrMainVersion
}
return emrClusterMainVersionAttributes(d, clusterTypes, mainVersions)
}
func emrClusterMainVersionAttributes(d *schema.ResourceData, clusterTypes map[string][]string, mainVersions []emr.EmrMainVersion) error {
var (
ids []string
s []map[string]interface{}
)
for _, version := range mainVersions {
// if display is false, ignore it
if !version.Display {
continue
}
ct := clusterTypes[version.EmrVersion]
if len(ct) == 0 {
continue
}
mapping := map[string]interface{}{
"image_id": version.ImageId,
"emr_version": version.EmrVersion,
"cluster_types": ct,
}
s = append(s, mapping)
ids = append(ids, version.EmrVersion)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("main_versions", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"sort"
"strconv"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudEnhancedNatAvailableZones() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEnhancedNatAvailableZonesRead,
Schema: map[string]*schema.Schema{
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"zones": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
"local_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEnhancedNatAvailableZonesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "ListEnhanhcedNatGatewayAvailableZones"
request := map[string]interface{}{
"RegionId": client.RegionId,
}
conn, err := meta.(*connectivity.AliyunClient).NewVpcClient()
if err != nil {
return WrapError(err)
}
// If the API supports
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"TaskConflict", "UnknownError", Throttling}) {
time.Sleep(5 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_enhanced_nat_available_zones", action, AlibabaCloudSdkGoERROR)
}
var s []map[string]interface{}
var ids []string
v, err := jsonpath.Get("$.Zones", response)
if err != nil || len(v.([]interface{})) < 1 {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_enhanced_nat_available_zones", action, AlibabaCloudSdkGoERROR)
}
zones := v.([]interface{})
sort.Slice(zones, func(i, j int) bool {
return zones[i].(map[string]interface{})["ZoneId"].(string) < zones[j].(map[string]interface{})["ZoneId"].(string)
})
for _, val := range zones {
value := val.(map[string]interface{})
mapping := map[string]interface{}{
"zone_id": value["ZoneId"].(string),
"local_name": value["LocalName"].(string),
}
s = append(s, mapping)
ids = append(ids, value["LocalName"].(string))
}
d.SetId(strconv.FormatInt(time.Now().Unix(), 16))
if err := d.Set("zones", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEnsKeyPairs() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEnsKeyPairsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"key_pair_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"version": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"pairs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"key_pair_finger_print": {
Type: schema.TypeString,
Computed: true,
},
"key_pair_name": {
Type: schema.TypeString,
Computed: true,
},
"version": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEnsKeyPairsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeKeyPairs"
request := make(map[string]interface{})
if v, ok := d.GetOk("key_pair_name"); ok {
request["KeyPairName"] = v
}
request["Version"] = d.Get("version")
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var keyPairNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
keyPairNameRegex = r
}
var response map[string]interface{}
conn, err := client.NewEnsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-11-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ens_key_pairs", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.KeyPairs.KeyPair", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.KeyPairs.KeyPair", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if keyPairNameRegex != nil && !keyPairNameRegex.MatchString(fmt.Sprint(item["KeyPairName"])) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["KeyPairName"], ":", request["Version"]),
"create_time": object["CreationTime"],
"key_pair_finger_print": object["KeyPairFingerPrint"],
"key_pair_name": object["KeyPairName"],
"version": request["Version"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["KeyPairName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("pairs", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"strconv"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ess"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEssAlarms() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEssAlarmsRead,
Schema: map[string]*schema.Schema{
"scaling_group_id": {
Type: schema.TypeString,
Optional: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"metric_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"system", "custom"}, false),
},
"alarms": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"enable": {
Type: schema.TypeBool,
Computed: true,
},
"alarm_actions": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"scaling_group_id": {
Type: schema.TypeString,
Computed: true,
},
"metric_type": {
Type: schema.TypeString,
Computed: true,
},
"metric_name": {
Type: schema.TypeString,
Computed: true,
},
"period": {
Type: schema.TypeInt,
Computed: true,
},
"statistics": {
Type: schema.TypeString,
Computed: true,
},
"threshold": {
Type: schema.TypeString,
Computed: true,
},
"comparison_operator": {
Type: schema.TypeString,
Computed: true,
},
"evaluation_count": {
Type: schema.TypeInt,
Computed: true,
},
"cloud_monitor_group_id": {
Type: schema.TypeInt,
Computed: true,
},
"dimensions": {
Type: schema.TypeMap,
Computed: true,
},
"state": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEssAlarmsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ess.CreateDescribeAlarmsRequest()
request.RegionId = client.RegionId
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
if scalingGroupId, ok := d.GetOk("scaling_group_id"); ok && scalingGroupId.(string) != "" {
request.ScalingGroupId = scalingGroupId.(string)
}
if metric_type, ok := d.GetOk("metric_type"); ok && metric_type.(string) != "" {
request.MetricType = metric_type.(string)
}
var allAlarms []ess.Alarm
for {
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DescribeAlarms(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ess_alarms", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response := raw.(*ess.DescribeAlarmsResponse)
if len(response.AlarmList.Alarm) < 1 {
break
}
allAlarms = append(allAlarms, response.AlarmList.Alarm...)
if len(response.AlarmList.Alarm) < PageSizeLarge {
break
}
if page, err := getNextpageNumber(request.PageNumber); err != nil {
return WrapError(err)
} else {
request.PageNumber = page
}
}
var filteredAlarms = make([]ess.Alarm, 0)
nameRegex, okNameRegex := d.GetOk("name_regex")
idsMap := make(map[string]string)
ids, okIds := d.GetOk("ids")
if okIds {
for _, i := range ids.([]interface{}) {
if i == nil {
continue
}
idsMap[i.(string)] = i.(string)
}
}
if okNameRegex || okIds {
for _, alarm := range allAlarms {
if okNameRegex && nameRegex != "" {
r, err := regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
if r != nil && !r.MatchString(alarm.Name) {
continue
}
}
if okIds && len(idsMap) > 0 {
if _, ok := idsMap[alarm.AlarmTaskId]; !ok {
continue
}
}
filteredAlarms = append(filteredAlarms, alarm)
}
} else {
filteredAlarms = allAlarms
}
return alarmsDescriptionAttribute(d, filteredAlarms, meta)
}
func alarmsDescriptionAttribute(d *schema.ResourceData, alarms []ess.Alarm, meta interface{}) error {
var ids []string
var names []string
var s = make([]map[string]interface{}, 0)
for _, alarm := range alarms {
dims := make([]ess.Dimension, 0, len(alarm.Dimensions.Dimension))
for _, dimension := range alarm.Dimensions.Dimension {
dims = append(dims, dimension)
}
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
mapping := map[string]interface{}{
"state": alarm.State,
"id": alarm.AlarmTaskId,
"name": alarm.Name,
"scaling_group_id": alarm.ScalingGroupId,
"metric_name": alarm.MetricName,
"description": alarm.Description,
"enable": alarm.Enable,
"alarm_actions": alarm.AlarmActions.AlarmAction,
"metric_type": alarm.MetricType,
"period": alarm.Period,
"statistics": alarm.Statistics,
"threshold": strconv.FormatFloat(alarm.Threshold, 'f', -1, 32),
"comparison_operator": alarm.ComparisonOperator,
"evaluation_count": alarm.EvaluationCount,
"dimensions": essService.flattenDimensionsToMap(dims),
}
ids = append(ids, alarm.AlarmTaskId)
names = append(names, alarm.AlarmTaskName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("alarms", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ess"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEssLifecycleHooks() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEssLifecycleHooksRead,
Schema: map[string]*schema.Schema{
"scaling_group_id": {
Type: schema.TypeString,
Optional: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"hooks": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"scaling_group_id": {
Type: schema.TypeString,
Computed: true,
},
"default_result": {
Type: schema.TypeString,
Computed: true,
},
"heartbeat_timeout": {
Type: schema.TypeInt,
Computed: true,
},
"lifecycle_transition": {
Type: schema.TypeString,
Computed: true,
},
"notification_arn": {
Type: schema.TypeString,
Computed: true,
},
"notification_metadata": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEssLifecycleHooksRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ess.CreateDescribeLifecycleHooksRequest()
request.RegionId = client.RegionId
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
if scalingGroupId, ok := d.GetOk("scaling_group_id"); ok && scalingGroupId.(string) != "" {
request.ScalingGroupId = scalingGroupId.(string)
}
var allLifecycleHooks []ess.LifecycleHook
for {
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DescribeLifecycleHooks(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ess_lifecycle_hooks", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response := raw.(*ess.DescribeLifecycleHooksResponse)
if len(response.LifecycleHooks.LifecycleHook) < 1 {
break
}
allLifecycleHooks = append(allLifecycleHooks, response.LifecycleHooks.LifecycleHook...)
if len(response.LifecycleHooks.LifecycleHook) < PageSizeLarge {
break
}
if page, err := getNextpageNumber(request.PageNumber); err != nil {
return WrapError(err)
} else {
request.PageNumber = page
}
}
var filteredLifecycleHooks = make([]ess.LifecycleHook, 0)
nameRegex, okNameRegex := d.GetOk("name_regex")
idsMap := make(map[string]string)
ids, okIds := d.GetOk("ids")
if okIds {
for _, i := range ids.([]interface{}) {
if i == nil {
continue
}
idsMap[i.(string)] = i.(string)
}
}
if okNameRegex || okIds {
for _, hook := range allLifecycleHooks {
if okNameRegex && nameRegex != "" {
r, err := regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
if r != nil && !r.MatchString(hook.LifecycleHookName) {
continue
}
}
if okIds && len(idsMap) > 0 {
if _, ok := idsMap[hook.LifecycleHookId]; !ok {
continue
}
}
filteredLifecycleHooks = append(filteredLifecycleHooks, hook)
}
} else {
filteredLifecycleHooks = allLifecycleHooks
}
return lifecycleHooksDescriptionAttribute(d, filteredLifecycleHooks, meta)
}
func lifecycleHooksDescriptionAttribute(d *schema.ResourceData, lifecycleHooks []ess.LifecycleHook, meta interface{}) error {
var ids []string
var names []string
var s = make([]map[string]interface{}, 0)
for _, hook := range lifecycleHooks {
mapping := map[string]interface{}{
"id": hook.LifecycleHookId,
"name": hook.LifecycleHookName,
"scaling_group_id": hook.ScalingGroupId,
"default_result": hook.DefaultResult,
"heartbeat_timeout": hook.HeartbeatTimeout,
"lifecycle_transition": hook.LifecycleTransition,
"notification_arn": hook.NotificationArn,
"notification_metadata": hook.NotificationMetadata,
}
ids = append(ids, hook.LifecycleHookId)
names = append(names, hook.LifecycleHookName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("hooks", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"github.com/aliyun/alibaba-cloud-sdk-go/services/ess"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudEssNotifications() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEssNotificationsRead,
Schema: map[string]*schema.Schema{
"scaling_group_id": {
Type: schema.TypeString,
Required: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"notifications": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"notification_arn": {
Type: schema.TypeString,
Computed: true,
},
"notification_types": {
Type: schema.TypeSet,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"scaling_group_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEssNotificationsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ess.CreateDescribeNotificationConfigurationsRequest()
request.RegionId = client.RegionId
if scalingGroupId, ok := d.GetOk("scaling_group_id"); ok && scalingGroupId.(string) != "" {
request.ScalingGroupId = scalingGroupId.(string)
}
var allNotifications []ess.NotificationConfigurationModel
for {
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DescribeNotificationConfigurations(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ess_notifications", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response := raw.(*ess.DescribeNotificationConfigurationsResponse)
if len(response.NotificationConfigurationModels.NotificationConfigurationModel) < 1 {
break
}
allNotifications = append(allNotifications, response.NotificationConfigurationModels.NotificationConfigurationModel...)
if len(response.NotificationConfigurationModels.NotificationConfigurationModel) < PageSizeLarge {
break
} else {
continue
}
}
var filteredNotifications = make([]ess.NotificationConfigurationModel, 0)
idsMap := make(map[string]string)
if ids, okIds := d.GetOk("ids"); okIds {
for _, i := range ids.([]interface{}) {
if i == nil {
continue
}
idsMap[i.(string)] = i.(string)
}
for _, n := range allNotifications {
if _, ok := idsMap[n.NotificationArn]; !ok {
continue
}
filteredNotifications = append(filteredNotifications, n)
}
} else {
filteredNotifications = allNotifications
}
return notificationsDescriptionAttribute(d, filteredNotifications, meta)
}
func notificationsDescriptionAttribute(d *schema.ResourceData, notifications []ess.NotificationConfigurationModel, meta interface{}) error {
var ids []string
var s = make([]map[string]interface{}, 0)
for _, n := range notifications {
mapping := map[string]interface{}{
"notification_arn": n.NotificationArn,
"notification_types": n.NotificationTypes.NotificationType,
"scaling_group_id": n.ScalingGroupId,
}
ids = append(ids, n.NotificationArn)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("notifications", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ess"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEssScalingConfigurations() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEssScalingConfigurationsRead,
Schema: map[string]*schema.Schema{
"scaling_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"configurations": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"scaling_group_id": {
Type: schema.TypeString,
Computed: true,
},
"image_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_type": {
Type: schema.TypeString,
Computed: true,
},
"security_group_id": {
Type: schema.TypeString,
Computed: true,
},
"internet_charge_type": {
Type: schema.TypeString,
Computed: true,
},
"internet_max_bandwidth_in": {
Type: schema.TypeInt,
Computed: true,
},
"internet_max_bandwidth_out": {
Type: schema.TypeInt,
Computed: true,
},
"credit_specification": {
Type: schema.TypeString,
Computed: true,
},
"system_disk_category": {
Type: schema.TypeString,
Computed: true,
},
"system_disk_size": {
Type: schema.TypeInt,
Computed: true,
},
"system_disk_performance_level": {
Type: schema.TypeString,
Computed: true,
},
"data_disks": {
Type: schema.TypeList,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"size": {
Type: schema.TypeInt,
Optional: true,
},
"category": {
Type: schema.TypeString,
Optional: true,
},
"snapshot_id": {
Type: schema.TypeString,
Optional: true,
},
"device": {
Type: schema.TypeString,
Optional: true,
},
"delete_with_instance": {
Type: schema.TypeBool,
Optional: true,
},
"performance_level": {
Type: schema.TypeString,
Optional: true,
},
},
},
Computed: true,
},
"lifecycle_state": {
Type: schema.TypeString,
Computed: true,
},
"creation_time": {
Type: schema.TypeString,
Computed: true,
},
"instance_name": {
Type: schema.TypeString,
Computed: true,
},
"host_name": {
Type: schema.TypeString,
Computed: true,
},
"spot_strategy": {
Type: schema.TypeString,
Computed: true,
},
"spot_price_limit": {
Type: schema.TypeList,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"instance_type": {
Type: schema.TypeString,
Optional: true,
},
"price_limit": {
Type: schema.TypeFloat,
Optional: true,
},
},
},
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEssScalingConfigurationsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ess.CreateDescribeScalingConfigurationsRequest()
request.RegionId = client.RegionId
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
if scalingGroupId, ok := d.GetOk("scaling_group_id"); ok && scalingGroupId.(string) != "" {
request.ScalingGroupId = scalingGroupId.(string)
}
var allScalingConfigurations []ess.ScalingConfiguration
for {
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DescribeScalingConfigurations(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ess_scalingconfigurations", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response := raw.(*ess.DescribeScalingConfigurationsResponse)
if len(response.ScalingConfigurations.ScalingConfiguration) < 1 {
break
}
allScalingConfigurations = append(allScalingConfigurations, response.ScalingConfigurations.ScalingConfiguration...)
if len(response.ScalingConfigurations.ScalingConfiguration) < PageSizeLarge {
break
}
if page, err := getNextpageNumber(request.PageNumber); err != nil {
return WrapError(err)
} else {
request.PageNumber = page
}
}
var filteredScalingConfigurations = make([]ess.ScalingConfiguration, 0)
nameRegex, okNameRegex := d.GetOk("name_regex")
idsMap := make(map[string]string)
ids, okIds := d.GetOk("ids")
if okIds {
for _, i := range ids.([]interface{}) {
if i == nil {
continue
}
idsMap[i.(string)] = i.(string)
}
}
if okNameRegex || okIds {
for _, configuration := range allScalingConfigurations {
if okNameRegex && nameRegex != "" {
r, err := regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
if r != nil && !r.MatchString(configuration.ScalingConfigurationName) {
continue
}
}
if okIds && len(idsMap) > 0 {
if _, ok := idsMap[configuration.ScalingConfigurationId]; !ok {
continue
}
}
filteredScalingConfigurations = append(filteredScalingConfigurations, configuration)
}
} else {
filteredScalingConfigurations = allScalingConfigurations
}
return scalingConfigurationsDescriptionAttribute(d, filteredScalingConfigurations, meta)
}
func scalingConfigurationsDescriptionAttribute(d *schema.ResourceData, scalingConfigurations []ess.ScalingConfiguration, meta interface{}) error {
var ids []string
var names []string
var s = make([]map[string]interface{}, 0)
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
for _, scalingConfiguration := range scalingConfigurations {
mapping := map[string]interface{}{
"id": scalingConfiguration.ScalingConfigurationId,
"name": scalingConfiguration.ScalingConfigurationName,
"scaling_group_id": scalingConfiguration.ScalingGroupId,
"image_id": scalingConfiguration.ImageId,
"instance_type": scalingConfiguration.InstanceType,
"security_group_id": scalingConfiguration.SecurityGroupId,
"internet_charge_type": scalingConfiguration.InternetChargeType,
"internet_max_bandwidth_in": scalingConfiguration.InternetMaxBandwidthIn,
"internet_max_bandwidth_out": scalingConfiguration.InternetMaxBandwidthOut,
"credit_specification": scalingConfiguration.CreditSpecification,
"system_disk_category": scalingConfiguration.SystemDiskCategory,
"system_disk_size": scalingConfiguration.SystemDiskSize,
"system_disk_performance_level": scalingConfiguration.SystemDiskPerformanceLevel,
"data_disks": essService.flattenDataDiskMappings(scalingConfiguration.DataDisks.DataDisk),
"lifecycle_state": scalingConfiguration.LifecycleState,
"creation_time": scalingConfiguration.CreationTime,
"instance_name": scalingConfiguration.InstanceName,
"host_name": scalingConfiguration.HostName,
"spot_strategy": scalingConfiguration.SpotStrategy,
"spot_price_limit": essService.flattenSpotPriceLimitMappings(scalingConfiguration.SpotPriceLimit.SpotPriceModel),
}
ids = append(ids, scalingConfiguration.ScalingConfigurationId)
names = append(names, scalingConfiguration.ScalingConfigurationName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("configurations", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ess"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEssScalingGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEssScalingGroupsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"active_scaling_configuration": {
Type: schema.TypeString,
Computed: true,
},
"launch_template_id": {
Type: schema.TypeString,
Computed: true,
},
"launch_template_version": {
Type: schema.TypeString,
Computed: true,
},
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"min_size": {
Type: schema.TypeInt,
Computed: true,
},
"max_size": {
Type: schema.TypeInt,
Computed: true,
},
"cooldown_time": {
Type: schema.TypeInt,
Computed: true,
},
"removal_policies": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"load_balancer_ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"db_instance_ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"vswitch_ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"lifecycle_state": {
Type: schema.TypeString,
Computed: true,
},
"total_capacity": {
Type: schema.TypeInt,
Computed: true,
},
"active_capacity": {
Type: schema.TypeInt,
Computed: true,
},
"pending_capacity": {
Type: schema.TypeInt,
Computed: true,
},
"removing_capacity": {
Type: schema.TypeInt,
Computed: true,
},
"creation_time": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEssScalingGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ess.CreateDescribeScalingGroupsRequest()
request.RegionId = client.RegionId
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var allScalingGroups []ess.ScalingGroup
for {
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DescribeScalingGroups(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ess_scalinggroups", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ess.DescribeScalingGroupsResponse)
if len(response.ScalingGroups.ScalingGroup) < 1 {
break
}
allScalingGroups = append(allScalingGroups, response.ScalingGroups.ScalingGroup...)
if len(response.ScalingGroups.ScalingGroup) < PageSizeLarge {
break
}
if page, err := getNextpageNumber(request.PageNumber); err != nil {
return WrapError(err)
} else {
request.PageNumber = page
}
}
var filteredScalingGroupsTemp = make([]ess.ScalingGroup, 0)
nameRegex, okNameRegex := d.GetOk("name_regex")
idsMap := make(map[string]string)
ids, okIds := d.GetOk("ids")
if okIds {
for _, i := range ids.([]interface{}) {
if i == nil {
continue
}
idsMap[i.(string)] = i.(string)
}
}
if okNameRegex || okIds {
for _, group := range allScalingGroups {
if okNameRegex && nameRegex != "" {
r, err := regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
if r != nil && !r.MatchString(group.ScalingGroupName) {
continue
}
}
if okIds && len(idsMap) > 0 {
if _, ok := idsMap[group.ScalingGroupId]; !ok {
continue
}
}
filteredScalingGroupsTemp = append(filteredScalingGroupsTemp, group)
}
} else {
filteredScalingGroupsTemp = allScalingGroups
}
return scalingGroupsDescriptionAttribute(d, filteredScalingGroupsTemp, meta)
}
func scalingGroupsDescriptionAttribute(d *schema.ResourceData, scalingGroups []ess.ScalingGroup, meta interface{}) error {
var ids []string
var names []string
var s = make([]map[string]interface{}, 0)
for _, scalingGroup := range scalingGroups {
mapping := map[string]interface{}{
"id": scalingGroup.ScalingGroupId,
"name": scalingGroup.ScalingGroupName,
"active_scaling_configuration": scalingGroup.ActiveScalingConfigurationId,
"launch_template_id": scalingGroup.LaunchTemplateId,
"launch_template_version": scalingGroup.LaunchTemplateVersion,
"region_id": scalingGroup.RegionId,
"min_size": scalingGroup.MinSize,
"max_size": scalingGroup.MaxSize,
"cooldown_time": scalingGroup.DefaultCooldown,
"removal_policies": scalingGroup.RemovalPolicies.RemovalPolicy,
"load_balancer_ids": scalingGroup.LoadBalancerIds.LoadBalancerId,
"db_instance_ids": scalingGroup.DBInstanceIds.DBInstanceId,
"vswitch_ids": scalingGroup.VSwitchIds.VSwitchId,
"lifecycle_state": scalingGroup.LifecycleState,
"total_capacity": scalingGroup.TotalCapacity,
"active_capacity": scalingGroup.ActiveCapacity,
"pending_capacity": scalingGroup.PendingCapacity,
"removing_capacity": scalingGroup.RemovingCapacity,
"creation_time": scalingGroup.CreationTime,
}
ids = append(ids, scalingGroup.ScalingGroupId)
names = append(names, scalingGroup.ScalingGroupName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ess"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEssScalingRules() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEssScalingRulesRead,
Schema: map[string]*schema.Schema{
"scaling_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
},
"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"scaling_group_id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"cooldown": {
Type: schema.TypeInt,
Computed: true,
},
"adjustment_type": {
Type: schema.TypeString,
Computed: true,
},
"adjustment_value": {
Type: schema.TypeInt,
Computed: true,
},
"min_adjustment_magnitude": {
Type: schema.TypeInt,
Computed: true,
},
"scaling_rule_ari": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEssScalingRulesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ess.CreateDescribeScalingRulesRequest()
request.RegionId = client.RegionId
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
if scalingGroupId, ok := d.GetOk("scaling_group_id"); ok && scalingGroupId.(string) != "" {
request.ScalingGroupId = scalingGroupId.(string)
}
if ruleType, ok := d.GetOk("type"); ok && ruleType.(string) != "" {
request.ScalingRuleType = ruleType.(string)
}
var allScalingRules []ess.ScalingRule
for {
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DescribeScalingRules(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ess_scalingrules", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ess.DescribeScalingRulesResponse)
if len(response.ScalingRules.ScalingRule) < 1 {
break
}
allScalingRules = append(allScalingRules, response.ScalingRules.ScalingRule...)
if len(response.ScalingRules.ScalingRule) < PageSizeLarge {
break
}
if page, err := getNextpageNumber(request.PageNumber); err != nil {
return err
} else {
request.PageNumber = page
}
}
var filteredScalingRulesTemp = make([]ess.ScalingRule, 0)
nameRegex, okNameRegex := d.GetOk("name_regex")
idsMap := make(map[string]string)
ids, okIds := d.GetOk("ids")
if okIds {
for _, i := range ids.([]interface{}) {
if i == nil {
continue
}
idsMap[i.(string)] = i.(string)
}
}
if okNameRegex || okIds {
for _, rule := range allScalingRules {
if okNameRegex && nameRegex != "" {
r, err := regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
if r != nil && !r.MatchString(rule.ScalingRuleName) {
continue
}
}
if okIds && len(idsMap) > 0 {
if _, ok := idsMap[rule.ScalingRuleId]; !ok {
continue
}
}
filteredScalingRulesTemp = append(filteredScalingRulesTemp, rule)
}
} else {
filteredScalingRulesTemp = allScalingRules
}
return scalingRulesDescriptionAttribute(d, filteredScalingRulesTemp, meta)
}
func scalingRulesDescriptionAttribute(d *schema.ResourceData, scalingRules []ess.ScalingRule, meta interface{}) error {
var ids []string
var names []string
var s = make([]map[string]interface{}, 0)
for _, scalingRule := range scalingRules {
mapping := map[string]interface{}{
"id": scalingRule.ScalingRuleId,
"scaling_group_id": scalingRule.ScalingGroupId,
"name": scalingRule.ScalingRuleName,
"type": scalingRule.ScalingRuleType,
"cooldown": scalingRule.Cooldown,
"adjustment_type": scalingRule.AdjustmentType,
"adjustment_value": scalingRule.AdjustmentValue,
"min_adjustment_magnitude": scalingRule.MinAdjustmentMagnitude,
"scaling_rule_ari": scalingRule.ScalingRuleAri,
}
ids = append(ids, scalingRule.ScalingRuleId)
names = append(names, scalingRule.ScalingRuleName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("rules", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ess"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEssScheduledTasks() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEssScheduledTasksRead,
Schema: map[string]*schema.Schema{
"scheduled_task_id": {
Type: schema.TypeString,
Optional: true,
},
"scheduled_action": {
Type: schema.TypeString,
Optional: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"tasks": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"scheduled_action": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"launch_expiration_time": {
Type: schema.TypeInt,
Computed: true,
},
"launch_time": {
Type: schema.TypeString,
Computed: true,
},
"max_value": {
Type: schema.TypeInt,
Computed: true,
},
"min_value": {
Type: schema.TypeInt,
Computed: true,
},
"recurrence_end_time": {
Type: schema.TypeString,
Computed: true,
},
"recurrence_value": {
Type: schema.TypeString,
Computed: true,
},
"recurrence_type": {
Type: schema.TypeString,
Computed: true,
},
"task_enabled": {
Type: schema.TypeBool,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEssScheduledTasksRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ess.CreateDescribeScheduledTasksRequest()
request.RegionId = client.RegionId
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
if v, ok := d.GetOk("scheduled_task_id"); ok {
request.ScheduledTaskId = &[]string{v.(string)}
}
if v, ok := d.GetOk("scheduled_action"); ok {
request.ScheduledAction = &[]string{v.(string)}
}
var allScheduledTasks []ess.ScheduledTask
for {
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DescribeScheduledTasks(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ess_scheduled_tasks", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response := raw.(*ess.DescribeScheduledTasksResponse)
if len(response.ScheduledTasks.ScheduledTask) < 1 {
break
}
allScheduledTasks = append(allScheduledTasks, response.ScheduledTasks.ScheduledTask...)
if len(response.ScheduledTasks.ScheduledTask) < PageSizeLarge {
break
}
if page, err := getNextpageNumber(request.PageNumber); err != nil {
return WrapError(err)
} else {
request.PageNumber = page
}
}
var filteredScheduledtasks = make([]ess.ScheduledTask, 0)
nameRegex, okNameRegex := d.GetOk("name_regex")
idsMap := make(map[string]string)
ids, okIds := d.GetOk("ids")
if okIds {
for _, i := range ids.([]interface{}) {
if i == nil {
continue
}
idsMap[i.(string)] = i.(string)
}
}
if okNameRegex || okIds {
for _, task := range allScheduledTasks {
if okNameRegex && nameRegex != "" {
r, err := regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
if r != nil && !r.MatchString(task.ScheduledTaskName) {
continue
}
}
if okIds && len(idsMap) > 0 {
if _, ok := idsMap[task.ScheduledTaskId]; !ok {
continue
}
}
filteredScheduledtasks = append(filteredScheduledtasks, task)
}
} else {
filteredScheduledtasks = allScheduledTasks
}
return scheduledTasksDescriptionAttribute(d, filteredScheduledtasks, meta)
}
func scheduledTasksDescriptionAttribute(d *schema.ResourceData, tasks []ess.ScheduledTask, meta interface{}) error {
var ids []string
var names []string
var s = make([]map[string]interface{}, 0)
for _, t := range tasks {
mapping := map[string]interface{}{
"id": t.ScheduledTaskId,
"name": t.ScheduledTaskName,
"scheduled_action": t.ScheduledAction,
"description": t.Description,
"launch_expiration_time": t.LaunchExpirationTime,
"launch_time": t.LaunchTime,
"max_value": t.MaxValue,
"min_value": t.MinValue,
"recurrence_end_time": t.RecurrenceEndTime,
"recurrence_value": t.RecurrenceValue,
"recurrence_type": t.RecurrenceType,
"task_enabled": t.TaskEnabled,
}
ids = append(ids, t.ScheduledTaskId)
names = append(names, t.ScheduledTaskName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("tasks", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEventBridgeEventBuses() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEventBridgeEventBusesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"event_bus_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"name_prefix": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"buses": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"event_bus_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEventBridgeEventBusesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListEventBuses"
request := make(map[string]interface{})
request["Limit"] = PageSizeLarge
if v, ok := d.GetOk("event_bus_type"); ok {
request["EventBusType"] = v
}
if v, ok := d.GetOk("limit"); ok {
request["Limit"] = v
}
if v, ok := d.GetOk("name_prefix"); ok {
request["NamePrefix"] = v
}
var objects []map[string]interface{}
var eventBusNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
eventBusNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewEventbridgeClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_event_bridge_event_buses", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("ListEventBuses failed, response: %v", response))
}
resp, err := jsonpath.Get("$.Data.EventBuses", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Data.EventBuses", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if eventBusNameRegex != nil {
if !eventBusNameRegex.MatchString(fmt.Sprint(item["EventBusName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["EventBusName"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": fmt.Sprint(object["CreateTimestamp"]),
"description": object["Description"],
"id": fmt.Sprint(object["EventBusName"]),
"event_bus_name": fmt.Sprint(object["EventBusName"]),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["EventBusName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("buses", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEventBridgeEventSources() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEventBridgeEventSourcesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"sources": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"event_source_name": {
Type: schema.TypeString,
Computed: true,
},
"external_source_config": {
Type: schema.TypeMap,
Computed: true,
},
"external_source_type": {
Type: schema.TypeString,
Computed: true,
},
"linked_external_source": {
Type: schema.TypeBool,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudEventBridgeEventSourcesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListUserDefinedEventSources"
request := make(map[string]interface{})
request["Limit"] = PageSizeLarge
var objects []map[string]interface{}
var eventSourceNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
eventSourceNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewEventbridgeClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_event_bridge_event_sources", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("ListEventSources failed, response: %v", response))
}
resp, err := jsonpath.Get("$.Data.EventSourceList", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Data", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if eventSourceNameRegex != nil {
if !eventSourceNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Name"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"description": object["Description"],
"id": fmt.Sprint(object["Name"]),
"event_source_name": fmt.Sprint(object["Name"]),
"external_source_config": object["ExternalSourceConfig"],
"external_source_type": object["ExternalSourceType"],
"linked_external_source": object["LinkedExternalSource"],
"type": object["Type"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("sources", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEventBridgeRules() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEventBridgeRulesRead,
Schema: map[string]*schema.Schema{
"event_bus_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"rule_name_prefix": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"DISABLE", "ENABLE"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Computed: true,
},
"event_bus_name": {
Type: schema.TypeString,
Computed: true,
},
"filter_pattern": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"rule_name": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"targets": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"endpoint": {
Type: schema.TypeString,
Computed: true,
},
"target_id": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudEventBridgeRulesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListRules"
request := make(map[string]interface{})
request["Limit"] = PageSizeLarge
request["EventBusName"] = d.Get("event_bus_name")
if v, ok := d.GetOk("rule_name_prefix"); ok {
request["RuleNamePrefix"] = v
}
var objects []map[string]interface{}
var ruleNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
ruleNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewEventbridgeClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_event_bridge_rules", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("ListRules failed, response: %v", response))
}
resp, err := jsonpath.Get("$.Data.Rules", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Data.Rules", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if ruleNameRegex != nil {
if !ruleNameRegex.MatchString(fmt.Sprint(item["RuleName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["RuleName"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"description": object["Description"],
"event_bus_name": object["EventBusName"],
"filter_pattern": object["FilterPattern"],
"id": fmt.Sprint(object["RuleName"]),
"rule_name": fmt.Sprint(object["RuleName"]),
"status": object["Status"],
}
targets := make([]map[string]interface{}, 0)
if targetsList, ok := object["Targets"].([]interface{}); ok {
for _, v := range targetsList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"endpoint": m1["Endpoint"],
"target_id": m1["Id"],
"type": m1["Type"],
}
targets = append(targets, temp1)
}
}
}
mapping["targets"] = targets
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["RuleName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("rules", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudEventBridgeService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudEventBridgeServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudEventBridgeServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("EventBridgeServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
var response map[string]interface{}
action := "CreateInstance"
request := map[string]interface{}{
"ProductCode": "eventbridge",
"SubscriptionType": "PayAsYouGo",
}
conn, err := meta.(*connectivity.AliyunClient).NewBssopenapiClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-14"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"NotApplicable"}) {
conn.Endpoint = String(connectivity.BssOpenAPIEndpointInternational)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ORDER.OPEND"}) {
d.SetId("EventBridgeServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_event_bridge_service", action, AlibabaCloudSdkGoERROR)
}
d.SetId("EventBridgeServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudExpressConnectAccessPoints() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudExpressConnectAccessPointsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"disabled", "full", "hot", "recommended"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"points": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"access_point_feature_models": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"feature_key": {
Type: schema.TypeString,
Computed: true,
},
"feature_value": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"access_point_id": {
Type: schema.TypeString,
Computed: true,
},
"access_point_name": {
Type: schema.TypeString,
Computed: true,
},
"attached_region_no": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"host_operator": {
Type: schema.TypeString,
Computed: true,
},
"location": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudExpressConnectAccessPointsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeAccessPoints"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var accessPointNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
accessPointNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_express_connect_access_points", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.AccessPointSet.AccessPointType", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.AccessPointSet.AccessPointType", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if accessPointNameRegex != nil && !accessPointNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["AccessPointId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeXLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["AccessPointId"]),
"access_point_id": fmt.Sprint(object["AccessPointId"]),
"access_point_name": object["Name"],
"attached_region_no": object["AttachedRegionNo"],
"description": object["Description"],
"host_operator": object["HostOperator"],
"location": object["Location"],
"status": object["Status"],
"type": object["Type"],
}
accessPointFeatureModel := make([]map[string]interface{}, 0)
if accessPointFeatureModelList, ok := object["AccessPointFeatureModels"].(map[string]interface{})["AccessPointFeatureModel"].([]interface{}); ok {
for _, v := range accessPointFeatureModelList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"feature_key": m1["FeatureKey"],
"feature_value": m1["FeatureValue"],
}
accessPointFeatureModel = append(accessPointFeatureModel, temp1)
}
}
}
mapping["access_point_feature_models"] = accessPointFeatureModel
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("points", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudExpressConnectPhysicalConnectionService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudPhysicalConnectionServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudPhysicalConnectionServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("PhysicalConnectionServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
client := meta.(*connectivity.AliyunClient)
action := "OpenPhysicalConnectionService"
var response map[string]interface{}
request := map[string]interface{}{
"RegionId": client.RegionId,
}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
return resource.RetryableError(err)
}
addDebug(action, response, nil)
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"PURCHASE_QUANTITY_LIMIT"}) {
d.SetId("PhysicalConnectionServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_fc_service", action, AlibabaCloudSdkGoERROR)
}
d.SetId("PhysicalConnectionServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudExpressConnectPhysicalConnections() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudExpressConnectPhysicalConnectionsRead,
Schema: map[string]*schema.Schema{
"include_reservation_data": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Allocated", "Allocating", "Allocation Failed", "Approved", "Canceled", "Confirmed", "Enabled", "Initial", "Rejected", "Terminated"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"connections": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"access_point_id": {
Type: schema.TypeString,
Computed: true,
},
"ad_location": {
Type: schema.TypeString,
Computed: true,
},
"bandwidth": {
Type: schema.TypeString,
Computed: true,
},
"business_status": {
Type: schema.TypeString,
Computed: true,
},
"circuit_code": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"enabled_time": {
Type: schema.TypeString,
Computed: true,
},
"end_time": {
Type: schema.TypeString,
Computed: true,
},
"has_reservation_data": {
Type: schema.TypeString,
Computed: true,
},
"line_operator": {
Type: schema.TypeString,
Computed: true,
},
"loa_status": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"peer_location": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"physical_connection_id": {
Type: schema.TypeString,
Computed: true,
},
"physical_connection_name": {
Type: schema.TypeString,
Computed: true,
},
"port_number": {
Type: schema.TypeString,
Computed: true,
},
"port_type": {
Type: schema.TypeString,
Computed: true,
},
"redundant_physical_connection_id": {
Type: schema.TypeString,
Computed: true,
},
"reservation_active_time": {
Type: schema.TypeString,
Computed: true,
},
"reservation_internet_charge_type": {
Type: schema.TypeString,
Computed: true,
},
"reservation_order_type": {
Type: schema.TypeString,
Computed: true,
},
"spec": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudExpressConnectPhysicalConnectionsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribePhysicalConnections"
request := make(map[string]interface{})
if v, ok := d.GetOkExists("include_reservation_data"); ok {
request["IncludeReservationData"] = v
}
request["RegionId"] = client.RegionId
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var physicalConnectionNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
physicalConnectionNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_express_connect_physical_connections", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.PhysicalConnectionSet.PhysicalConnectionType", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.PhysicalConnectionSet.PhysicalConnectionType", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if physicalConnectionNameRegex != nil && !physicalConnectionNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["PhysicalConnectionId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"access_point_id": object["AccessPointId"],
"ad_location": object["AdLocation"],
"bandwidth": fmt.Sprint(object["Bandwidth"]),
"business_status": object["BusinessStatus"],
"circuit_code": object["CircuitCode"],
"create_time": object["CreationTime"],
"description": object["Description"],
"enabled_time": object["EnabledTime"],
"end_time": object["EndTime"],
"has_reservation_data": fmt.Sprint(object["HasReservationData"]),
"line_operator": object["LineOperator"],
"loa_status": object["LoaStatus"],
"payment_type": object["ChargeType"],
"peer_location": object["PeerLocation"],
"id": fmt.Sprint(object["PhysicalConnectionId"]),
"physical_connection_id": fmt.Sprint(object["PhysicalConnectionId"]),
"physical_connection_name": object["Name"],
"port_number": object["PortNumber"],
"port_type": object["PortType"],
"redundant_physical_connection_id": object["RedundantPhysicalConnectionId"],
"reservation_active_time": object["ReservationActiveTime"],
"reservation_internet_charge_type": object["ReservationInternetChargeType"],
"reservation_order_type": object["ReservationOrderType"],
"spec": object["Spec"],
"status": object["Status"],
"type": object["Type"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("connections", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudExpressConnectVirtualBorderRouters() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudExpressConnectVirtualBorderRoutersRead,
Schema: map[string]*schema.Schema{
"filter": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"values": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
},
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"active", "deleting", "recovering", "terminated", "terminating", "unconfirmed"}, false),
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"routers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"access_point_id": {
Type: schema.TypeString,
Computed: true,
},
"activation_time": {
Type: schema.TypeString,
Computed: true,
},
"circuit_code": {
Type: schema.TypeString,
Computed: true,
},
"cloud_box_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"detect_multiplier": {
Type: schema.TypeInt,
Computed: true,
},
"ecc_id": {
Type: schema.TypeString,
Computed: true,
},
"enable_ipv6": {
Type: schema.TypeBool,
Computed: true,
},
"local_gateway_ip": {
Type: schema.TypeString,
Computed: true,
},
"local_ipv6_gateway_ip": {
Type: schema.TypeString,
Computed: true,
},
"min_rx_interval": {
Type: schema.TypeInt,
Computed: true,
},
"min_tx_interval": {
Type: schema.TypeInt,
Computed: true,
},
"payment_vbr_expire_time": {
Type: schema.TypeString,
Computed: true,
},
"peer_gateway_ip": {
Type: schema.TypeString,
Computed: true,
},
"peer_ipv6_gateway_ip": {
Type: schema.TypeString,
Computed: true,
},
"peering_ipv6_subnet_mask": {
Type: schema.TypeString,
Computed: true,
},
"peering_subnet_mask": {
Type: schema.TypeString,
Computed: true,
},
"physical_connection_business_status": {
Type: schema.TypeString,
Computed: true,
},
"physical_connection_id": {
Type: schema.TypeString,
Computed: true,
},
"physical_connection_owner_uid": {
Type: schema.TypeString,
Computed: true,
},
"physical_connection_status": {
Type: schema.TypeString,
Computed: true,
},
"recovery_time": {
Type: schema.TypeString,
Computed: true,
},
"route_table_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"termination_time": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"virtual_border_router_id": {
Type: schema.TypeString,
Computed: true,
},
"virtual_border_router_name": {
Type: schema.TypeString,
Computed: true,
},
"vlan_id": {
Type: schema.TypeInt,
Computed: true,
},
"vlan_interface_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudExpressConnectVirtualBorderRoutersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeVirtualBorderRouters"
request := make(map[string]interface{})
if v, ok := d.GetOk("filter"); ok {
for filterPtr, filter := range v.([]interface{}) {
filterArg := filter.(map[string]interface{})
request[fmt.Sprintf("Filter.%d.Key", filterPtr+1)] = filterArg["key"]
for valuePtr, value := range filterArg["values"].([]interface{}) {
request[fmt.Sprintf("Filter.%d.Value.%d", filterPtr+1, valuePtr+1)] = value
}
}
}
request["RegionId"] = client.RegionId
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var virtualBorderRouterNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
virtualBorderRouterNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_express_connect_virtual_border_routers", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.VirtualBorderRouterSet.VirtualBorderRouterType", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.VirtualBorderRouterSet.VirtualBorderRouterType", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if virtualBorderRouterNameRegex != nil && !virtualBorderRouterNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["VbrId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"access_point_id": object["AccessPointId"],
"activation_time": object["ActivationTime"],
"circuit_code": object["CircuitCode"],
"cloud_box_instance_id": object["CloudBoxInstanceId"],
"create_time": object["CreationTime"],
"description": object["Description"],
"detect_multiplier": formatInt(object["DetectMultiplier"]),
"ecc_id": object["EccId"],
"enable_ipv6": object["EnableIpv6"],
"local_gateway_ip": object["LocalGatewayIp"],
"local_ipv6_gateway_ip": object["LocalIpv6GatewayIp"],
"min_rx_interval": formatInt(object["MinRxInterval"]),
"min_tx_interval": formatInt(object["MinTxInterval"]),
"payment_vbr_expire_time": object["PConnVbrExpireTime"],
"peer_gateway_ip": object["PeerGatewayIp"],
"peer_ipv6_gateway_ip": object["PeerIpv6GatewayIp"],
"peering_ipv6_subnet_mask": object["PeeringIpv6SubnetMask"],
"peering_subnet_mask": object["PeeringSubnetMask"],
"physical_connection_business_status": object["PhysicalConnectionBusinessStatus"],
"physical_connection_id": object["PhysicalConnectionId"],
"physical_connection_owner_uid": object["PhysicalConnectionOwnerUid"],
"physical_connection_status": object["PhysicalConnectionStatus"],
"recovery_time": object["RecoveryTime"],
"route_table_id": object["RouteTableId"],
"status": object["Status"],
"termination_time": object["TerminationTime"],
"type": object["Type"],
"id": fmt.Sprint(object["VbrId"]),
"virtual_border_router_id": fmt.Sprint(object["VbrId"]),
"virtual_border_router_name": object["Name"],
"vlan_id": formatInt(object["VlanId"]),
"vlan_interface_id": object["VlanInterfaceId"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("routers", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/fc-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudFcCustomDomains() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudFcCustomDomainsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Computed: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"domains": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"domain_name": {
Type: schema.TypeString,
Computed: true,
},
"protocol": {
Type: schema.TypeString,
Computed: true,
},
"account_id": {
Type: schema.TypeString,
Computed: true,
},
"api_version": {
Type: schema.TypeString,
Computed: true,
},
"created_time": {
Type: schema.TypeString,
Computed: true,
},
"last_modified_time": {
Type: schema.TypeString,
Computed: true,
},
"route_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"path": {
Type: schema.TypeString,
Computed: true,
},
"service_name": {
Type: schema.TypeString,
Computed: true,
},
"function_name": {
Type: schema.TypeString,
Computed: true,
},
"qualifier": {
Type: schema.TypeString,
Computed: true,
},
"methods": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"cert_config": {
Type: schema.TypeList,
Computed: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cert_name": {
Type: schema.TypeString,
Computed: true,
},
"certificate": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudFcCustomDomainsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var ids []string
var names []string
var customDomainMappings []map[string]interface{}
nextToken := ""
for {
request := fc.NewListCustomDomainsInput()
if nextToken != "" {
request.NextToken = &nextToken
}
var requestInfo *fc.Client
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.ListCustomDomains(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_fc_custom_domains", "ListCustomDomains", FcGoSdk)
}
addDebug("ListCustomDomains", raw, requestInfo, request)
response, _ := raw.(*fc.ListCustomDomainsOutput)
if response.CustomDomains == nil || len(response.CustomDomains) < 1 {
break
}
for _, domain := range response.CustomDomains {
mapping := map[string]interface{}{
"id": *domain.DomainName,
"domain_name": *domain.DomainName,
"account_id": *domain.AccountID,
"protocol": *domain.Protocol,
"api_version": *domain.APIVersion,
"created_time": domain.CreatedTime,
"last_modified_time": domain.LastModifiedTime,
}
var routeConfigMappings []map[string]interface{}
for _, v := range domain.RouteConfig.Routes {
routeConfigMappings = append(routeConfigMappings, map[string]interface{}{
"path": *v.Path,
"service_name": *v.ServiceName,
"function_name": *v.FunctionName,
"qualifier": *v.Qualifier,
"methods": v.Methods,
})
}
mapping["route_config"] = routeConfigMappings
var certConfigMappings []map[string]interface{}
if domain.CertConfig != nil && domain.CertConfig.CertName != nil {
certConfigMappings = append(certConfigMappings, map[string]interface{}{
"cert_name": *domain.CertConfig.CertName,
"certificate": *domain.CertConfig.Certificate,
})
}
mapping["cert_config"] = certConfigMappings
// Filter by name.
nameRegex, ok := d.GetOk("name_regex")
if ok && nameRegex.(string) != "" {
var r *regexp.Regexp
if nameRegex != "" {
r, err = regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
}
if r != nil && !r.MatchString(mapping["domain_name"].(string)) {
continue
}
}
// Filter by id.
if len(idsMap) > 0 {
if _, ok := idsMap[*domain.DomainName]; !ok {
continue
}
}
customDomainMappings = append(customDomainMappings, mapping)
ids = append(ids, *domain.DomainName)
names = append(names, *domain.DomainName)
}
nextToken = ""
if response.NextToken != nil {
nextToken = *response.NextToken
}
if nextToken == "" {
break
}
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("domains", customDomainMappings); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), customDomainMappings)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/fc-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudFcFunctions() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudFcFunctionsRead,
Schema: map[string]*schema.Schema{
"service_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
// Computed values
"functions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"runtime": {
Type: schema.TypeString,
Computed: true,
},
"handler": {
Type: schema.TypeString,
Computed: true,
},
"timeout": {
Type: schema.TypeInt,
Computed: true,
},
"initializer": {
Type: schema.TypeString,
Computed: true,
},
"initialization_timeout": {
Type: schema.TypeInt,
Computed: true,
},
"memory_size": {
Type: schema.TypeInt,
Computed: true,
},
"environment_variables": {
Type: schema.TypeMap,
Computed: true,
},
"code_size": {
Type: schema.TypeInt,
Computed: true,
},
"code_checksum": {
Type: schema.TypeString,
Computed: true,
},
"instance_type": {
Type: schema.TypeString,
Computed: true,
},
"instance_concurrency": {
Type: schema.TypeInt,
Computed: true,
},
"ca_port": {
Type: schema.TypeInt,
Computed: true,
},
"creation_time": {
Type: schema.TypeString,
Computed: true,
},
"last_modification_time": {
Type: schema.TypeString,
Computed: true,
},
"custom_container_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"image": {
Type: schema.TypeString,
Computed: true,
},
"command": {
Type: schema.TypeString,
Computed: true,
},
"args": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudFcFunctionsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
serviceName := d.Get("service_name").(string)
var ids []string
var names []string
var functionMappings []map[string]interface{}
nextToken := ""
// ids
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
for {
request := fc.NewListFunctionsInput(serviceName)
if nextToken != "" {
request.NextToken = &nextToken
}
var requestInfo *fc.Client
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.ListFunctions(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_fc_functions", "ListFunctions", FcGoSdk)
}
addDebug("ListFunctions", raw, requestInfo, request)
response, _ := raw.(*fc.ListFunctionsOutput)
if response.Functions == nil || len(response.Functions) < 1 {
break
}
for _, function := range response.Functions {
mapping := map[string]interface{}{
"id": *function.FunctionID,
"name": *function.FunctionName,
"description": *function.Description,
"runtime": *function.Runtime,
"handler": *function.Handler,
"timeout": *function.Timeout,
"memory_size": *function.MemorySize,
"code_size": *function.CodeSize,
"code_checksum": *function.CodeChecksum,
"creation_time": *function.CreatedTime,
"last_modification_time": *function.LastModifiedTime,
"environment_variables": function.EnvironmentVariables,
}
if function.Initializer != nil {
mapping["initializer"] = *function.Initializer
}
if function.InitializationTimeout != nil {
mapping["initialization_timeout"] = *function.InitializationTimeout
}
if function.InstanceConcurrency != nil {
mapping["instance_concurrency"] = *function.InstanceConcurrency
}
if function.InstanceType != nil {
mapping["instance_type"] = *function.InstanceType
}
if function.CAPort != nil {
mapping["ca_port"] = *function.CAPort
}
if function.CustomContainerConfig != nil {
var cfgList []map[string]interface{}
cfg := map[string]interface{}{
"image": *function.CustomContainerConfig.Image,
}
if function.CustomContainerConfig.Command != nil {
cfg["command"] = *function.CustomContainerConfig.Command
}
if function.CustomContainerConfig.Args != nil {
cfg["args"] = *function.CustomContainerConfig.Args
}
cfgList = append(cfgList, cfg)
mapping["custom_container_config"] = cfgList
}
// Filter by function name.
nameRegex, ok := d.GetOk("name_regex")
if ok && nameRegex.(string) != "" {
var r *regexp.Regexp
if nameRegex != "" {
r, err = regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
}
if r != nil && !r.MatchString(mapping["name"].(string)) {
continue
}
}
// Filter by function id.
if len(idsMap) > 0 {
if _, ok := idsMap[*function.FunctionID]; !ok {
continue
}
}
functionMappings = append(functionMappings, mapping)
ids = append(ids, *function.FunctionID)
names = append(names, *function.FunctionName)
}
nextToken = ""
if response.NextToken != nil {
nextToken = *response.NextToken
}
if nextToken == "" {
break
}
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("functions", functionMappings); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), functionMappings)
}
return nil
}
package alicloud
import (
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudFcService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudFcServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudFcServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("FcServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
action := "OpenFcService"
request := map[string]interface{}{}
conn, err := meta.(*connectivity.AliyunClient).NewTeaRoaCommonClient(connectivity.OpenFcService)
if err != nil {
return WrapError(err)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequestWithAction(StringPointer(action), StringPointer("2020-03-10"), nil, StringPointer("POST"), StringPointer("AK"), String("/service/open"), nil, nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"QPS Limit Exceeded"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
addDebug(action, response, nil)
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ORDER.OPEND", "FC_INTL_ALREADY_OPENED", "SYSTEM.SALE_VALIDATE_NO_SPECIFIC_CODE_FAILED"}) {
d.SetId("FcServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_fc_service", action, AlibabaCloudSdkGoERROR)
}
d.SetId("FcServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/fc-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudFcServices() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudFcServicesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
// Computed values
"services": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"role": {
Type: schema.TypeString,
Computed: true,
},
"internet_access": {
Type: schema.TypeBool,
Computed: true,
},
"creation_time": {
Type: schema.TypeString,
Computed: true,
},
"last_modification_time": {
Type: schema.TypeString,
Computed: true,
},
"log_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"project": {
Type: schema.TypeString,
Computed: true,
},
"logstore": {
Type: schema.TypeString,
Computed: true,
},
},
},
MaxItems: 1,
},
"vpc_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"security_group_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
MaxItems: 1,
},
"nas_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"user_id": {
Type: schema.TypeInt,
Computed: true,
},
"group_id": {
Type: schema.TypeInt,
Computed: true,
},
"mount_points": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"server_addr": {
Type: schema.TypeString,
Computed: true,
},
"mount_dir": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
MaxItems: 1,
},
},
},
},
},
}
}
func dataSourceAlicloudFcServicesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var ids []string
var names []string
var serviceMappings []map[string]interface{}
nextToken := ""
for {
request := fc.NewListServicesInput()
if nextToken != "" {
request.NextToken = &nextToken
}
var requestInfo *fc.Client
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.ListServices(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_fc_services", "ListServices", FcGoSdk)
}
addDebug("ListServices", raw, requestInfo, request)
response, _ := raw.(*fc.ListServicesOutput)
if response.Services == nil || len(response.Services) < 1 {
break
}
// ids
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
for _, service := range response.Services {
mapping := map[string]interface{}{
"id": *service.ServiceID,
"name": *service.ServiceName,
"description": *service.Description,
"role": *service.Role,
"internet_access": *service.InternetAccess,
"creation_time": *service.CreatedTime,
"last_modification_time": *service.LastModifiedTime,
}
var logConfigMappings []map[string]interface{}
if service.LogConfig != nil {
logConfigMappings = append(logConfigMappings, map[string]interface{}{
"project": *service.LogConfig.Project,
"logstore": *service.LogConfig.Logstore,
})
}
mapping["log_config"] = logConfigMappings
var vpcConfigMappings []map[string]interface{}
if service.VPCConfig != nil &&
(service.VPCConfig.VPCID != nil || service.VPCConfig.SecurityGroupID != nil) {
vpcConfigMappings = append(vpcConfigMappings, map[string]interface{}{
"vpc_id": *service.VPCConfig.VPCID,
"vswitch_ids": service.VPCConfig.VSwitchIDs,
"security_group_id": *service.VPCConfig.SecurityGroupID,
})
}
mapping["vpc_config"] = vpcConfigMappings
var nasConfigMappings []map[string]interface{}
if service.NASConfig != nil {
nasConfig := map[string]interface{}{
"user_id": *service.NASConfig.UserID,
"group_id": *service.NASConfig.GroupID,
}
var mountPoints []map[string]interface{}
for _, v := range service.NASConfig.MountPoints {
mountPoints = append(mountPoints, map[string]interface{}{
"server_addr": v.ServerAddr,
"mount_dir": v.MountDir,
})
}
nasConfig["mount_points"] = mountPoints
nasConfigMappings = append(nasConfigMappings, nasConfig)
}
mapping["nas_config"] = nasConfigMappings
nameRegex, ok := d.GetOk("name_regex")
if ok && nameRegex.(string) != "" {
var r *regexp.Regexp
if nameRegex != "" {
r, err = regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
}
if r != nil && !r.MatchString(mapping["name"].(string)) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[*service.ServiceID]; !ok {
continue
}
}
serviceMappings = append(serviceMappings, mapping)
ids = append(ids, *service.ServiceID)
names = append(names, *service.ServiceName)
}
nextToken = ""
if response.NextToken != nil {
nextToken = *response.NextToken
}
if nextToken == "" {
break
}
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("services", serviceMappings); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), serviceMappings)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/fc-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudFcTriggers() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudFcTriggersRead,
Schema: map[string]*schema.Schema{
"service_name": {
Type: schema.TypeString,
Required: true,
},
"function_name": {
Type: schema.TypeString,
Required: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
// Computed values
"triggers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"source_arn": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"invocation_role": {
Type: schema.TypeString,
Computed: true,
},
"config": {
Type: schema.TypeString,
Computed: true,
},
"creation_time": {
Type: schema.TypeString,
Computed: true,
},
"last_modification_time": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudFcTriggersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
serviceName := d.Get("service_name").(string)
functionName := d.Get("function_name").(string)
var ids []string
var names []string
var triggerMappings []map[string]interface{}
nextToken := ""
// ids
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
for {
request := fc.NewListTriggersInput(serviceName, functionName)
if nextToken != "" {
request.NextToken = &nextToken
}
var requestInfo *fc.Client
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.ListTriggers(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_fc_triggers", "ListTriggers", FcGoSdk)
}
addDebug("ListTriggers", raw, requestInfo, request)
response, _ := raw.(*fc.ListTriggersOutput)
if len(response.Triggers) < 1 {
break
}
for _, trigger := range response.Triggers {
var sourceARN, invocationRole string
if trigger.SourceARN != nil {
sourceARN = *trigger.SourceARN
}
if trigger.InvocationRole != nil {
invocationRole = *trigger.InvocationRole
}
mapping := map[string]interface{}{
"id": *trigger.TriggerID,
"name": *trigger.TriggerName,
"source_arn": sourceARN,
"type": *trigger.TriggerType,
"invocation_role": invocationRole,
"config": string(trigger.RawTriggerConfig),
"creation_time": *trigger.CreatedTime,
"last_modification_time": *trigger.LastModifiedTime,
}
nameRegex, ok := d.GetOk("name_regex")
if ok && nameRegex.(string) != "" {
var r *regexp.Regexp
if nameRegex != "" {
r, err = regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
}
if r != nil && !r.MatchString(mapping["name"].(string)) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[*trigger.TriggerID]; !ok {
continue
}
}
triggerMappings = append(triggerMappings, mapping)
ids = append(ids, *trigger.TriggerID)
names = append(names, *trigger.TriggerName)
}
nextToken = ""
if response.NextToken != nil {
nextToken = *response.NextToken
}
if nextToken == "" {
break
}
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("triggers", triggerMappings); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), triggerMappings)
}
return nil
}
package alicloud
import (
"fmt"
"sort"
"github.com/aliyun/fc-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudFcZones() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudFcZonesRead,
Schema: map[string]*schema.Schema{
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"zones": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudFcZonesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var clientInfo *fc.Client
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
clientInfo = fcClient
return fcClient.GetAccountSettings(fc.NewGetAccountSettingsInput())
})
if err != nil {
return WrapError(fmt.Errorf("[API ERROR] FC GetAccountSettings: %#v", err))
}
addDebug("GetAccountSettings", raw, clientInfo)
out, _ := raw.(*fc.GetAccountSettingsOutput)
if out != nil && len(out.AvailableAZs) > 0 {
sort.Strings(out.AvailableAZs)
var zoneIds []string
var s []map[string]interface{}
for _, zoneId := range out.AvailableAZs {
mapping := map[string]interface{}{"id": zoneId}
s = append(s, mapping)
zoneIds = append(zoneIds, zoneId)
}
d.SetId(dataResourceIdHash(out.AvailableAZs))
if err := d.Set("zones", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", zoneIds); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
}
return nil
}
package alicloud
import (
"fmt"
"hash/crc64"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudFileCRC64Checksum() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudFileCRC64ChecksumRead,
Schema: map[string]*schema.Schema{
"filename": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"checksum": {
Type: schema.TypeString,
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func dataSourceAlicloudFileCRC64ChecksumRead(d *schema.ResourceData, meta interface{}) error {
filename := d.Get("filename")
file, err := loadFileContent(filename.(string))
if err != nil {
return WrapError(err)
}
table := crc64.MakeTable(crc64.ECMA)
checkSum := fmt.Sprintf("%d", crc64.Checksum(file, table))
d.Set("checksum", checkSum)
d.SetId(checkSum)
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), map[string]string{"checksum": checkSum})
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudFnFExecutions() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudFnFExecutionsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"flow_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Running", "Stopped", "Succeeded", "Failed", "TimedOut"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"executions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"execution_name": {
Type: schema.TypeString,
Computed: true,
},
"flow_name": {
Type: schema.TypeString,
Computed: true,
},
"input": {
Type: schema.TypeString,
Computed: true,
},
"output": {
Type: schema.TypeString,
Computed: true,
},
"started_time": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"stopped_time": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudFnFExecutionsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListExecutions"
request := make(map[string]interface{})
request["FlowName"] = d.Get("flow_name")
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
var objects []map[string]interface{}
var executionNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
executionNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewFnfClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-03-15"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_fnf_executions", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Executions", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Executions", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if executionNameRegex != nil && !executionNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["FlowName"], ":", item["Name"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["FlowName"], ":", object["Name"]),
"execution_name": fmt.Sprint(object["Name"]),
"flow_name": object["FlowName"],
"input": object["Input"],
"output": object["Output"],
"started_time": object["StartedTime"],
"stopped_time": object["StoppedTime"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["FlowName"], ":", object["Name"])
fnfService := FnfService{client}
getResp, err := fnfService.DescribeFnFExecution(id)
if err != nil {
return WrapError(err)
}
mapping["status"] = getResp["Status"]
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("executions", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudFnfFlows() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudFnfFlowsRead,
Schema: map[string]*schema.Schema{
"limit": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"flows": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"definition": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"flow_id": {
Type: schema.TypeString,
Computed: true,
},
"last_modified_time": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"role_arn": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudFnfFlowsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListFlows"
request := make(map[string]interface{})
if v, ok := d.GetOk("limit"); ok {
request["Limit"] = v
}
var objects []map[string]interface{}
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
nameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewFnfClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-03-15"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_fnf_flows", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Flows", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Flows", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if nameRegex != nil {
if !nameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Name"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"definition": object["Definition"],
"description": object["Description"],
"flow_id": object["Id"],
"last_modified_time": object["LastModifiedTime"],
"id": fmt.Sprint(object["Name"]),
"name": fmt.Sprint(object["Name"]),
"role_arn": object["RoleArn"],
"type": object["Type"],
}
ids = append(ids, fmt.Sprint(object["Name"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("flows", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudFnfSchedules() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudFnfSchedulesRead,
Schema: map[string]*schema.Schema{
"flow_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"limit": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"schedules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cron_expression": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"enable": {
Type: schema.TypeBool,
Computed: true,
},
"last_modified_time": {
Type: schema.TypeString,
Computed: true,
},
"payload": {
Type: schema.TypeString,
Computed: true,
},
"schedule_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"schedule_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudFnfSchedulesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListSchedules"
request := make(map[string]interface{})
request["FlowName"] = d.Get("flow_name")
if v, ok := d.GetOk("limit"); ok {
request["Limit"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var scheduleNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
scheduleNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewFnfClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-03-15"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_fnf_schedules", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Schedules", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Schedules", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if scheduleNameRegex != nil {
if !scheduleNameRegex.MatchString(fmt.Sprint(item["ScheduleName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ScheduleName"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"cron_expression": object["CronExpression"],
"description": object["Description"],
"enable": object["Enable"],
"last_modified_time": object["LastModifiedTime"],
"payload": object["Payload"],
"schedule_id": object["ScheduleId"],
"id": fmt.Sprint(object["ScheduleName"]),
"schedule_name": fmt.Sprint(object["ScheduleName"]),
}
ids = append(ids, fmt.Sprint(object["ScheduleName"]))
names = append(names, object["ScheduleName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("schedules", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"fmt"
"log"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudFnfService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudFnfServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudFnfServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("FnfServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateInstance"
request := map[string]interface{}{
"ProductCode": "fnf",
"SubscriptionType": "PayAsYouGo",
"Parameter.1.Code": "commodityCode",
"Parameter.1.Value": "fnf",
}
conn, err := client.NewBssopenapiClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-14"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"NotApplicable"}) {
conn.Endpoint = String(connectivity.BssOpenAPIEndpointInternational)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, nil)
if err != nil {
if IsExpectedErrors(err, []string{"SYSTEM.SALE_VALIDATE_NO_SPECIFIC_CODE_FAILED"}) {
d.SetId("FnfServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_fnf_service", "CreateInstance", AlibabaCloudSdkGoERROR)
}
if response["Success"] != nil && !response["Success"].(bool) {
if response["Code"] != nil && response["Code"].(string) == "SYSTEM.SALE_VALIDATE_NO_SPECIFIC_CODE_FAILED" {
d.SetId("FnfServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(fmt.Errorf("%s", response), DataDefaultErrorMsg, "alicloud_fnf_service", "CreateInstance", AlibabaCloudSdkGoERROR)
}
if response["Data"] != nil {
d.SetId(fmt.Sprintf("%v", response["Data"].(map[string]interface{})["OrderId"]))
} else {
log.Printf("[ERROR] When opening Fnf service, invoking CreateInstance got an nil data. Response: %s.", response)
d.SetId("FnfServiceHasBeenOpened")
}
d.Set("status", "Opened")
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudForwardEntries() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudForwardEntriesRead,
Schema: map[string]*schema.Schema{
"external_ip": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"external_port": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"forward_entry_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"forward_table_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"internal_ip": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"internal_port": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ip_protocol": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"any", "tcp", "udp"}, false),
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "Deleting", "Pending"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"entries": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"external_ip": {
Type: schema.TypeString,
Computed: true,
},
"external_port": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"forward_entry_id": {
Type: schema.TypeString,
Computed: true,
},
"forward_entry_name": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"internal_ip": {
Type: schema.TypeString,
Computed: true,
},
"internal_port": {
Type: schema.TypeString,
Computed: true,
},
"ip_protocol": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudForwardEntriesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeForwardTableEntries"
request := make(map[string]interface{})
if v, ok := d.GetOk("external_ip"); ok {
request["ExternalIp"] = v
}
if v, ok := d.GetOk("external_port"); ok {
request["ExternalPort"] = v
}
if v, ok := d.GetOk("forward_entry_name"); ok {
request["ForwardEntryName"] = v
}
request["ForwardTableId"] = d.Get("forward_table_id")
if v, ok := d.GetOk("internal_ip"); ok {
request["InternalIp"] = v
}
if v, ok := d.GetOk("internal_port"); ok {
request["InternalPort"] = v
}
if v, ok := d.GetOk("ip_protocol"); ok {
request["IpProtocol"] = v
}
request["RegionId"] = client.RegionId
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var forwardEntryNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
forwardEntryNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_forward_entries", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.ForwardTableEntries.ForwardTableEntry", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.ForwardTableEntries.ForwardTableEntry", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if forwardEntryNameRegex != nil {
if !forwardEntryNameRegex.MatchString(fmt.Sprint(item["ForwardEntryName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ForwardEntryId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"external_ip": object["ExternalIp"],
"external_port": object["ExternalPort"],
"id": fmt.Sprint(object["ForwardEntryId"]),
"forward_entry_id": fmt.Sprint(object["ForwardEntryId"]),
"forward_entry_name": object["ForwardEntryName"],
"name": object["ForwardEntryName"],
"internal_ip": object["InternalIp"],
"internal_port": object["InternalPort"],
"ip_protocol": object["IpProtocol"],
"status": object["Status"],
}
ids = append(ids, fmt.Sprint(object["ForwardEntryId"]))
names = append(names, object["ForwardEntryName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("entries", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudGaAccelerators() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudGaAcceleratorsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"active", "binding", "configuring", "deleting", "finacialLocked", "init", "unbinding"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"accelerators": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"accelerator_id": {
Type: schema.TypeString,
Computed: true,
},
"accelerator_name": {
Type: schema.TypeString,
Computed: true,
},
"basic_bandwidth_package": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"bandwidth": {
Type: schema.TypeInt,
Computed: true,
},
"bandwidth_type": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"cen_id": {
Type: schema.TypeString,
Computed: true,
},
"cross_domain_bandwidth_package": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"bandwidth": {
Type: schema.TypeInt,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"ddos_id": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"dns_name": {
Type: schema.TypeString,
Computed: true,
},
"expired_time": {
Type: schema.TypeInt,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"second_dns_name": {
Type: schema.TypeString,
Computed: true,
},
"spec": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudGaAcceleratorsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListAccelerators"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var acceleratorNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
acceleratorNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ga_accelerators", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Accelerators", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Accelerators", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if acceleratorNameRegex != nil {
if !acceleratorNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["AcceleratorId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["State"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["AcceleratorId"]),
"accelerator_id": fmt.Sprint(object["AcceleratorId"]),
"accelerator_name": object["Name"],
"cen_id": object["CenId"],
"ddos_id": object["DdosId"],
"description": object["Description"],
"dns_name": object["DnsName"],
"expired_time": formatInt(object["ExpiredTime"]),
"payment_type": object["InstanceChargeType"],
"second_dns_name": object["SecondDnsName"],
"spec": object["Spec"],
"status": object["State"],
}
basicBandwidthPackageSli := make([]map[string]interface{}, 0)
if v, ok := object["BasicBandwidthPackage"].(map[string]interface{}); ok && len(v) > 0 {
basicBandwidthPackage := object["BasicBandwidthPackage"]
basicBandwidthPackageMap := make(map[string]interface{})
basicBandwidthPackageMap["bandwidth"] = basicBandwidthPackage.(map[string]interface{})["Bandwidth"]
basicBandwidthPackageMap["bandwidth_type"] = basicBandwidthPackage.(map[string]interface{})["BandwidthType"]
basicBandwidthPackageMap["instance_id"] = basicBandwidthPackage.(map[string]interface{})["InstanceId"]
basicBandwidthPackageSli = append(basicBandwidthPackageSli, basicBandwidthPackageMap)
}
mapping["basic_bandwidth_package"] = basicBandwidthPackageSli
crossDomainBandwidthPackageSli := make([]map[string]interface{}, 0)
if v, ok := object["CrossDomainBandwidthPackage"].(map[string]interface{}); ok && len(v) > 0 {
crossDomainBandwidthPackage := object["CrossDomainBandwidthPackage"]
crossDomainBandwidthPackageMap := make(map[string]interface{})
crossDomainBandwidthPackageMap["bandwidth"] = crossDomainBandwidthPackage.(map[string]interface{})["Bandwidth"]
crossDomainBandwidthPackageMap["instance_id"] = crossDomainBandwidthPackage.(map[string]interface{})["InstanceId"]
crossDomainBandwidthPackageSli = append(crossDomainBandwidthPackageSli, crossDomainBandwidthPackageMap)
}
mapping["cross_domain_bandwidth_package"] = crossDomainBandwidthPackageSli
ids = append(ids, fmt.Sprint(object["AcceleratorId"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("accelerators", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudGaAcls() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudGaAclsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"acl_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"active", "configuring", "deleting", "init"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"acls": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"acl_entries": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"entry": {
Type: schema.TypeString,
Computed: true,
},
"entry_description": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"acl_id": {
Type: schema.TypeString,
Computed: true,
},
"acl_name": {
Type: schema.TypeString,
Computed: true,
},
"address_ip_version": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudGaAclsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListAcls"
request := make(map[string]interface{})
if v, ok := d.GetOk("acl_name"); ok {
request["AclName"] = v
}
request["RegionId"] = client.RegionId
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var aclNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
aclNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ga_acls", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Acls", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Acls", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if aclNameRegex != nil && !aclNameRegex.MatchString(fmt.Sprint(item["AclName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["AclId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["AclStatus"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["AclId"]),
"acl_id": fmt.Sprint(object["AclId"]),
"acl_name": object["AclName"],
"address_ip_version": object["AddressIPVersion"],
"status": object["AclStatus"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["AclName"])
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["AclId"])
gaService := GaService{client}
getResp, err := gaService.DescribeGaAcl(id)
if err != nil {
return WrapError(err)
}
if v, ok := getResp["AclEntries"].([]interface{}); ok {
aclEntries := make([]map[string]interface{}, 0)
for _, val := range v {
item := val.(map[string]interface{})
temp := map[string]interface{}{
"entry": item["Entry"],
"entry_description": item["EntryDescription"],
}
aclEntries = append(aclEntries, temp)
}
mapping["acl_entries"] = aclEntries
}
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("acls", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudGaAdditionalCertificates() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudGaAdditionalCertificatesRead,
Schema: map[string]*schema.Schema{
"accelerator_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"listener_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"certificates": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"accelerator_id": {
Type: schema.TypeString,
Computed: true,
},
"certificate_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"domain": {
Type: schema.TypeString,
Computed: true,
},
"listener_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudGaAdditionalCertificatesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListListenerCertificates"
request := make(map[string]interface{})
request["AcceleratorId"] = d.Get("accelerator_id")
request["ListenerId"] = d.Get("listener_id")
request["RegionId"] = client.RegionId
request["Role"] = "additional"
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ga_additional_certificates", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Certificates", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Certificates", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(request["AcceleratorId"], ":", request["ListenerId"], ":", item["Domain"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"accelerator_id": request["AcceleratorId"],
"certificate_id": object["CertificateId"],
"id": fmt.Sprint(request["AcceleratorId"], ":", request["ListenerId"], ":", object["Domain"]),
"domain": fmt.Sprint(object["Domain"]),
"listener_id": request["ListenerId"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("certificates", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudGaBandwidthPackages() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudGaBandwidthPackagesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"active", "binded", "binding", "finacialLocked", "init", "unbinding", "updating"}, false),
},
"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Basic", "CrossDomain"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"packages": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"bandwidth": {
Type: schema.TypeInt,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"bandwidth_package_id": {
Type: schema.TypeString,
Computed: true,
},
"bandwidth_package_name": {
Type: schema.TypeString,
Computed: true,
},
"bandwidth_type": {
Type: schema.TypeString,
Computed: true,
},
"cbn_geographic_region_ida": {
Type: schema.TypeString,
Computed: true,
},
"cbn_geographic_region_idb": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"expired_time": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudGaBandwidthPackagesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListBandwidthPackages"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("status"); ok {
request["State"] = v
}
if v, ok := d.GetOk("type"); ok {
request["Type"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var bandwidthPackageNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
bandwidthPackageNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ga_bandwidth_packages", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.BandwidthPackages", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.BandwidthPackages", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if bandwidthPackageNameRegex != nil {
if !bandwidthPackageNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["BandwidthPackageId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"bandwidth": formatInt(object["Bandwidth"]),
"id": fmt.Sprint(object["BandwidthPackageId"]),
"bandwidth_package_id": fmt.Sprint(object["BandwidthPackageId"]),
"bandwidth_package_name": object["Name"],
"bandwidth_type": object["BandwidthType"],
"cbn_geographic_region_ida": object["CbnGeographicRegionIdA"],
"cbn_geographic_region_idb": object["CbnGeographicRegionIdB"],
"description": object["Description"],
"expired_time": object["ExpiredTime"],
"payment_type": convertGaBandwidthPackagePaymentTypeResponse(object["ChargeType"].(string)),
"type": object["Type"],
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["BandwidthPackageId"]))
names = append(names, object["Name"])
s = append(s, mapping)
continue
}
gaService := GaService{client}
id := fmt.Sprint(object["BandwidthPackageId"])
getResp, err := gaService.DescribeGaBandwidthPackage(id)
if err != nil {
return WrapError(err)
}
if statusOk && status != "" && status != getResp["State"].(string) {
continue
}
mapping["status"] = getResp["State"]
ids = append(ids, fmt.Sprint(object["BandwidthPackageId"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("packages", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudGaEndpointGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudGaEndpointGroupsRead,
Schema: map[string]*schema.Schema{
"accelerator_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"endpoint_group_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "default",
ValidateFunc: validation.StringInSlice([]string{"default", "virtual"}, false),
},
"listener_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"active", "configuring", "creating", "init"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Computed: true,
},
"endpoint_configurations": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enable_clientip_preservation": {
Type: schema.TypeBool,
Computed: true,
},
"endpoint": {
Type: schema.TypeString,
Computed: true,
},
"probe_port": {
Type: schema.TypeInt,
Computed: true,
},
"probe_protocol": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"weight": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"endpoint_group_id": {
Type: schema.TypeString,
Computed: true,
},
"endpoint_group_region": {
Type: schema.TypeString,
Computed: true,
},
"health_check_interval_seconds": {
Type: schema.TypeInt,
Computed: true,
},
"health_check_path": {
Type: schema.TypeString,
Computed: true,
},
"health_check_port": {
Type: schema.TypeInt,
Computed: true,
},
"health_check_protocol": {
Type: schema.TypeString,
Computed: true,
},
"listener_id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"port_overrides": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"endpoint_port": {
Type: schema.TypeInt,
Computed: true,
},
"listener_port": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"threshold_count": {
Type: schema.TypeInt,
Computed: true,
},
"traffic_percentage": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudGaEndpointGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListEndpointGroups"
request := make(map[string]interface{})
request["AcceleratorId"] = d.Get("accelerator_id")
if v, ok := d.GetOk("endpoint_group_type"); ok {
request["EndpointGroupType"] = v
}
if v, ok := d.GetOk("listener_id"); ok {
request["ListenerId"] = v
}
request["RegionId"] = client.RegionId
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
nameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ga_endpoint_groups", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.EndpointGroups", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.EndpointGroups", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if nameRegex != nil {
if !nameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["EndpointGroupId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["State"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"description": object["Description"],
"id": fmt.Sprint(object["EndpointGroupId"]),
"endpoint_group_id": fmt.Sprint(object["EndpointGroupId"]),
"endpoint_group_region": object["EndpointGroupRegion"],
"health_check_interval_seconds": formatInt(object["HealthCheckIntervalSeconds"]),
"health_check_path": object["HealthCheckPath"],
"health_check_port": formatInt(object["HealthCheckPort"]),
"health_check_protocol": object["HealthCheckProtocol"],
"listener_id": object["ListenerId"],
"name": object["Name"],
"status": object["State"],
"threshold_count": formatInt(object["ThresholdCount"]),
"traffic_percentage": formatInt(object["TrafficPercentage"]),
}
endpointConfigurations := make([]map[string]interface{}, 0)
if endpointConfigurationsList, ok := object["EndpointConfigurations"].([]interface{}); ok {
for _, v := range endpointConfigurationsList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"enable_clientip_preservation": m1["EnableClientIPPreservation"],
"endpoint": m1["Endpoint"],
"probe_port": m1["ProbePort"],
"probe_protocol": m1["ProbeProtocol"],
"type": m1["Type"],
"weight": m1["Weight"],
}
endpointConfigurations = append(endpointConfigurations, temp1)
}
}
}
mapping["endpoint_configurations"] = endpointConfigurations
portOverrides := make([]map[string]interface{}, 0)
if portOverridesList, ok := object["PortOverrides"].([]interface{}); ok {
for _, v := range portOverridesList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"endpoint_port": m1["EndpointPort"],
"listener_port": m1["ListenerPort"],
}
portOverrides = append(portOverrides, temp1)
}
}
}
mapping["port_overrides"] = portOverrides
ids = append(ids, fmt.Sprint(object["EndpointGroupId"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudGaForwardingRules() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudGaForwardingRulesRead,
Schema: map[string]*schema.Schema{
"accelerator_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"listener_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"active", "configuring"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"forwarding_rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"priority": {
Type: schema.TypeInt,
Computed: true,
},
"forwarding_rule_id": {
Type: schema.TypeString,
Computed: true,
},
"forwarding_rule_name": {
Type: schema.TypeString,
Computed: true,
},
"listener_id": {
Type: schema.TypeString,
Computed: true,
},
"forwarding_rule_status": {
Type: schema.TypeString,
Computed: true,
},
"rule_conditions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"rule_condition_type": {
Type: schema.TypeString,
Computed: true,
},
"path_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"values": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
},
},
"host_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"values": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
},
},
},
},
},
"rule_actions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"order": {
Type: schema.TypeInt,
Computed: true,
},
"rule_action_type": {
Type: schema.TypeString,
Computed: true,
},
"forward_group_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"server_group_tuples": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"endpoint_group_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
},
},
"id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudGaForwardingRulesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListForwardingRules"
request := make(map[string]interface{})
request["AcceleratorId"] = d.Get("accelerator_id")
request["ListenerId"] = d.Get("listener_id")
request["RegionId"] = client.RegionId
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ga_forwarding_rules", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.ForwardingRules", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.ForwardingRules", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ForwardingRuleId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["ForwardingRuleStatus"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
ruleConditions := make([]map[string]interface{}, 0)
for _, v := range object["RuleConditions"].([]interface{}) {
ruleCondition := map[string]interface{}{}
v := v.(map[string]interface{})
ruleCondition["rule_condition_type"] = v["RuleConditionType"]
if v["PathConfig"].(map[string]interface{})["Values"] != nil {
ruleCondition["path_config"] = []map[string]interface{}{
{
"values": v["PathConfig"].(map[string]interface{})["Values"],
},
}
}
if v["HostConfig"].(map[string]interface{})["Values"] != nil {
ruleCondition["host_config"] = []map[string]interface{}{
{
"values": v["HostConfig"].(map[string]interface{})["Values"],
},
}
}
ruleConditions = append(ruleConditions, ruleCondition)
}
ruleActions := make([]map[string]interface{}, 0)
for _, v := range object["RuleActions"].([]interface{}) {
v := v.(map[string]interface{})
ruleAction := map[string]interface{}{}
ruleAction["order"] = v["Order"]
ruleAction["rule_action_type"] = v["RuleActionType"]
serverGroupTuples := make([]map[string]interface{}, 0)
for _, serverGroupTuple := range v["ForwardGroupConfig"].(map[string]interface{})["ServerGroupTuples"].([]interface{}) {
serverGroupTuples = append(serverGroupTuples, map[string]interface{}{
"endpoint_group_id": serverGroupTuple.(map[string]interface{})["EndpointGroupId"],
})
}
ruleAction["forward_group_config"] = []map[string]interface{}{
{
"server_group_tuples": serverGroupTuples,
},
}
ruleActions = append(ruleActions, ruleAction)
}
mapping := map[string]interface{}{
"priority": object["Priority"],
"forwarding_rule_id": object["ForwardingRuleId"],
"id": fmt.Sprint(d.Get("accelerator_id"), ":", object["ListenerId"], ":", object["ForwardingRuleId"]),
"forwarding_rule_name": object["ForwardingRuleName"],
"forwarding_rule_status": object["ForwardingRuleStatus"],
"rule_conditions": ruleConditions,
"rule_actions": ruleActions,
"listener_id": object["ListenerId"],
}
ids = append(ids, fmt.Sprint(object["ForwardingRuleId"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("forwarding_rules", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudGaIpSets() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudGaIpSetsRead,
Schema: map[string]*schema.Schema{
"accelerator_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"active", "deleting", "init", "updating"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"sets": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"accelerate_region_id": {
Type: schema.TypeString,
Computed: true,
},
"bandwidth": {
Type: schema.TypeInt,
Computed: true,
},
"ip_address_list": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"ip_set_id": {
Type: schema.TypeString,
Computed: true,
},
"ip_version": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudGaIpSetsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListIpSets"
request := make(map[string]interface{})
request["AcceleratorId"] = d.Get("accelerator_id")
request["RegionId"] = client.RegionId
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ga_ip_sets", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.IpSets", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.IpSets", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["IpSetId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["State"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"accelerate_region_id": object["AccelerateRegionId"],
"bandwidth": formatInt(object["Bandwidth"]),
"ip_address_list": object["IpAddressList"],
"id": fmt.Sprint(object["IpSetId"]),
"ip_set_id": fmt.Sprint(object["IpSetId"]),
"ip_version": object["IpVersion"],
"status": object["State"],
}
ids = append(ids, fmt.Sprint(object["IpSetId"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("sets", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudGaListeners() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudGaListenersRead,
Schema: map[string]*schema.Schema{
"accelerator_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"active", "configuring", "creating"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"listeners": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"certificates": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"client_affinity": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"listener_id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"port_ranges": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"from_port": {
Type: schema.TypeInt,
Computed: true,
},
"to_port": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"protocol": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudGaListenersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListListeners"
request := make(map[string]interface{})
request["AcceleratorId"] = d.Get("accelerator_id")
request["RegionId"] = client.RegionId
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
nameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ga_listeners", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Listeners", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Listeners", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if nameRegex != nil {
if !nameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ListenerId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["State"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"client_affinity": object["ClientAffinity"],
"description": object["Description"],
"id": fmt.Sprint(object["ListenerId"]),
"listener_id": fmt.Sprint(object["ListenerId"]),
"name": object["Name"],
"protocol": object["Protocol"],
"status": object["State"],
}
certificates := make([]map[string]interface{}, 0)
if certificatesList, ok := object["Certificates"].([]interface{}); ok {
for _, v := range certificatesList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"id": m1["Id"],
"type": m1["Type"],
}
certificates = append(certificates, temp1)
}
}
}
mapping["certificates"] = certificates
portRanges := make([]map[string]interface{}, 0)
if portRangesList, ok := object["PortRanges"].([]interface{}); ok {
for _, v := range portRangesList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"from_port": m1["FromPort"],
"to_port": m1["ToPort"],
}
portRanges = append(portRanges, temp1)
}
}
}
mapping["port_ranges"] = portRanges
ids = append(ids, fmt.Sprint(object["ListenerId"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("listeners", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudGpdbAccounts() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudGpdbAccountsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"db_instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Creating", "Deleting"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"accounts": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"account_name": {
Type: schema.TypeString,
Computed: true,
},
"db_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudGpdbAccountsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeAccounts"
request := make(map[string]interface{})
request["DBInstanceId"] = d.Get("db_instance_id")
var objects []map[string]interface{}
var accountNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
accountNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewGpdbClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-05-03"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_gpdb_accounts", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Accounts.DBInstanceAccount", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Accounts.DBInstanceAccount", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if accountNameRegex != nil && !accountNameRegex.MatchString(fmt.Sprint(item["AccountName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DBInstanceId"], ":", item["AccountName"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["AccountStatus"].(string) {
continue
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"account_description": object["AccountDescription"],
"id": fmt.Sprint(object["DBInstanceId"], ":", object["AccountName"]),
"account_name": fmt.Sprint(object["AccountName"]),
"db_instance_id": object["DBInstanceId"],
"status": convertGpdbAccountStatusResponse(object["AccountStatus"]),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["AccountName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("accounts", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/gpdb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudGpdbInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudGpdbInstancesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"availability_zone": {
Type: schema.TypeString,
Optional: true,
},
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
},
"tags": tagsSchema(),
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
MinItems: 1,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"availability_zone": {
Type: schema.TypeString,
Computed: true,
},
"creation_time": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"engine": {
Type: schema.TypeString,
Computed: true,
},
"engine_version": {
Type: schema.TypeString,
Computed: true,
},
"instance_class": {
Type: schema.TypeString,
Computed: true,
},
"instance_group_count": {
Type: schema.TypeString,
Computed: true,
},
"instance_network_type": {
Type: schema.TypeString,
Computed: true,
},
"charge_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudGpdbInstancesRead(d *schema.ResourceData, meta interface{}) error {
// name regex
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
if r, err := regexp.Compile(v.(string)); err == nil {
nameRegex = r
} else {
return WrapError(err)
}
}
// availability zone
availabilityZone := d.Get("availability_zone").(string)
// vSwitchId
vSwitchId := d.Get("vswitch_id").(string)
// ids
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[Trim(vv.(string))] = Trim(vv.(string))
}
}
client := meta.(*connectivity.AliyunClient)
gpdbService := GpdbService{client}
request := gpdb.CreateDescribeDBInstancesRequest()
request.RegionId = client.RegionId
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
if v, ok := d.GetOk("tags"); ok {
var reqTags []gpdb.DescribeDBInstancesTag
for key, value := range v.(map[string]interface{}) {
reqTags = append(reqTags, gpdb.DescribeDBInstancesTag{
Key: key,
Value: value.(string),
})
}
request.Tag = &reqTags
}
var dbi []gpdb.DBInstanceAttribute
for {
raw, err := client.WithGpdbClient(func(gpdbClient *gpdb.Client) (interface{}, error) {
return gpdbClient.DescribeDBInstances(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_gpdb_instances", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*gpdb.DescribeDBInstancesResponse)
addDebug(request.GetActionName(), response)
if len(response.Items.DBInstance) < 1 {
break
}
for _, item := range response.Items.DBInstance {
// filter by description regex
if nameRegex != nil {
if !nameRegex.MatchString(item.DBInstanceDescription) {
continue
}
}
// filter by instance id
if len(idsMap) > 0 {
if _, ok := idsMap[item.DBInstanceId]; !ok {
continue
}
}
// filter by availability zone
if availabilityZone != "" && availabilityZone != strings.ToLower(string(item.ZoneId)) {
continue
}
// filter by vSwitchId
if vSwitchId != "" && vSwitchId != string(item.VSwitchId) {
continue
}
// describe instance
instanceAttribute, err := gpdbService.DescribeGpdbInstance(item.DBInstanceId)
if err != nil {
return WrapError(err)
}
dbi = append(dbi, instanceAttribute)
}
if len(response.Items.DBInstance) < PageSizeLarge {
break
}
if page, err := getNextpageNumber(request.PageNumber); err != nil {
return WrapError(err)
} else {
request.PageNumber = page
}
}
return describeGpdbInstances(d, dbi)
}
func describeGpdbInstances(d *schema.ResourceData, dbi []gpdb.DBInstanceAttribute) error {
var ids []string
var names []string
var instances []map[string]interface{}
for _, item := range dbi {
mapping := map[string]interface{}{
"id": item.DBInstanceId,
"description": item.DBInstanceDescription,
"region_id": item.RegionId,
"availability_zone": item.ZoneId,
"creation_time": item.CreationTime,
"status": item.DBInstanceStatus,
"engine": item.Engine,
"engine_version": item.EngineVersion,
"charge_type": item.PayType,
"instance_class": item.DBInstanceClass,
"instance_group_count": item.DBInstanceGroupCount,
"instance_network_type": item.InstanceNetworkType,
}
ids = append(ids, item.DBInstanceId)
names = append(names, item.DBInstanceDescription)
instances = append(instances, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("instances", instances); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), instances)
}
return nil
}
package alicloud
import (
"fmt"
"sort"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/services/gpdb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudGpdbZones() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudGpdbZonesRead,
Schema: map[string]*schema.Schema{
"multi": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"zones": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"multi_zone_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
},
}
}
func dataSourceAlicloudGpdbZonesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
multi := d.Get("multi").(bool)
var zoneIds []string
request := gpdb.CreateDescribeRegionsRequest()
request.RegionId = client.RegionId
raw, err := client.WithGpdbClient(func(gpdbClient *gpdb.Client) (interface{}, error) {
return gpdbClient.DescribeRegions(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_gpdb_zones", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*gpdb.DescribeRegionsResponse)
if len(response.Regions.Region) <= 0 {
return WrapError(fmt.Errorf("[ERROR] There is no available region for gpdb."))
}
for _, r := range response.Regions.Region {
for _, zoneId := range r.Zones.Zone {
if multi && strings.Contains(zoneId.ZoneId, MULTI_IZ_SYMBOL) && r.RegionId == string(client.Region) {
zoneIds = append(zoneIds, zoneId.ZoneId)
continue
}
if !multi && !strings.Contains(zoneId.ZoneId, MULTI_IZ_SYMBOL) && r.RegionId == string(client.Region) {
zoneIds = append(zoneIds, zoneId.ZoneId)
continue
}
}
}
if len(zoneIds) > 0 {
sort.Strings(zoneIds)
}
var s []map[string]interface{}
if !multi {
for _, zoneId := range zoneIds {
mapping := map[string]interface{}{"id": zoneId}
s = append(s, mapping)
}
} else {
for _, zoneId := range zoneIds {
mapping := map[string]interface{}{
"id": zoneId,
"multi_zone_ids": splitMultiZoneId(zoneId),
}
s = append(s, mapping)
}
}
d.SetId(dataResourceIdHash(zoneIds))
if err := d.Set("zones", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", zoneIds); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudGraphDatabaseDbInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudGraphDatabaseDbInstancesRead,
Schema: map[string]*schema.Schema{
"db_instance_description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Creating", "Running", "Deleting", "DBInstanceClassChanging", "NetAddressCreating", "NetAddressDeleting"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"connection_string": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"current_minor_version": {
Type: schema.TypeString,
Computed: true,
},
"db_instance_category": {
Type: schema.TypeString,
Computed: true,
},
"db_instance_cpu": {
Type: schema.TypeString,
Computed: true,
},
"db_instance_description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"db_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"db_instance_memory": {
Type: schema.TypeString,
Computed: true,
},
"db_instance_network_type": {
Type: schema.TypeString,
Computed: true,
},
"db_instance_storage_type": {
Type: schema.TypeString,
Computed: true,
},
"db_instance_type": {
Type: schema.TypeString,
Computed: true,
},
"db_node_class": {
Type: schema.TypeString,
Computed: true,
},
"db_node_count": {
Type: schema.TypeString,
Computed: true,
},
"db_node_storage": {
Type: schema.TypeString,
Computed: true,
},
"db_version": {
Type: schema.TypeString,
Computed: true,
},
"expire_time": {
Type: schema.TypeString,
Computed: true,
},
"expired": {
Type: schema.TypeString,
Computed: true,
},
"latest_minor_version": {
Type: schema.TypeString,
Computed: true,
},
"lock_mode": {
Type: schema.TypeString,
Computed: true,
},
"lock_reason": {
Type: schema.TypeString,
Computed: true,
},
"maintain_time": {
Type: schema.TypeString,
Computed: true,
},
"master_db_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeInt,
Computed: true,
},
"public_connection_string": {
Type: schema.TypeString,
Computed: true,
},
"public_port": {
Type: schema.TypeInt,
Computed: true,
},
"read_only_db_instance_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
"db_instance_ip_array": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"db_instance_ip_array_attribute": {
Type: schema.TypeString,
Optional: true,
},
"db_instance_ip_array_name": {
Type: schema.TypeString,
Optional: true,
},
"security_ips": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudGraphDatabaseDbInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDBInstances"
request := make(map[string]interface{})
if v, ok := d.GetOk("db_instance_description"); ok {
request["DBInstanceDescription"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("status"); ok {
request["DBInstanceStatus"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewGdsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-03"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_graph_database_db_instances", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Items.DBInstance", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Items.DBInstance", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DBInstanceId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": object["CreateTime"],
"db_instance_category": object["Category"],
"db_instance_description": object["DBInstanceDescription"],
"id": fmt.Sprint(object["DBInstanceId"]),
"db_instance_id": fmt.Sprint(object["DBInstanceId"]),
"db_instance_type": object["DBInstanceType"],
"db_node_class": object["DBNodeClass"],
"db_node_count": fmt.Sprint(object["DBNodeCount"]),
"db_node_storage": fmt.Sprint(object["DBNodeStorage"]),
"db_version": object["DBVersion"],
"expire_time": object["ExpireTime"],
"expired": fmt.Sprint(object["Expired"]),
"lock_mode": object["LockMode"],
"lock_reason": object["LockReason"],
"master_db_instance_id": object["MasterInstanceId"],
"payment_type": convertGraphDatabaseDbInstancePaymentTypeResponse(object["PayType"]),
"status": object["DBInstanceStatus"],
"vswitch_id": object["VSwitchId"],
"vpc_id": object["VpcId"],
"zone_id": object["ZoneId"],
}
if v := object["ReadOnlyDBInstanceIds"].(map[string]interface{})["ReadOnlyDBInstanceId"].([]interface{}); len(v) > 0 {
mapping["read_only_db_instance_ids"] = v[0].(map[string]interface{})["DBInstanceId"]
}
ids = append(ids, fmt.Sprint(mapping["id"]))
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["DBInstanceId"])
gdbService := GdbService{client}
getResp, err := gdbService.DescribeGraphDatabaseDbInstance(id)
if err != nil {
return WrapError(err)
}
mapping["connection_string"] = getResp["ConnectionString"]
mapping["current_minor_version"] = getResp["CurrentMinorVersion"]
mapping["db_instance_cpu"] = getResp["DBInstanceCPU"]
mapping["db_instance_memory"] = getResp["DBInstanceMemory"]
mapping["db_instance_network_type"] = getResp["DBInstanceNetworkType"]
mapping["db_instance_storage_type"] = getResp["DBInstanceStorageType"]
mapping["latest_minor_version"] = getResp["LatestMinorVersion"]
mapping["maintain_time"] = getResp["MaintainTime"]
if DBInstanceIPArray, ok := getResp["DBInstanceIPArray"]; ok {
DBInstanceIPArrayAry, ok := DBInstanceIPArray.([]interface{})
if ok && len(DBInstanceIPArrayAry) > 0 {
DBInstanceIPArraySli := make([]map[string]interface{}, 0)
for _, DBInstanceIPArrayArg := range DBInstanceIPArrayAry {
DBInstanceIPArrayMap := make(map[string]interface{})
DBInstanceIPArrayMap["security_ips"] = DBInstanceIPArrayArg.(map[string]interface{})["SecurityIps"]
DBInstanceIPArrayMap["db_instance_ip_array_name"] = DBInstanceIPArrayArg.(map[string]interface{})["DBInstanceIPArrayName"]
if v, ok := DBInstanceIPArrayArg.(map[string]interface{})["DBInstanceIPArrayAttribute"]; ok {
DBInstanceIPArrayMap["db_instance_ip_array_attribute"] = v
}
DBInstanceIPArraySli = append(DBInstanceIPArraySli, DBInstanceIPArrayMap)
}
mapping["db_instance_ip_array"] = DBInstanceIPArraySli
}
}
if v, ok := getResp["Port"]; ok && v.(string) != "" {
mapping["port"] = formatInt(v)
}
mapping["public_connection_string"] = getResp["PublicConnectionString"]
if v, ok := getResp["PublicPort"]; ok && fmt.Sprint(v) != "0" {
mapping["public_port"] = formatInt(v)
}
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudHavips() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudHavipsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "InUse", "Pending"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"havips": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"associated_eip_addresses": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"associated_instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"havip_id": {
Type: schema.TypeString,
Computed: true,
},
"havip_name": {
Type: schema.TypeString,
Computed: true,
},
"ip_address": {
Type: schema.TypeString,
Computed: true,
},
"master_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudHavipsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeHaVips"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var havipNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
havipNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_havips", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.HaVips.HaVip", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.HaVips.HaVip", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if havipNameRegex != nil {
if !havipNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["HaVipId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"associated_eip_addresses": object["AssociatedEipAddresses"].(map[string]interface{})["associatedEipAddresse"],
"associated_instances": object["AssociatedInstances"].(map[string]interface{})["associatedInstance"],
"description": object["Description"],
"id": fmt.Sprint(object["HaVipId"]),
"havip_id": fmt.Sprint(object["HaVipId"]),
"havip_name": object["Name"],
"ip_address": object["IpAddress"],
"master_instance_id": object["MasterInstanceId"],
"status": object["Status"],
"vswitch_id": object["VSwitchId"],
"vpc_id": object["VpcId"],
}
ids = append(ids, fmt.Sprint(object["HaVipId"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("havips", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"strings"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/hbase"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
mapset "github.com/deckarep/golang-set"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudHBaseInstanceTypes() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudHBaseInstanceTypesRead,
Schema: map[string]*schema.Schema{
"charge_type": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{string(PostPaid), string(PrePaid)}, true),
Optional: true,
Default: PostPaid,
},
"region_id": {
Type: schema.TypeString,
Optional: true,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
},
"engine": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"singlehbase", "hbase", "hbaseue", "bds"}, false),
Optional: true,
},
"version": {
Type: schema.TypeString,
Optional: true,
},
"instance_type": {
Type: schema.TypeString,
Optional: true,
},
"disk_type": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"cloud_ssd", "cloud_essd_pl1", "cloud_efficiency", "local_hdd_pro", "local_ssd_pro"}, false),
Optional: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"types": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"value": {
Type: schema.TypeString,
Computed: true,
},
"cpu_size": {
Type: schema.TypeInt,
Computed: true,
},
"mem_size": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"master_instance_types": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"instance_type": {
Type: schema.TypeString,
Computed: true,
},
"cpu_size": {
Type: schema.TypeInt,
Computed: true,
},
"mem_size": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"core_instance_types": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"zone": {
Type: schema.TypeString,
Computed: true,
},
"engine": {
Type: schema.TypeString,
Computed: true,
},
"version": {
Type: schema.TypeString,
Computed: true,
},
"category": {
Type: schema.TypeString,
Computed: true,
},
"storage_type": {
Type: schema.TypeString,
Computed: true,
},
"instance_type": {
Type: schema.TypeString,
Computed: true,
},
"cpu_size": {
Type: schema.TypeInt,
Computed: true,
},
"mem_size": {
Type: schema.TypeInt,
Computed: true,
},
"max_core_count": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudHBaseInstanceTypesRead(d *schema.ResourceData, meta interface{}) error {
response, err := describeAvaiableResource(d, meta)
if err != nil {
return WrapErrorf(err, "describeAvaiableResource failed")
}
var ids []string
var masterInstanceTypes []map[string]interface{}
typeSet := mapset.NewSet()
var types []map[string]interface{}
masterTypeSet := mapset.NewSet()
var coreInstanceTypes []map[string]interface{}
for _, zone := range response.AvailableZones.AvailableZone {
for _, master := range zone.MasterResources.MasterResource {
if masterTypeSet.Contains(master.InstanceType) {
continue
}
e := map[string]interface{}{
"value": master.InstanceType,
"cpu_size": master.InstanceTypeDetail.Cpu,
"mem_size": master.InstanceTypeDetail.Mem,
}
types = append(types, e)
e = map[string]interface{}{
"instance_type": master.InstanceType,
"cpu_size": master.InstanceTypeDetail.Cpu,
"mem_size": master.InstanceTypeDetail.Mem,
}
masterInstanceTypes = append(masterInstanceTypes, e)
masterTypeSet.Add(master.InstanceType)
if !typeSet.Contains(master.InstanceType) {
typeSet.Add(master.InstanceType)
}
}
for _, engine := range zone.SupportedEngines.SupportedEngine {
for _, verion := range engine.SupportedEngineVersions.SupportedEngineVersion {
for _, category := range verion.SupportedCategories.SupportedCategoriesItem {
for _, storageType := range category.SupportedStorageTypes.SupportedStorageType {
for _, coreResource := range storageType.CoreResources.CoreResource {
if !typeSet.Contains(coreResource.InstanceType) {
typeSet.Add(coreResource.InstanceType)
}
e := map[string]interface{}{
"zone": zone.ZoneId,
"engine": engine.Engine,
"version": verion.Version,
"category": category.Category,
"storage_type": storageType.StorageType,
"instance_type": coreResource.InstanceType,
"cpu_size": coreResource.InstanceTypeDetail.Cpu,
"mem_size": coreResource.InstanceTypeDetail.Mem,
"max_core_count": coreResource.MaxCoreCount,
}
coreInstanceTypes = append(coreInstanceTypes, e)
}
}
}
}
}
}
for _, v := range typeSet.ToSlice() {
ids = append(ids, v.(string))
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("types", types); err != nil {
return WrapError(err)
}
if err := d.Set("master_instance_types", masterInstanceTypes); err != nil {
return WrapError(err)
}
if err := d.Set("core_instance_types", coreInstanceTypes); err != nil {
return WrapError(err)
}
result := map[string]interface{}{
"master_instance_types": masterInstanceTypes,
"core_instance_types": coreInstanceTypes,
"types": types,
}
// create a json file in current directory and write data source to it
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
_ = writeToFile(output.(string), result)
}
return nil
}
func describeAvaiableResource(d *schema.ResourceData, meta interface{}) (result hbase.DescribeAvailableResourceResponse, err error) {
client := meta.(*connectivity.AliyunClient)
request := hbase.CreateDescribeAvailableResourceRequest()
if charge_type, ok := d.GetOk("charge_type"); ok {
request.ChargeType = strings.TrimSpace(charge_type.(string))
}
if region_id, ok := d.GetOk("region_id"); ok {
request.RegionId = strings.TrimSpace(region_id.(string))
} else {
request.RegionId = string(client.Region)
}
if zone_id, ok := d.GetOk("zone_id"); ok {
request.ZoneId = strings.TrimSpace(zone_id.(string))
}
if engine, ok := d.GetOk("engine"); ok {
request.Engine = strings.TrimSpace(engine.(string))
}
if version, ok := d.GetOk("version"); ok {
request.EngineVersion = strings.TrimSpace(version.(string))
}
if instanceType, ok := d.GetOk("instance_type"); ok {
request.CoreInstanceType = strings.TrimSpace(instanceType.(string))
}
if diskType, ok := d.GetOk("disk_type"); ok {
request.DiskType = strings.TrimSpace(diskType.(string))
}
raw, err := client.WithHbaseClient(func(hbaseClient *hbase.Client) (interface{}, error) {
return hbaseClient.DescribeAvailableResource(request)
})
response, _ := raw.(*hbase.DescribeAvailableResourceResponse)
if err != nil {
return result, WrapErrorf(err, DefaultErrorMsg, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
if response == nil {
return result, WrapErrorf(err, DataDefaultErrorMsg, "alicloud_hbase_instance_types", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return *response, nil
}
package alicloud
import (
"regexp"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/services/hbase"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudHBaseInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudHBaseInstancesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"availability_zone": {
Type: schema.TypeString,
Optional: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"tags": tagsSchema(),
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
"engine": {
Type: schema.TypeString,
Computed: true,
},
"engine_version": {
Type: schema.TypeString,
Computed: true,
},
"network_type": {
Type: schema.TypeString,
Computed: true,
},
"master_instance_type": {
Type: schema.TypeString,
Computed: true,
},
"master_node_count": {
Type: schema.TypeInt,
Computed: true,
},
"core_instance_type": {
Type: schema.TypeString,
Computed: true,
},
"core_node_count": {
Type: schema.TypeInt,
Computed: true,
},
"core_disk_type": {
Type: schema.TypeString,
Computed: true,
},
"core_disk_size": {
Type: schema.TypeInt,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"pay_type": {
Type: schema.TypeString,
Computed: true,
},
"created_time": {
Type: schema.TypeString,
Computed: true,
},
"expire_time": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"backup_status": {
Type: schema.TypeString,
Computed: true,
},
"deletion_protection": {
Type: schema.TypeBool,
Computed: true,
},
"tags": tagsSchema(),
},
},
},
},
}
}
func dataSourceAlicloudHBaseInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
hbaseService := HBaseService{client}
request := hbase.CreateDescribeInstancesRequest()
request.RegionId = client.RegionId
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
nameRegex = regexp.MustCompile(v.(string))
}
var az string
if v, ok := d.GetOk("availability_zone"); ok {
az = strings.ToLower(v.(string))
}
var dbi []hbase.Instance
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
if v, ok := d.GetOk("tags"); ok {
var reqTags []hbase.DescribeInstancesTag
for key, value := range v.(map[string]interface{}) {
reqTags = append(reqTags, hbase.DescribeInstancesTag{
Key: key,
Value: value.(string),
})
}
request.Tag = &reqTags
}
for {
raw, err := client.WithHbaseClient(func(hbaseClient *hbase.Client) (interface{}, error) {
return hbaseClient.DescribeInstances(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_hbase_instances", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*hbase.DescribeInstancesResponse)
if len(response.Instances.Instance) < 1 {
break
}
for _, item := range response.Instances.Instance {
if nameRegex != nil && !nameRegex.MatchString(item.InstanceName) {
continue
}
if len(az) > 0 && az != strings.ToLower(item.ZoneId) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[item.InstanceId]; !ok {
continue
}
}
dbi = append(dbi, item)
}
if len(response.Instances.Instance) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
var ids []string
var names []string
var s []map[string]interface{}
for _, item := range dbi {
mapping := map[string]interface{}{
"id": item.InstanceId,
"name": item.InstanceName,
"region_id": item.RegionId,
"zone_id": item.ZoneId,
"engine": item.Engine,
"engine_version": item.MajorVersion,
"network_type": item.NetworkType,
"master_instance_type": item.MasterInstanceType,
"master_node_count": item.MasterNodeCount,
"core_instance_type": item.CoreInstanceType,
"core_node_count": item.CoreNodeCount,
"core_disk_type": item.CoreDiskType,
"core_disk_size": item.CoreDiskSize,
"vpc_id": item.VpcId,
"vswitch_id": item.VswitchId,
"pay_type": item.PayType,
"status": item.Status,
"backup_status": item.BackupStatus,
"created_time": item.CreatedTimeUTC,
"expire_time": item.ExpireTimeUTC,
"deletion_protection": item.IsDeletionProtection,
"tags": hbaseService.tagsToMap(item.Tags.Tag),
}
ids = append(ids, item.InstanceId)
names = append(names, item.InstanceName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
err := writeToFile(output.(string), s)
if err != nil {
return WrapError(err)
}
}
return nil
}
package alicloud
import (
"fmt"
"sort"
"github.com/aliyun/alibaba-cloud-sdk-go/services/hbase"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudHBaseZones() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudHBaseZonesRead,
Schema: map[string]*schema.Schema{
"multi": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Removed: "Field 'multi' has been removed from provider version 1.99.0.",
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"zones": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"multi_zone_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
Removed: "Field 'multi_zone_ids' has been removed from provider version 1.99.0.",
},
},
},
},
},
}
}
func dataSourceAlicloudHBaseZonesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var zoneIds []string
request := hbase.CreateDescribeRegionsRequest()
request.RegionId = client.RegionId
raw, err := client.WithHbaseClient(func(hbaseClient *hbase.Client) (interface{}, error) {
return hbaseClient.DescribeRegions(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_hbase_zones", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
regions, _ := raw.(*hbase.DescribeRegionsResponse)
if len(regions.Regions.Region) <= 0 {
return WrapError(fmt.Errorf("[ERROR] There is no available region for HBase."))
}
for _, r := range regions.Regions.Region {
for _, zonid := range r.Zones.Zone {
if r.RegionId == string(client.Region) {
zoneIds = append(zoneIds, zonid.Id)
}
}
}
if len(zoneIds) > 0 {
sort.Strings(zoneIds)
}
var s []map[string]interface{}
for _, zoneId := range zoneIds {
mapping := map[string]interface{}{"id": zoneId}
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(zoneIds))
if err := d.Set("zones", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", zoneIds); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"strconv"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudHbrBackupJobs() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudHbrBackupJobsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"sort_direction": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ASCEND", "DESCEND"}, false),
},
"source_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ECS_FILE", "NAS", "OSS"}, false),
},
"filter": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"values": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"operator": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"EQUAL", "NOT_EQUAL", "GREATER_THAN", "GREATER_THAN_OR_EQUAL", "LESS_THAN", "LESS_THAN_OR_EQUAL", "BETWEEN", "IN"}, false),
},
},
},
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"COMPLETE", "FAILED", "PARTIAL_COMPLETE", "UNAVAILABLE"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"jobs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"actual_bytes": {
Type: schema.TypeString,
Computed: true,
},
"actual_items": {
Type: schema.TypeString,
Computed: true,
},
"back_job_name": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"backup_job_id": {
Type: schema.TypeString,
Computed: true,
},
"backup_type": {
Type: schema.TypeString,
Computed: true,
},
"bucket": {
Type: schema.TypeString,
Computed: true,
},
"bytes_done": {
Type: schema.TypeString,
Computed: true,
},
"bytes_total": {
Type: schema.TypeString,
Computed: true,
},
"complete_time": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"exclude": {
Type: schema.TypeString,
Computed: true,
},
"file_system_id": {
Type: schema.TypeString,
Computed: true,
},
"include": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"items_done": {
Type: schema.TypeString,
Computed: true,
},
"items_total": {
Type: schema.TypeString,
Computed: true,
},
"nas_create_time": {
Type: schema.TypeString,
Computed: true,
},
"paths": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"plan_id": {
Type: schema.TypeString,
Computed: true,
},
"prefix": {
Type: schema.TypeString,
Computed: true,
},
"source_type": {
Type: schema.TypeString,
Computed: true,
},
"start_time": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"updated_time": {
Type: schema.TypeString,
Computed: true,
},
"vault_id": {
Type: schema.TypeString,
Computed: true,
},
"progress": {
Type: schema.TypeString,
Computed: true,
},
"error_message": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudHbrBackupJobsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeBackupJobs2"
request := make(map[string]interface{})
if v, ok := d.GetOk("sort_direction"); ok {
request["SortDirection"] = v
}
request["SourceType"] = d.Get("source_type")
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
if v, ok := d.GetOk("filter"); ok {
for filterPtr, filter := range v.([]interface{}) {
filterArg := filter.(map[string]interface{})
request[fmt.Sprintf("Filters.%d.Key", filterPtr+1)] = filterArg["key"]
request[fmt.Sprintf("Filters.%d.Operator", filterPtr+1)] = filterArg["operator"]
if filterArg["key"] == "CompleteTime" {
for valuePtr, value := range filterArg["values"].([]interface{}) {
request[fmt.Sprintf("Filters.%d.Values.%d", filterPtr+1, valuePtr+1)] = strconv.FormatInt(ConvertNasFileSystemStringToUnix(value.(string)), 10)
}
} else {
for valuePtr, value := range filterArg["values"].([]interface{}) {
request[fmt.Sprintf("Filters.%d.Values.%d", filterPtr+1, valuePtr+1)] = value
}
}
}
}
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_hbr_backup_jobs", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.BackupJobs.BackupJob", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.BackupJobs.BackupJob", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["JobId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"actual_bytes": fmt.Sprint(object["ActualBytes"]),
"actual_items": fmt.Sprint(object["ActualItems"]),
"back_job_name": object["JobName"],
"id": fmt.Sprint(object["JobId"]),
"backup_job_id": fmt.Sprint(object["JobId"]),
"backup_type": object["BackupType"],
"bucket": object["Bucket"],
"bytes_done": fmt.Sprint(object["BytesDone"]),
"bytes_total": fmt.Sprint(object["BytesTotal"]),
"complete_time": fmt.Sprint(object["CompleteTime"]),
"create_time": fmt.Sprint(object["CreatedTime"]),
"exclude": object["Exclude"],
"file_system_id": object["FileSystemId"],
"include": object["Include"],
"instance_id": object["InstanceId"],
"items_done": fmt.Sprint(object["ItemsDone"]),
"items_total": fmt.Sprint(object["ItemsTotal"]),
"progress": fmt.Sprint(object["Progress"]),
"nas_create_time": fmt.Sprint(object["CreateTime"]),
"plan_id": object["PlanId"],
"prefix": object["Prefix"],
"source_type": object["SourceType"],
"error_message": object["ErrorMessage"],
"start_time": fmt.Sprint(object["StartTime"]),
"status": object["Status"],
"updated_time": fmt.Sprint(object["UpdatedTime"]),
"vault_id": object["VaultId"],
}
if object["Path"] != nil {
mapping["path"] = object["Paths"].(map[string]interface{})["Path"]
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("jobs", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudHbrEcsBackupClients() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudHbrEcsBackupClientsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"instance_ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ACTIVATED", "DEACTIVATED", "INSTALLING", "INSTALL_FAILED", "NOT_INSTALLED", "REGISTERED", "STOPPED", "UNINSTALLING", "UNINSTALL_FAILED", "UNKNOWN", "UPGRADE_FAILED", "UPGRADING"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"clients": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"arch_type": {
Type: schema.TypeString,
Computed: true,
},
"backup_status": {
Type: schema.TypeString,
Computed: true,
},
"client_type": {
Type: schema.TypeString,
Computed: true,
},
"client_version": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"data_network_type": {
Type: schema.TypeString,
Computed: true,
},
"data_proxy_setting": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"ecs_backup_client_id": {
Type: schema.TypeString,
Computed: true,
},
"hostname": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_name": {
Type: schema.TypeString,
Computed: true,
},
"last_heart_beat_time": {
Type: schema.TypeString,
Computed: true,
},
"max_client_version": {
Type: schema.TypeString,
Computed: true,
},
"max_cpu_core": {
Type: schema.TypeString,
Computed: true,
},
"max_worker": {
Type: schema.TypeString,
Computed: true,
},
"os_type": {
Type: schema.TypeString,
Computed: true,
},
"private_ipv4": {
Type: schema.TypeString,
Computed: true,
},
"proxy_host": {
Type: schema.TypeString,
Computed: true,
},
"proxy_password": {
Type: schema.TypeString,
Computed: true,
},
"proxy_port": {
Type: schema.TypeString,
Computed: true,
},
"proxy_user": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"updated_time": {
Type: schema.TypeString,
Computed: true,
},
"use_https": {
Type: schema.TypeBool,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudHbrEcsBackupClientsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeBackupClients"
request := make(map[string]interface{})
request["ClientType"] = "ECS_CLIENT"
if v, ok := d.GetOk("instance_ids"); ok {
request["InstanceIds"] = convertListToJsonString(v.([]interface{}))
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_hbr_ecs_backup_clients", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.Clients", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Clients", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ClientId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"arch_type": object["ArchType"],
"backup_status": object["BackupStatus"],
"client_type": object["ClientType"],
"client_version": object["ClientVersion"],
"create_time": fmt.Sprint(object["CreatedTime"]),
"data_network_type": object["Settings"].(map[string]interface{})["DataNetworkType"],
"data_proxy_setting": object["Settings"].(map[string]interface{})["DataProxySetting"],
"id": fmt.Sprint(object["ClientId"]),
"ecs_backup_client_id": fmt.Sprint(object["ClientId"]),
"hostname": object["Hostname"],
"instance_id": object["InstanceId"],
"instance_name": object["InstanceName"],
"last_heart_beat_time": fmt.Sprint(object["LastHeartBeatTime"]),
"max_client_version": object["MaxClientVersion"],
"max_cpu_core": object["Settings"].(map[string]interface{})["MaxCpuCore"],
"max_worker": object["Settings"].(map[string]interface{})["MaxWorker"],
"os_type": object["OsType"],
"private_ipv4": object["PrivateIpV4"],
"proxy_host": object["Settings"].(map[string]interface{})["ProxyHost"],
"proxy_password": object["Settings"].(map[string]interface{})["ProxyPassword"],
"proxy_port": fmt.Sprint(object["Settings"].(map[string]interface{})["ProxyPort"]),
"proxy_user": object["Settings"].(map[string]interface{})["ProxyUser"],
"status": object["Status"],
"updated_time": fmt.Sprint(object["UpdatedTime"]),
"use_https": object["Settings"].(map[string]interface{})["UseHttps"],
"zone_id": object["ZoneId"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("clients", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudHbrEcsBackupPlans() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudHbrEcsBackupPlansRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vault_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"plans": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"backup_type": {
Type: schema.TypeString,
Computed: true,
},
"source_type": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"detail": {
Type: schema.TypeString,
Computed: true,
},
"created_time": {
Type: schema.TypeString,
Computed: true,
},
"updated_time": {
Type: schema.TypeString,
Computed: true,
},
"disabled": {
Type: schema.TypeBool,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"ecs_backup_plan_id": {
Type: schema.TypeString,
Computed: true,
},
"ecs_backup_plan_name": {
Type: schema.TypeString,
Computed: true,
},
"exclude": {
Type: schema.TypeString,
Computed: true,
},
"include": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"options": {
Type: schema.TypeString,
Computed: true,
},
"path": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"retention": {
Type: schema.TypeString,
Computed: true,
},
"schedule": {
Type: schema.TypeString,
Computed: true,
},
"speed_limit": {
Type: schema.TypeString,
Computed: true,
},
"vault_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudHbrEcsBackupPlansRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeBackupPlans"
request := make(map[string]interface{})
request["SourceType"] = "ECS_FILE"
filtersMapList := make([]map[string]interface{}, 0)
if v, ok := d.GetOk("instance_id"); ok {
filtersMapList = append(filtersMapList, map[string]interface{}{
"Key": "instanceId",
"Values": []string{v.(string)},
})
}
if v, ok := d.GetOk("vault_id"); ok {
filtersMapList = append(filtersMapList, map[string]interface{}{
"Key": "vaultId",
"Values": []string{v.(string)},
})
}
request["Filters"] = filtersMapList
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var ecsBackupPlanNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
ecsBackupPlanNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_hbr_ecs_backup_plans", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.BackupPlans.BackupPlan", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.BackupPlans.BackupPlan", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if ecsBackupPlanNameRegex != nil && !ecsBackupPlanNameRegex.MatchString(fmt.Sprint(item["PlanName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["PlanId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"backup_type": object["BackupType"],
"source_type": object["SourceType"],
"create_time": fmt.Sprint(object["CreateTime"]),
"detail": object["Detail"],
"created_time": fmt.Sprint(object["CreatedTime"]),
"updated_time": fmt.Sprint(object["UpdatedTime"]),
"disabled": object["Disabled"],
"id": fmt.Sprint(object["PlanId"]),
"ecs_backup_plan_id": fmt.Sprint(object["PlanId"]),
"ecs_backup_plan_name": object["PlanName"],
"exclude": object["Exclude"],
"include": object["Include"],
"instance_id": object["InstanceId"],
"options": object["Options"],
"retention": fmt.Sprint(object["Retention"]),
"schedule": object["Schedule"],
"speed_limit": object["SpeedLimit"],
"vault_id": object["VaultId"],
}
if object["Path"] != nil {
mapping["path"] = object["Paths"].(map[string]interface{})["Path"]
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["PlanName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("plans", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudHbrNasBackupPlans() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudHbrNasBackupPlansRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"file_system_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vault_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"plans": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"backup_type": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"disabled": {
Type: schema.TypeBool,
Computed: true,
},
"file_system_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"nas_backup_plan_id": {
Type: schema.TypeString,
Computed: true,
},
"nas_backup_plan_name": {
Type: schema.TypeString,
Computed: true,
},
"options": {
Type: schema.TypeString,
Computed: true,
},
"path": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"retention": {
Type: schema.TypeString,
Computed: true,
},
"schedule": {
Type: schema.TypeString,
Computed: true,
},
"vault_id": {
Type: schema.TypeString,
Computed: true,
},
"created_time": {
Type: schema.TypeString,
Computed: true,
},
"updated_time": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudHbrNasBackupPlansRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeBackupPlans"
request := make(map[string]interface{})
request["SourceType"] = "NAS"
filtersMapList := make([]map[string]interface{}, 0)
if v, ok := d.GetOk("file_system_id"); ok {
filtersMapList = append(filtersMapList, map[string]interface{}{
"Key": "fileSystemId",
"Values": []string{v.(string)},
})
}
if v, ok := d.GetOk("vault_id"); ok {
filtersMapList = append(filtersMapList, map[string]interface{}{
"Key": "vaultId",
"Values": []string{v.(string)},
})
}
request["Filters"] = filtersMapList
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var nasBackupPlanNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
nasBackupPlanNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_hbr_nas_backup_plans", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.BackupPlans.BackupPlan", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.BackupPlans.BackupPlan", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if nasBackupPlanNameRegex != nil && !nasBackupPlanNameRegex.MatchString(fmt.Sprint(item["PlanName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["PlanId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
t := int64(formatInt(object["CreateTime"]))
mapping := map[string]interface{}{
"backup_type": object["BackupType"],
"create_time": ConvertNasFileSystemUnixToString("2006-01-02T15:04:05CST", t),
"disabled": object["Disabled"],
"file_system_id": object["FileSystemId"],
"id": fmt.Sprint(object["PlanId"]),
"nas_backup_plan_id": fmt.Sprint(object["PlanId"]),
"nas_backup_plan_name": object["PlanName"],
"options": object["Options"],
"retention": fmt.Sprint(object["Retention"]),
"schedule": object["Schedule"],
"vault_id": object["VaultId"],
"created_time": fmt.Sprint(object["CreatedTime"]),
"updated_time": fmt.Sprint(object["UpdatedTime"]),
}
if object["Path"] != nil {
mapping["path"] = object["Paths"].(map[string]interface{})["Path"]
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["PlanName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("plans", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudHbrOssBackupPlans() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudHbrOssBackupPlansRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"bucket": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vault_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"plans": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"backup_type": {
Type: schema.TypeString,
Computed: true,
},
"bucket": {
Type: schema.TypeString,
Computed: true,
},
"disabled": {
Type: schema.TypeBool,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"oss_backup_plan_id": {
Type: schema.TypeString,
Computed: true,
},
"oss_backup_plan_name": {
Type: schema.TypeString,
Computed: true,
},
"prefix": {
Type: schema.TypeString,
Computed: true,
},
"retention": {
Type: schema.TypeString,
Computed: true,
},
"schedule": {
Type: schema.TypeString,
Computed: true,
},
"vault_id": {
Type: schema.TypeString,
Computed: true,
},
"created_time": {
Type: schema.TypeString,
Computed: true,
},
"updated_time": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudHbrOssBackupPlansRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeBackupPlans"
request := make(map[string]interface{})
request["SourceType"] = "OSS"
filtersMapList := make([]map[string]interface{}, 0)
if v, ok := d.GetOk("bucket"); ok {
filtersMapList = append(filtersMapList, map[string]interface{}{
"Key": "bucket",
"Values": []string{v.(string)},
})
}
if v, ok := d.GetOk("plan_id"); ok {
filtersMapList = append(filtersMapList, map[string]interface{}{
"Key": "planId",
"Values": []string{v.(string)},
})
}
if v, ok := d.GetOk("plan_name"); ok {
filtersMapList = append(filtersMapList, map[string]interface{}{
"Key": "planName",
"Values": []string{v.(string)},
})
}
if v, ok := d.GetOk("vault_id"); ok {
filtersMapList = append(filtersMapList, map[string]interface{}{
"Key": "vaultId",
"Values": []string{v.(string)},
})
}
request["Filters"] = filtersMapList
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var ossBackupPlanNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
ossBackupPlanNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_hbr_oss_backup_plans", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.BackupPlans.BackupPlan", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.BackupPlans.BackupPlan", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if ossBackupPlanNameRegex != nil && !ossBackupPlanNameRegex.MatchString(fmt.Sprint(item["PlanName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["PlanId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"backup_type": object["BackupType"],
"created_time": fmt.Sprint(object["CreatedTime"]),
"updated_time": fmt.Sprint(object["UpdatedTime"]),
"bucket": object["Bucket"],
"disabled": object["Disabled"],
"id": fmt.Sprint(object["PlanId"]),
"oss_backup_plan_id": fmt.Sprint(object["PlanId"]),
"oss_backup_plan_name": object["PlanName"],
"prefix": object["Prefix"],
"retention": fmt.Sprint(object["Retention"]),
"schedule": object["Schedule"],
"vault_id": object["VaultId"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["PlanName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("plans", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"strconv"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudHbrReplicationVaultRegions() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudHbrReplicationVaultRegionsRead,
Schema: map[string]*schema.Schema{
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"regions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"replication_region_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudHbrReplicationVaultRegionsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeVaultReplicationRegions"
request := make(map[string]interface{})
var response map[string]interface{}
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_hbr_replication_vault_regions", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Regions.RegionId", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Regions", response)
}
result, _ := resp.([]interface{})
s := make([]map[string]interface{}, 0)
for _, v := range result {
mapping := map[string]interface{}{
"replication_region_id": fmt.Sprint(v),
}
s = append(s, mapping)
}
d.SetId(strconv.FormatInt(time.Now().Unix(), 16))
if err := d.Set("regions", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudHbrRestoreJobs() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudHbrRestoreJobsRead,
Schema: map[string]*schema.Schema{
"restore_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ECS_FILE", "NAS", "OSS"}, false),
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"CANCELED", "CANCELING", "COMPLETE", "CREATED", "EXPIRED", "FAILED", "PARTIAL_COMPLETE", "QUEUED", "RUNNING"}, false),
},
"restore_id": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"source_type": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"target_bucket": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"target_file_system_id": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"target_instance_id": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"vault_id": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"jobs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"actual_bytes": {
Type: schema.TypeString,
Computed: true,
},
"actual_items": {
Type: schema.TypeString,
Computed: true,
},
"bytes_done": {
Type: schema.TypeString,
Computed: true,
},
"bytes_total": {
Type: schema.TypeString,
Computed: true,
},
"complete_time": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"error_file": {
Type: schema.TypeString,
Computed: true,
},
"error_message": {
Type: schema.TypeString,
Computed: true,
},
"expire_time": {
Type: schema.TypeString,
Computed: true,
},
"items_done": {
Type: schema.TypeString,
Computed: true,
},
"items_total": {
Type: schema.TypeString,
Computed: true,
},
"options": {
Type: schema.TypeString,
Computed: true,
},
"parent_id": {
Type: schema.TypeString,
Computed: true,
},
"progress": {
Type: schema.TypeInt,
Computed: true,
},
"restore_job_id": {
Type: schema.TypeString,
Computed: true,
},
"restore_type": {
Type: schema.TypeString,
Computed: true,
},
"snapshot_hash": {
Type: schema.TypeString,
Computed: true,
},
"snapshot_id": {
Type: schema.TypeString,
Computed: true,
},
"source_type": {
Type: schema.TypeString,
Computed: true,
},
"start_time": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"target_bucket": {
Type: schema.TypeString,
Computed: true,
},
"target_client_id": {
Type: schema.TypeString,
Computed: true,
},
"target_create_time": {
Type: schema.TypeString,
Computed: true,
},
"target_data_source_id": {
Type: schema.TypeString,
Computed: true,
},
"target_file_system_id": {
Type: schema.TypeString,
Computed: true,
},
"target_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"target_path": {
Type: schema.TypeString,
Computed: true,
},
"target_prefix": {
Type: schema.TypeString,
Computed: true,
},
"updated_time": {
Type: schema.TypeString,
Computed: true,
},
"vault_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudHbrRestoreJobsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeRestoreJobs2"
request := make(map[string]interface{})
request["RestoreType"] = d.Get("restore_type")
filtersMapList := make([]map[string]interface{}, 0)
if v, ok := d.GetOk("vault_id"); ok {
filtersMapList = append(filtersMapList, map[string]interface{}{
"Key": "vaultId",
"Values": v,
})
}
if v, ok := d.GetOk("restore_id"); ok {
filtersMapList = append(filtersMapList, map[string]interface{}{
"Key": "restoreId",
"Values": v,
})
}
if v, ok := d.GetOk("source_type"); ok {
filtersMapList = append(filtersMapList, map[string]interface{}{
"Key": "sourceType",
"Values": v,
})
}
if v, ok := d.GetOk("target_bucket"); ok {
filtersMapList = append(filtersMapList, map[string]interface{}{
"Key": "targetBucket",
"Values": v,
})
}
if v, ok := d.GetOk("target_file_system_id"); ok {
filtersMapList = append(filtersMapList, map[string]interface{}{
"Key": "targetFileSystemId",
"Values": v,
})
}
if v, ok := d.GetOk("target_instance_id"); ok {
filtersMapList = append(filtersMapList, map[string]interface{}{
"Key": "targetInstanceId",
"Values": v,
})
}
request["Filters"] = filtersMapList
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_hbr_restore_jobs", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.RestoreJobs.RestoreJob", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.RestoreJobs.RestoreJob", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["RestoreId"], ":", object["RestoreType"]),
"actual_bytes": fmt.Sprint(object["ActualBytes"]),
"actual_items": fmt.Sprint(object["ActualItems"]),
"bytes_done": fmt.Sprint(object["BytesDone"]),
"bytes_total": fmt.Sprint(object["BytesTotal"]),
"complete_time": fmt.Sprint(object["CompleteTime"]),
"create_time": fmt.Sprint(object["CreatedTime"]),
"error_file": object["ErrorFile"],
"error_message": object["ErrorMessage"],
"expire_time": fmt.Sprint(object["ExpireTime"]),
"items_done": fmt.Sprint(object["ItemsDone"]),
"items_total": fmt.Sprint(object["ItemsTotal"]),
"options": object["Options"],
"parent_id": object["ParentId"],
"progress": formatInt(object["Progress"]),
"restore_job_id": object["RestoreId"],
"restore_type": object["RestoreType"],
"snapshot_hash": object["SnapshotHash"],
"snapshot_id": object["SnapshotId"],
"source_type": object["SourceType"],
"start_time": fmt.Sprint(object["StartTime"]),
"status": object["Status"],
"target_bucket": object["TargetBucket"],
"target_client_id": object["TargetClientId"],
"target_create_time": fmt.Sprint(object["TargetCreateTime"]),
"target_data_source_id": object["TargetDataSourceId"],
"target_file_system_id": object["TargetFileSystemId"],
"target_instance_id": object["TargetInstanceId"],
"target_path": object["TargetPath"],
"target_prefix": object["TargetPrefix"],
"updated_time": fmt.Sprint(object["UpdatedTime"]),
"vault_id": object["VaultId"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("jobs", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudHbrServerBackupPlans() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudHbrServerBackupPlansRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"filters": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"values": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
},
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"plans": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"detail": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"app_consistent": {
Type: schema.TypeBool,
Computed: true,
},
"snapshot_group": {
Type: schema.TypeBool,
Computed: true,
},
"enable_fs_freeze": {
Type: schema.TypeBool,
Computed: true,
},
"pre_script_path": {
Type: schema.TypeString,
Computed: true,
},
"post_script_path": {
Type: schema.TypeString,
Computed: true,
},
"timeout_in_seconds": {
Type: schema.TypeInt,
Computed: true,
},
"disk_id_list": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"do_copy": {
Type: schema.TypeBool,
Computed: true,
},
"destination_region_id": {
Type: schema.TypeString,
Computed: true,
},
"destination_retention": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"disabled": {
Type: schema.TypeBool,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"ecs_server_backup_plan_id": {
Type: schema.TypeString,
Computed: true,
},
"ecs_server_backup_plan_name": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"retention": {
Type: schema.TypeString,
Computed: true,
},
"schedule": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudHbrServerBackupPlansRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeBackupPlans"
request := make(map[string]interface{})
if v, ok := d.GetOk("filters"); ok {
for filtersPtr, filters := range v.([]interface{}) {
filtersArg := filters.(map[string]interface{})
request[fmt.Sprintf("Filters.%d.Key", filtersPtr+1)] = filtersArg["key"]
for valuesPtr, values := range filtersArg["values"].([]interface{}) {
request[fmt.Sprintf("Filters.%d.Values.%d", filtersPtr+1, valuesPtr+1)] = values
}
}
}
request["SourceType"] = "UDM_ECS"
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_hbr_server_backup_plans", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.BackupPlans.BackupPlan", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.BackupPlans.BackupPlan", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["PlanId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": fmt.Sprint(object["CreatedTime"]),
"disabled": object["Disabled"],
"id": fmt.Sprint(object["PlanId"]),
"ecs_server_backup_plan_id": fmt.Sprint(object["PlanId"]),
"ecs_server_backup_plan_name": object["PlanName"],
"instance_id": object["InstanceId"],
"retention": fmt.Sprint(object["Retention"]),
"schedule": object["Schedule"],
}
if v, ok := object["Detail"].(map[string]interface{}); ok {
details := make([]map[string]interface{}, 0)
detail := make(map[string]interface{})
detail["app_consistent"] = v["appConsistent"]
detail["snapshot_group"] = v["snapshotGroup"]
detail["enable_fs_freeze"] = v["enableFsFreeze"]
detail["pre_script_path"] = v["preScriptPath"]
detail["post_script_path"] = v["postScriptPath"]
detail["timeout_in_seconds"] = formatInt(v["timeoutInSeconds"])
detail["do_copy"] = v["doCopy"]
detail["destination_region_id"] = v["destinationRegionId"]
detail["destination_retention"] = v["destinationRetention"]
if v["diskIdList"] != nil {
detail["disk_id_list"] = expandStringList(v["diskIdList"].([]interface{}))
}
details = append(details, detail)
mapping["detail"] = details
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("plans", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudHbrSnapshots() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudHbrSnapshotsRead,
Schema: map[string]*schema.Schema{
"limit": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"query": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"source_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ECS_FILE", "OSS", "NAS"}, false),
},
"vault_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"file_system_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"create_time": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"bucket": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"complete_time": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"complete_time_checker": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"MATCH_TERM", "GREATER_THAN", "GREATER_THAN_OR_EQUAL", "LESS_THAN", "LESS_THAN_OR_EQUAL", "BETWEEN", "IN", "NOT_IN"}, false),
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"COMPLETE", "PARTIAL_COMPLETE"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"snapshots": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"actual_bytes": {
Type: schema.TypeString,
Computed: true,
},
"actual_items": {
Type: schema.TypeString,
Computed: true,
},
"backup_type": {
Type: schema.TypeString,
Computed: true,
},
"bucket": {
Type: schema.TypeString,
Computed: true,
},
"bytes_done": {
Type: schema.TypeString,
Computed: true,
},
"bytes_total": {
Type: schema.TypeString,
Computed: true,
},
"complete_time": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"created_time": {
Type: schema.TypeString,
Computed: true,
},
"error_file": {
Type: schema.TypeString,
Computed: true,
},
"file_system_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"items_done": {
Type: schema.TypeString,
Computed: true,
},
"items_total": {
Type: schema.TypeString,
Computed: true,
},
"job_id": {
Type: schema.TypeString,
Computed: true,
},
"parent_snapshot_hash": {
Type: schema.TypeString,
Computed: true,
},
"path": {
Type: schema.TypeString,
Computed: true,
},
"prefix": {
Type: schema.TypeString,
Computed: true,
},
"client_id": {
Type: schema.TypeString,
Computed: true,
},
"retention": {
Type: schema.TypeString,
Computed: true,
},
"snapshot_hash": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"snapshot_id": {
Type: schema.TypeString,
Computed: true,
},
"source_type": {
Type: schema.TypeString,
Computed: true,
},
"start_time": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"updated_time": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
type QueryField struct {
Field string `json:"field"`
Value string `json:"value"`
Operation string `json:"operation"`
}
func dataSourceAlicloudHbrSnapshotsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "SearchHistoricalSnapshots"
request := make(map[string]interface{})
if v, ok := d.GetOk("limit"); ok {
request["Limit"] = v
}
request["SourceType"] = d.Get("source_type")
filtersMapList := make([]map[string]interface{}, 0)
if v, ok := d.GetOk("vault_id"); ok {
filtersMapList = append(filtersMapList, map[string]interface{}{
"field": "VaultId",
"value": v.(string),
"operation": "MATCH_TERM",
})
}
if v, ok := d.GetOk("instance_id"); ok {
filtersMapList = append(filtersMapList, map[string]interface{}{
"field": "InstanceId",
"value": v.(string),
"operation": "MATCH_TERM",
})
}
if v, ok := d.GetOk("bucket"); ok {
filtersMapList = append(filtersMapList, map[string]interface{}{
"field": "Bucket",
"value": v.(string),
"operation": "MATCH_TERM",
})
}
if v, ok := d.GetOk("file_system_id"); ok {
filtersMapList = append(filtersMapList, map[string]interface{}{
"field": "FileSystemId",
"value": v.(string),
"operation": "MATCH_TERM",
})
}
if v, ok := d.GetOk("create_time"); ok {
filtersMapList = append(filtersMapList, map[string]interface{}{
"field": "CreateTime",
"value": strconv.FormatInt(ConvertNasFileSystemStringToUnix(v.(string)), 10),
"operation": "MATCH_TERM",
})
}
if v, ok := d.GetOk("complete_time"); ok {
completeChecker := make(map[string]interface{})
completeChecker["field"] = "CompleteTime"
completeChecker["operation"] = "MATCH_TERM"
if vv, ok := d.GetOk("complete_time_checker"); ok {
completeChecker["operation"] = vv.(string)
}
if completeChecker["operation"] == "BETWEEN" {
timeSection := strings.Split(v.(string), ",")
completeChecker["value"] = ConvertNasFileSystemStringToUnix(timeSection[0])
completeChecker["value2"] = ConvertNasFileSystemStringToUnix(timeSection[1])
} else {
completeChecker["value"] = ConvertNasFileSystemStringToUnix(v.(string))
}
filtersMapList = append(filtersMapList, completeChecker)
}
if v, ok := d.GetOk("status"); ok {
filtersMapList = append(filtersMapList, map[string]interface{}{
"field": "Status",
"value": v.(string),
"operation": "MATCH_TERM",
})
}
request["Query"], _ = convertListMapToJsonString(filtersMapList)
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_hbr_snapshots", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.Snapshots.Snapshot", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Snapshots.Snapshot", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["SnapshotId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"actual_bytes": fmt.Sprint(object["ActualBytes"]),
"actual_items": fmt.Sprint(object["ActualItems"]),
"backup_type": object["BackupType"],
"bucket": object["Bucket"],
"bytes_done": fmt.Sprint(object["BytesDone"]),
"bytes_total": fmt.Sprint(object["BytesTotal"]),
"complete_time": fmt.Sprint(object["CompleteTime"]),
"create_time": fmt.Sprint(object["CreateTime"]),
"created_time": fmt.Sprint(object["CreatedTime"]),
"error_file": object["ErrorFile"],
"file_system_id": object["FileSystemId"],
"instance_id": object["InstanceId"],
"items_done": fmt.Sprint(object["ItemsDone"]),
"items_total": fmt.Sprint(object["ItemsTotal"]),
"job_id": object["JobId"],
"parent_snapshot_hash": object["ParentSnapshotHash"],
"prefix": object["Prefix"],
"client_id": object["ClientId"],
"retention": fmt.Sprint(object["Retention"]),
"snapshot_hash": object["SnapshotHash"],
"id": fmt.Sprint(object["SnapshotId"]),
"snapshot_id": fmt.Sprint(object["SnapshotId"]),
"source_type": object["SourceType"],
"start_time": fmt.Sprint(object["StartTime"]),
"status": object["Status"],
"updated_time": fmt.Sprint(object["UpdatedTime"]),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("snapshots", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudHbrVaults() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudHbrVaultsRead,
Schema: map[string]*schema.Schema{
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"CREATED", "ERROR", "INITIALIZING", "UNKNOWN"}, false),
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"vault_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "STANDARD",
ValidateFunc: validation.StringInSlice([]string{"STANDARD"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"vaults": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"bucket_name": {
Type: schema.TypeString,
Computed: true,
},
"bytes_done": {
Type: schema.TypeString,
Computed: true,
},
"created_time": {
Type: schema.TypeString,
Computed: true,
},
"dedup": {
Type: schema.TypeBool,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"index_available": {
Type: schema.TypeBool,
Computed: true,
},
"index_level": {
Type: schema.TypeString,
Computed: true,
},
"index_update_time": {
Type: schema.TypeString,
Computed: true,
},
"latest_replication_time": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"replication": {
Type: schema.TypeBool,
Computed: true,
},
"replication_source_region_id": {
Type: schema.TypeString,
Computed: true,
},
"replication_source_vault_id": {
Type: schema.TypeString,
Computed: true,
},
"retention": {
Type: schema.TypeString,
Computed: true,
},
"search_enabled": {
Type: schema.TypeBool,
Computed: true,
},
"source_types": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"storage_size": {
Type: schema.TypeString,
Computed: true,
},
"updated_time": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"vault_id": {
Type: schema.TypeString,
Computed: true,
},
"vault_name": {
Type: schema.TypeString,
Computed: true,
},
"vault_status_message": {
Type: schema.TypeString,
Computed: true,
},
"vault_storage_class": {
Type: schema.TypeString,
Computed: true,
},
"vault_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudHbrVaultsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeVaults"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
if v, ok := d.GetOk("vault_type"); ok {
request["VaultType"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var vaultNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
vaultNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_hbr_vaults", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.Vaults.Vault", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Vaults.Vault", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if vaultNameRegex != nil && !vaultNameRegex.MatchString(fmt.Sprint(item["VaultName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["VaultId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"bucket_name": object["BucketName"],
"bytes_done": fmt.Sprint(object["BytesDone"]),
"created_time": fmt.Sprint(object["CreatedTime"]),
"dedup": object["Dedup"],
"description": object["Description"],
"index_available": object["IndexAvailable"],
"index_level": object["IndexLevel"],
"index_update_time": fmt.Sprint(object["IndexUpdateTime"]),
"latest_replication_time": fmt.Sprint(object["LatestReplicationTime"]),
"payment_type": object["ChargeType"],
"replication": object["Replication"],
"replication_source_region_id": object["ReplicationSourceRegionId"],
"replication_source_vault_id": object["ReplicationSourceVaultId"],
"retention": fmt.Sprint(object["Retention"]),
"search_enabled": object["SearchEnabled"],
"source_types": object["SourceTypes"].(map[string]interface{})["SourceType"],
"status": object["Status"],
"storage_size": fmt.Sprint(object["StorageSize"]),
"updated_time": fmt.Sprint(object["UpdatedTime"]),
"id": fmt.Sprint(object["VaultId"]),
"vault_id": fmt.Sprint(object["VaultId"]),
"vault_name": object["VaultName"],
"vault_status_message": object["VaultStatusMessage"],
"vault_storage_class": object["VaultStorageClass"],
"vault_type": object["VaultType"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["VaultName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("vaults", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"log"
"regexp"
"sort"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudImages() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudImagesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.ValidateRegexp,
},
"most_recent": {
Type: schema.TypeBool,
Optional: true,
Default: false,
ForceNew: true,
},
"owners": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
// must contain a valid Image owner, expected ImageOwnerSystem, ImageOwnerSelf, ImageOwnerOthers, ImageOwnerMarketplace, ImageOwnerDefault
ValidateFunc: validation.StringInSlice([]string{"system", "self", "others", "marketplace", ""}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"status": {
Type: schema.TypeString,
Optional: true,
Default: "Available",
ValidateFunc: validation.StringInSlice([]string{"Available", "Creating", "Waiting", "UnAvailable", "CreateFailed", "Deprecated"}, false),
},
"image_id": {
Type: schema.TypeString,
Optional: true,
},
"image_name": {
Type: schema.TypeString,
Optional: true,
},
"is_support_io_optimized": {
Type: schema.TypeBool,
Optional: true,
},
"is_support_cloud_init": {
Type: schema.TypeBool,
Optional: true,
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"snapshot_id": {
Type: schema.TypeString,
Optional: true,
},
"image_family": {
Type: schema.TypeString,
Optional: true,
},
"instance_type": {
Type: schema.TypeString,
Optional: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
},
"usage": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"instance", "none"}, false),
},
"os_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"windows", "linux"}, false),
},
"architecture": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"i386", "x86_64"}, false),
},
"action_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"CreateEcs", "CreateOS"}, false),
},
"tags": tagsSchema(),
// Computed values.
"images": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"image_id": {
Type: schema.TypeString,
Computed: true,
},
"architecture": {
Type: schema.TypeString,
Computed: true,
},
"creation_time": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"image_owner_alias": {
Type: schema.TypeString,
Computed: true,
},
"os_type": {
Type: schema.TypeString,
Computed: true,
},
"os_name": {
Type: schema.TypeString,
Computed: true,
},
"os_name_en": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"platform": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"state": {
Type: schema.TypeString,
Computed: true,
},
"size": {
Type: schema.TypeInt,
Computed: true,
},
// Complex computed values
"disk_device_mappings": {
Type: schema.TypeList,
Computed: true,
//Set: imageDiskDeviceMappingHash,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"device": {
Type: schema.TypeString,
Computed: true,
},
"size": {
Type: schema.TypeString,
Computed: true,
},
"snapshot_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"product_code": {
Type: schema.TypeString,
Computed: true,
},
"is_self_shared": {
Type: schema.TypeString,
Computed: true,
},
"is_subscribed": {
Type: schema.TypeBool,
Computed: true,
},
"is_copied": {
Type: schema.TypeBool,
Computed: true,
},
"is_support_io_optimized": {
Type: schema.TypeBool,
Computed: true,
},
"image_version": {
Type: schema.TypeString,
Computed: true,
},
"progress": {
Type: schema.TypeString,
Computed: true,
},
"usage": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
},
},
},
},
}
}
// dataSourceAlicloudImagesDescriptionRead performs the Alicloud Image lookup.
func dataSourceAlicloudImagesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
nameRegex, nameRegexOk := d.GetOk("name_regex")
owners, ownersOk := d.GetOk("owners")
mostRecent, mostRecentOk := d.GetOk("most_recent")
if nameRegexOk == false && ownersOk == false && mostRecentOk == false {
return WrapError(Error("One of name_regex, owners or most_recent must be assigned"))
}
request := ecs.CreateDescribeImagesRequest()
request.PageNumber = requests.NewInteger(1)
request.PageSize = requests.NewInteger(PageSizeXLarge)
if ownersOk {
request.ImageOwnerAlias = owners.(string)
}
if status, ok := d.GetOk("status"); ok && status.(string) != "" {
request.Status = status.(string)
}
if v, ok := d.GetOk("image_id"); ok && v.(string) != "" {
request.ImageId = v.(string)
}
if v, ok := d.GetOk("image_name"); ok && v.(string) != "" {
request.ImageName = v.(string)
}
if v, ok := d.GetOk("snapshot_id"); ok && v.(string) != "" {
request.SnapshotId = v.(string)
}
if v, ok := d.GetOk("image_family"); ok && v.(string) != "" {
request.ImageFamily = v.(string)
}
if v, ok := d.GetOk("instance_type"); ok && v.(string) != "" {
request.InstanceType = v.(string)
}
if v, ok := d.GetOk("resource_group_id"); ok && v.(string) != "" {
request.ResourceGroupId = v.(string)
}
if v, ok := d.GetOk("usage"); ok && v.(string) != "" {
request.Usage = v.(string)
}
if v, ok := d.GetOk("architecture"); ok && v.(string) != "" {
request.Architecture = v.(string)
}
if v, ok := d.GetOk("os_type"); ok && v.(string) != "" {
request.OSType = v.(string)
}
if v, ok := d.GetOk("action_type"); ok && v.(string) != "" {
request.ActionType = v.(string)
}
if v, ok := d.GetOk("is_support_io_optimized"); ok {
request.IsSupportIoOptimized = requests.NewBoolean(v.(bool))
}
if v, ok := d.GetOk("is_support_cloud_init"); ok {
request.IsSupportCloudinit = requests.NewBoolean(v.(bool))
}
if v, ok := d.GetOk("dry_run"); ok {
request.DryRun = requests.NewBoolean(v.(bool))
}
if v, ok := d.GetOk("tags"); ok {
var reqTags []ecs.DescribeImagesTag
for k, v := range v.(map[string]interface{}) {
reqTags = append(reqTags, ecs.DescribeImagesTag{
Key: k,
Value: v.(string),
})
}
request.Tag = &reqTags
}
var allImages []ecs.Image
for {
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeImages(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_images", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*ecs.DescribeImagesResponse)
if response == nil || len(response.Images.Image) < 1 {
break
}
allImages = append(allImages, response.Images.Image...)
if len(response.Images.Image) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
var filteredImages []ecs.Image
if nameRegexOk {
r, err := regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
for _, image := range allImages {
// Check for a very rare case where the response would include no
// image name. No name means nothing to attempt a match against,
// therefore we are skipping such image.
if image.ImageName == "" {
log.Printf("[WARN] Unable to find Image name to match against "+
"for image ID %q, nothing to do.",
image.ImageId)
continue
}
if r.MatchString(image.ImageName) {
filteredImages = append(filteredImages, image)
}
}
} else {
filteredImages = allImages[:]
}
var images []ecs.Image
if len(filteredImages) > 1 && mostRecent.(bool) {
// Query returned single result.
images = append(images, mostRecentImage(filteredImages))
} else {
images = filteredImages
}
return imagesDescriptionAttributes(d, images, meta)
}
// populate the numerous fields that the image description returns.
func imagesDescriptionAttributes(d *schema.ResourceData, images []ecs.Image, meta interface{}) error {
var ids []string
var s []map[string]interface{}
for _, image := range images {
mapping := map[string]interface{}{
"id": image.ImageId,
"architecture": image.Architecture,
"creation_time": image.CreationTime,
"description": image.Description,
"image_id": image.ImageId,
"image_owner_alias": image.ImageOwnerAlias,
"os_name": image.OSName,
"os_name_en": image.OSNameEn,
"os_type": image.OSType,
"name": image.ImageName,
"platform": image.Platform,
"status": image.Status,
"state": image.Status,
"size": image.Size,
"is_self_shared": image.IsSelfShared,
"is_subscribed": image.IsSubscribed,
"is_copied": image.IsCopied,
"is_support_io_optimized": image.IsSupportIoOptimized,
"image_version": image.ImageVersion,
"progress": image.Progress,
"usage": image.Usage,
"product_code": image.ProductCode,
// Complex types get their own functions
"disk_device_mappings": imageDiskDeviceMappings(image.DiskDeviceMappings.DiskDeviceMapping),
"tags": imageTagsMappings(d, image.ImageId, meta),
}
ids = append(ids, image.ImageId)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("images", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
//Find most recent image
type imageSort []ecs.Image
func (a imageSort) Len() int {
return len(a)
}
func (a imageSort) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a imageSort) Less(i, j int) bool {
itime, _ := time.Parse(time.RFC3339, a[i].CreationTime)
jtime, _ := time.Parse(time.RFC3339, a[j].CreationTime)
return itime.Unix() < jtime.Unix()
}
// Returns the most recent Image out of a slice of images.
func mostRecentImage(images []ecs.Image) ecs.Image {
sortedImages := images
sort.Sort(imageSort(sortedImages))
return sortedImages[len(sortedImages)-1]
}
// Returns a set of disk device mappings.
func imageDiskDeviceMappings(m []ecs.DiskDeviceMapping) []map[string]interface{} {
var s []map[string]interface{}
for _, v := range m {
mapping := map[string]interface{}{
"device": v.Device,
"size": v.Size,
"snapshot_id": v.SnapshotId,
}
s = append(s, mapping)
}
return s
}
//Returns a mapping of image tags
func imageTagsMappings(d *schema.ResourceData, imageId string, meta interface{}) map[string]string {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
tags, err := ecsService.DescribeTags(imageId, TagResourceImage)
if err != nil {
return nil
}
return ecsTagsToMap(tags)
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudImmProjects() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudImmProjectsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"projects": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"billing_type": {
Type: schema.TypeString,
Computed: true,
},
"compute_unit": {
Type: schema.TypeInt,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"modify_time": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"project": {
Type: schema.TypeString,
Computed: true,
},
"service_role": {
Type: schema.TypeString,
Computed: true,
},
"endpoint": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudImmProjectsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListProjects"
request := map[string]interface{}{
"MaxKeys": PageSizeLarge,
"RegionId": client.RegionId,
}
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewImmClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-06"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_imm_projects", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Projects", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Projects", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Project"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if marker, ok := response["Marker"].(string); ok && marker != "" {
request["Marker"] = marker
} else {
break
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"billing_type": object["BillingType"],
"compute_unit": formatInt(object["CU"]),
"create_time": object["CreateTime"],
"modify_time": object["ModifyTime"],
"type": object["Type"],
"id": fmt.Sprint(object["Project"]),
"project": fmt.Sprint(object["Project"]),
"service_role": object["ServiceRole"],
"endpoint": object["Endpoint"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("projects", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudImpAppTemplates() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudImpAppTemplatesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"attached", "unattached"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"templates": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"app_template_creator": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"app_template_id": {
Type: schema.TypeString,
Computed: true,
},
"app_template_name": {
Type: schema.TypeString,
Computed: true,
},
"component_list": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"config_list": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Computed: true,
},
"value": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"integration_mode": {
Type: schema.TypeString,
Computed: true,
},
"scene": {
Type: schema.TypeString,
Computed: true,
},
"sdk_info": {
Type: schema.TypeString,
Computed: true,
},
"standard_room_info": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudImpAppTemplatesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListAppTemplates"
request := make(map[string]interface{})
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var appTemplateNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
appTemplateNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewImpClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-06-30"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_imp_app_templates", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Result.AppTemplateInfoList", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Result.AppTemplateInfoList", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if appTemplateNameRegex != nil && !appTemplateNameRegex.MatchString(fmt.Sprint(item["AppTemplateName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["AppTemplateId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"app_template_creator": object["AppTemplateCreator"],
"id": fmt.Sprint(object["AppTemplateId"]),
"app_template_id": fmt.Sprint(object["AppTemplateId"]),
"app_template_name": object["AppTemplateName"],
"component_list": object["ComponentList"],
"create_time": object["CreateTime"],
"integration_mode": object["IntegrationMode"],
"scene": object["Scene"],
"sdk_info": object["SdkInfo"],
"standard_room_info": object["StandardRoomInfo"],
"status": object["Status"],
}
if configList, ok := object["ConfigList"]; ok && configList != nil {
configListMaps := make([]map[string]interface{}, 0)
for _, configListItem := range configList.([]interface{}) {
if configListItemMap, ok := configListItem.(map[string]interface{}); ok {
configListMap := make(map[string]interface{}, 0)
configListMap["key"] = configListItemMap["Key"]
configListMap["value"] = configListItemMap["Value"]
configListMaps = append(configListMaps, configListMap)
}
}
mapping["config_list"] = configListMaps
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["AppTemplateName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("templates", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"sort"
"github.com/denverdino/aliyungo/common"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudInstanceTypeFamilies() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudInstanceTypeFamiliesRead,
Schema: map[string]*schema.Schema{
"generation": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ecs-1", "ecs-2", "ecs-3", "ecs-4"}, false),
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"instance_charge_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: PostPaid,
// %q must contain a valid InstanceChargeType, expected common.PrePaid, common.PostPaid
ValidateFunc: validation.StringInSlice([]string{string(common.PrePaid), string(common.PostPaid)}, false),
},
"spot_strategy": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: NoSpot,
ValidateFunc: validation.StringInSlice([]string{"NoSpot", "SpotAsPriceGo", "SpotWithPriceLimit"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
// Computed values.
"families": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"generation": {
Type: schema.TypeString,
Computed: true,
},
"zone_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
},
}
}
func dataSourceAlicloudInstanceTypeFamiliesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
request := ecs.CreateDescribeInstanceTypeFamiliesRequest()
request.RegionId = client.RegionId
if v, ok := d.GetOk("generation"); ok {
request.Generation = v.(string)
}
zones, err := ecsService.DescribeZones(d)
families := make(map[string]map[string]string)
for _, zone := range zones {
for _, infos := range zone.AvailableResources.ResourcesInfo {
for _, family := range infos.InstanceTypeFamilies.SupportedInstanceTypeFamily {
if _, ok := families[family]; !ok {
families[family] = make(map[string]string)
}
families[family][zone.ZoneId] = ""
}
}
}
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeInstanceTypeFamilies(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_instance_type_families", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
var instanceTypeFamilies []ecs.InstanceTypeFamily
response, _ := raw.(*ecs.DescribeInstanceTypeFamiliesResponse)
if response != nil {
for _, family := range response.InstanceTypeFamilies.InstanceTypeFamily {
if _, ok := families[family.InstanceTypeFamilyId]; !ok {
continue
}
instanceTypeFamilies = append(instanceTypeFamilies, family)
}
}
return instanceTypeFamiliesDescriptionAttributes(d, instanceTypeFamilies, families)
}
func instanceTypeFamiliesDescriptionAttributes(d *schema.ResourceData, typeFamilies []ecs.InstanceTypeFamily, families map[string]map[string]string) error {
var ids []string
var s []map[string]interface{}
for _, f := range typeFamilies {
mapping := map[string]interface{}{
"id": f.InstanceTypeFamilyId,
"generation": f.Generation,
}
var zoneIds []string
for zoneId := range families[f.InstanceTypeFamilyId] {
zoneIds = append(zoneIds, zoneId)
}
sort.Strings(zoneIds)
mapping["zone_ids"] = zoneIds
ids = append(ids, f.InstanceTypeFamilyId)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("families", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"sort"
"strconv"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/services/bssopenapi"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/denverdino/aliyungo/common"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
type instanceTypeWithOriginalPrice struct {
InstanceType ecs.InstanceType
OriginalPrice float64
}
func dataSourceAlicloudInstanceTypes() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudInstanceTypesRead,
Schema: map[string]*schema.Schema{
"availability_zone": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"instance_type_family": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^ecs\..*`), "prefix must be 'ecs.'"),
},
"cpu_core_count": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"memory_size": {
Type: schema.TypeFloat,
Optional: true,
ForceNew: true,
},
"gpu_amount": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"gpu_spec": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"instance_charge_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: PostPaid,
// %q must contain a valid InstanceChargeType, expected common.PrePaid, common.PostPaid
ValidateFunc: validation.StringInSlice([]string{string(common.PrePaid), string(common.PostPaid)}, false),
},
"network_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Vpc", "Classic"}, false),
},
"spot_strategy": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: NoSpot,
ValidateFunc: validation.StringInSlice([]string{"NoSpot", "SpotAsPriceGo", "SpotWithPriceLimit"}, false),
},
"eni_amount": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"kubernetes_node_role": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
string(KubernetesNodeMaster),
string(KubernetesNodeWorker),
}, false),
},
"is_outdated": {
Type: schema.TypeBool,
Optional: true,
},
"sorted_by": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
"CPU",
"Memory",
"Price",
}, false),
},
"system_disk_category": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"cloud", "ephemeral_ssd", "cloud_essd", "cloud_efficiency", "cloud_ssd"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
// Computed values.
"instance_types": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"cpu_core_count": {
Type: schema.TypeInt,
Computed: true,
},
"memory_size": {
Type: schema.TypeFloat,
Computed: true,
},
"family": {
Type: schema.TypeString,
Computed: true,
},
"price": {
Type: schema.TypeString,
Computed: true,
},
"availability_zones": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"gpu": {
Type: schema.TypeMap,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"amount": {
Type: schema.TypeString,
Computed: true,
},
"category": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"burstable_instance": {
Type: schema.TypeMap,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"initial_credit": {
Type: schema.TypeString,
Computed: true,
},
"baseline_credit": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"eni_amount": {
Type: schema.TypeInt,
Computed: true,
},
"local_storage": {
Type: schema.TypeMap,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"capacity": {
Type: schema.TypeString,
Computed: true,
},
"amount": {
Type: schema.TypeString,
Computed: true,
},
"category": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudInstanceTypesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
zoneId, validZones, _, err := ecsService.DescribeAvailableResources(d, meta, InstanceTypeResource)
if err != nil {
return err
}
mapInstanceTypes := make(map[string][]string)
for _, zone := range validZones {
if zoneId != "" && zoneId != zone.ZoneId {
continue
}
for _, r := range zone.AvailableResources.AvailableResource {
for _, t := range r.SupportedResources.SupportedResource {
if t.Status == string(SoldOut) {
continue
}
if v, ok := mapInstanceTypes[t.Value]; ok {
v = append(v, zone.ZoneId)
mapInstanceTypes[t.Value] = v
} else {
mapInstanceTypes[t.Value] = []string{zone.ZoneId}
}
}
}
}
cpu := d.Get("cpu_core_count").(int)
mem := d.Get("memory_size").(float64)
family := strings.TrimSpace(d.Get("instance_type_family").(string))
gpuAmount := d.Get("gpu_amount").(int)
gpuSpec := d.Get("gpu_spec").(string)
req := ecs.CreateDescribeInstanceTypesRequest()
req.InstanceTypeFamily = family
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeInstanceTypes(req)
})
if err != nil {
return err
}
var instanceTypes []instanceTypeWithOriginalPrice
resp, _ := raw.(*ecs.DescribeInstanceTypesResponse)
if resp != nil {
eniAmount := d.Get("eni_amount").(int)
k8sNode := strings.TrimSpace(d.Get("kubernetes_node_role").(string))
for _, types := range resp.InstanceTypes.InstanceType {
if _, ok := mapInstanceTypes[types.InstanceTypeId]; !ok {
continue
}
if cpu > 0 && types.CpuCoreCount != cpu {
continue
}
if mem > 0 && types.MemorySize != mem {
continue
}
if eniAmount > types.EniQuantity {
continue
}
if gpuAmount > 0 && types.GPUAmount != gpuAmount {
continue
}
if gpuSpec != "" && types.GPUSpec != gpuSpec {
continue
}
// Kubernetes node does not support instance types which family is "ecs.t5" and spec less that c2g4
// Kubernetes master node does not support gpu instance types which family prefixes with "ecs.gn"
if k8sNode != "" {
if types.InstanceTypeFamily == "ecs.t5" {
continue
}
if types.CpuCoreCount < 2 || types.MemorySize < 4 {
continue
}
if k8sNode == string(KubernetesNodeMaster) && strings.HasPrefix(types.InstanceTypeFamily, "ecs.gn") {
continue
}
}
instanceTypes = append(instanceTypes, instanceTypeWithOriginalPrice{
InstanceType: types,
})
}
sortedBy := d.Get("sorted_by").(string)
if sortedBy == "Price" && len(instanceTypes) > 0 {
bssopenapiService := BssopenapiService{client}
priceList, err := getEcsInstanceTypePrice(bssopenapiService, d.Get("instance_charge_type").(string), instanceTypes)
if err != nil {
return WrapError(err)
}
for i := 0; i < len(instanceTypes); i++ {
instanceTypes[i].OriginalPrice = priceList[i]
}
}
}
return instanceTypesDescriptionAttributes(d, instanceTypes, mapInstanceTypes)
}
func instanceTypesDescriptionAttributes(d *schema.ResourceData, types []instanceTypeWithOriginalPrice, mapTypes map[string][]string) error {
sortedBy := d.Get("sorted_by").(string)
if sortedBy != "" {
sort.SliceStable(types, func(i, j int) bool {
switch sortedBy {
case "Price":
return types[i].OriginalPrice < types[j].OriginalPrice
case "CPU":
return types[i].InstanceType.CpuCoreCount < types[j].InstanceType.CpuCoreCount
case "Memory":
return types[i].InstanceType.MemorySize < types[j].InstanceType.MemorySize
}
return false
})
}
var ids []string
var s []map[string]interface{}
for _, t := range types {
mapping := map[string]interface{}{
"id": t.InstanceType.InstanceTypeId,
"cpu_core_count": t.InstanceType.CpuCoreCount,
"memory_size": t.InstanceType.MemorySize,
"family": t.InstanceType.InstanceTypeFamily,
"eni_amount": t.InstanceType.EniQuantity,
}
if sortedBy == "Price" {
mapping["price"] = fmt.Sprintf("%.4f", t.OriginalPrice)
}
zoneIds := mapTypes[t.InstanceType.InstanceTypeId]
sort.Strings(zoneIds)
mapping["availability_zones"] = zoneIds
gpu := map[string]interface{}{
"amount": strconv.Itoa(t.InstanceType.GPUAmount),
"category": t.InstanceType.GPUSpec,
}
mapping["gpu"] = gpu
brust := map[string]interface{}{
"initial_credit": strconv.Itoa(t.InstanceType.InitialCredit),
"baseline_credit": strconv.Itoa(t.InstanceType.BaselineCredit),
}
mapping["burstable_instance"] = brust
local := map[string]interface{}{
"capacity": strconv.FormatInt(t.InstanceType.LocalStorageCapacity, 10),
"amount": strconv.Itoa(t.InstanceType.LocalStorageAmount),
"category": t.InstanceType.LocalStorageCategory,
}
mapping["local_storage"] = local
ids = append(ids, t.InstanceType.InstanceTypeId)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("instance_types", s); err != nil {
return err
}
if err := d.Set("ids", ids); err != nil {
return err
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
func getEcsInstanceTypePrice(bssopenapiService BssopenapiService, instanceChargeType string, instanceTypes []instanceTypeWithOriginalPrice) ([]float64, error) {
client := bssopenapiService.client
var modules interface{}
moduleCode := "InstanceType"
var payAsYouGo []bssopenapi.GetPayAsYouGoPriceModuleList
var subsciption []bssopenapi.GetSubscriptionPriceModuleList
for _, types := range instanceTypes {
config := fmt.Sprintf("InstanceType:%s,IoOptimized:IoOptimized,ImageOs:linux,Region:%s",
types.InstanceType.InstanceTypeId, client.RegionId)
if instanceChargeType == string(PostPaid) {
payAsYouGo = append(payAsYouGo, bssopenapi.GetPayAsYouGoPriceModuleList{
ModuleCode: moduleCode,
Config: config,
PriceType: "Hour",
})
} else {
subsciption = append(subsciption, bssopenapi.GetSubscriptionPriceModuleList{
ModuleCode: moduleCode,
Config: config,
})
}
}
if len(payAsYouGo) != 0 {
modules = payAsYouGo
} else {
modules = subsciption
}
return bssopenapiService.GetInstanceTypePrice("ecs", "", modules)
}
package alicloud
import (
"regexp"
"strconv"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudInstancesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
MinItems: 1,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"image_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
//must contain a valid status, expected Creating, Starting, Running, Stopping, Stopped
ValidateFunc: validation.StringInSlice([]string{
string(Running),
string(Stopped),
string(Creating),
string(Starting),
string(Stopping),
}, false),
ForceNew: true,
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"availability_zone": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ram_role_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"tags": tagsSchema(),
"output_file": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"page_number": {
Type: schema.TypeInt,
Optional: true,
},
"page_size": {
Type: schema.TypeInt,
Optional: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"availability_zone": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"instance_type": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"image_id": {
Type: schema.TypeString,
Computed: true,
},
"private_ip": {
Type: schema.TypeString,
Computed: true,
},
"public_ip": {
Type: schema.TypeString,
Computed: true,
},
"eip": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"security_groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"key_name": {
Type: schema.TypeString,
Computed: true,
},
"creation_time": {
Type: schema.TypeString,
Computed: true,
},
"instance_charge_type": {
Type: schema.TypeString,
Computed: true,
},
"internet_charge_type": {
Type: schema.TypeString,
Computed: true,
},
"internet_max_bandwidth_out": {
Type: schema.TypeInt,
Computed: true,
},
"ram_role_name": {
Type: schema.TypeString,
Computed: true,
},
"spot_strategy": {
Type: schema.TypeString,
Computed: true,
},
"disk_device_mappings": {
Type: schema.TypeList,
Computed: true,
//Set: imageDiskDeviceMappingHash,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"device": {
Type: schema.TypeString,
Computed: true,
},
"size": {
Type: schema.TypeInt,
Computed: true,
},
"category": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"tags": tagsSchema(),
},
},
},
"total_count": {
Type: schema.TypeInt,
Computed: true,
},
},
}
}
func dataSourceAlicloudInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ecs.CreateDescribeInstancesRequest()
request.RegionId = client.RegionId
request.Status = d.Get("status").(string)
if v, ok := d.GetOk("ids"); ok && len(v.([]interface{})) > 0 {
request.InstanceIds = convertListToJsonString(v.([]interface{}))
}
if v, ok := d.GetOk("vpc_id"); ok && v.(string) != "" {
request.VpcId = v.(string)
}
if v, ok := d.GetOk("vswitch_id"); ok && v.(string) != "" {
request.VSwitchId = v.(string)
}
if v, ok := d.GetOk("resource_group_id"); ok && v.(string) != "" {
request.ResourceGroupId = v.(string)
}
if v, ok := d.GetOk("availability_zone"); ok && v.(string) != "" {
request.ZoneId = v.(string)
}
if v, ok := d.GetOk("tags"); ok {
var tags []ecs.DescribeInstancesTag
for key, value := range v.(map[string]interface{}) {
tags = append(tags, ecs.DescribeInstancesTag{
Key: key,
Value: value.(string),
})
}
request.Tag = &tags
}
var allInstances []ecs.Instance
if v, ok := d.GetOk("page_number"); ok && v.(int) > 0 {
request.PageNumber = requests.NewInteger(v.(int))
} else {
request.PageNumber = requests.NewInteger(1)
}
if v, ok := d.GetOk("page_size"); ok && v.(int) > 0 {
request.PageSize = requests.NewInteger(v.(int))
} else {
request.PageSize = requests.NewInteger(PageSizeLarge)
}
var response *ecs.DescribeInstancesResponse
for {
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeInstances(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_instances", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*ecs.DescribeInstancesResponse)
if isPagingRequest(d) {
allInstances = response.Instances.Instance
break
}
if len(response.Instances.Instance) < 1 {
break
}
allInstances = append(allInstances, response.Instances.Instance...)
pageSize, err := strconv.Atoi(string(request.PageSize))
if err != nil {
return WrapError(err)
}
if len(response.Instances.Instance) < pageSize {
break
}
if page, err := getNextpageNumber(request.PageNumber); err != nil {
return WrapError(err)
} else {
request.PageNumber = page
}
}
var filteredInstancesTemp []ecs.Instance
nameRegex, ok := d.GetOk("name_regex")
imageId, okImg := d.GetOk("image_id")
if (ok && nameRegex.(string) != "") || (okImg && imageId.(string) != "") {
var instanceNameRegex *regexp.Regexp
if nameRegex != "" {
r, err := regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
instanceNameRegex = r
}
for _, inst := range allInstances {
if instanceNameRegex != nil && !instanceNameRegex.MatchString(inst.InstanceName) {
continue
}
if imageId.(string) != "" && inst.ImageId != imageId.(string) {
continue
}
filteredInstancesTemp = append(filteredInstancesTemp, inst)
}
} else {
filteredInstancesTemp = allInstances
}
// Filter by ram role name and fetch the instance role name
instanceIds := make([]string, 0)
for _, inst := range filteredInstancesTemp {
if inst.InstanceNetworkType == "classic" {
continue
}
instanceIds = append(instanceIds, inst.InstanceId)
}
instanceRoleNameMap := make(map[string]string)
for index := 0; index < len(instanceIds); index += 100 {
// DescribeInstanceRamRole parameter InstanceIds supports at most 100 items once
request := ecs.CreateDescribeInstanceRamRoleRequest()
request.InstanceIds = convertListToJsonString(convertListStringToListInterface(instanceIds[index:IntMin(index+100, len(instanceIds))]))
request.RamRoleName = d.Get("ram_role_name").(string)
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
for {
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeInstanceRamRole(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_instances", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ecs.DescribeInstanceRamRoleResponse)
if len(response.InstanceRamRoleSets.InstanceRamRoleSet) < 1 {
break
}
for _, role := range response.InstanceRamRoleSets.InstanceRamRoleSet {
instanceRoleNameMap[role.InstanceId] = role.RamRoleName
}
if len(response.InstanceRamRoleSets.InstanceRamRoleSet) < PageSizeLarge {
break
}
if page, err := getNextpageNumber(request.PageNumber); err != nil {
return WrapError(err)
} else {
request.PageNumber = page
}
}
}
instanceDiskMappings, err := getInstanceDisksMappings(instanceRoleNameMap, meta)
if err != nil {
return WrapError(err)
}
return instancessDescriptionAttributes(d, filteredInstancesTemp, instanceRoleNameMap, instanceDiskMappings, meta, response.TotalCount)
}
// populate the numerous fields that the instance description returns.
func instancessDescriptionAttributes(d *schema.ResourceData, instances []ecs.Instance, instanceRoleNameMap map[string]string, instanceDisksMap map[string][]map[string]interface{}, meta interface{}, totalCount int) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
var ids []string
var names []string
var s []map[string]interface{}
for _, inst := range instances {
// if instance can not in instanceRoleNameMap, it should be removed.
if _, ok := instanceRoleNameMap[inst.InstanceId]; !ok {
continue
}
mapping := map[string]interface{}{
"id": inst.InstanceId,
"region_id": inst.RegionId,
"availability_zone": inst.ZoneId,
"status": inst.Status,
"name": inst.InstanceName,
"instance_type": inst.InstanceType,
"vpc_id": inst.VpcAttributes.VpcId,
"vswitch_id": inst.VpcAttributes.VSwitchId,
"image_id": inst.ImageId,
"description": inst.Description,
"security_groups": inst.SecurityGroupIds.SecurityGroupId,
"resource_group_id": inst.ResourceGroupId,
"eip": inst.EipAddress.IpAddress,
"key_name": inst.KeyPairName,
"ram_role_name": instanceRoleNameMap[inst.InstanceId],
"spot_strategy": inst.SpotStrategy,
"creation_time": inst.CreationTime,
"instance_charge_type": inst.InstanceChargeType,
"internet_charge_type": inst.InternetChargeType,
"internet_max_bandwidth_out": inst.InternetMaxBandwidthOut,
// Complex types get their own functions
"disk_device_mappings": instanceDisksMap[inst.InstanceId],
"tags": ecsService.tagsToMap(inst.Tags.Tag),
}
if len(inst.InnerIpAddress.IpAddress) > 0 {
mapping["private_ip"] = inst.InnerIpAddress.IpAddress[0]
} else {
mapping["private_ip"] = inst.VpcAttributes.PrivateIpAddress.IpAddress[0]
}
if len(inst.PublicIpAddress.IpAddress) > 0 {
mapping["public_ip"] = inst.PublicIpAddress.IpAddress[0]
} else {
mapping["public_ip"] = inst.VpcAttributes.NatIpAddress
}
ids = append(ids, inst.InstanceId)
names = append(names, inst.InstanceName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
d.Set("ids", ids)
d.Set("names", names)
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if err := d.Set("total_count", totalCount); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
//Returns a mapping of instance disks
func getInstanceDisksMappings(instanceMap map[string]string, meta interface{}) (map[string][]map[string]interface{}, error) {
client := meta.(*connectivity.AliyunClient)
request := ecs.CreateDescribeDisksRequest()
request.PageSize = requests.NewInteger(PageSizeXLarge)
request.PageNumber = requests.NewInteger(1)
instanceDisks := make(map[string][]map[string]interface{})
var allDisks []ecs.Disk
for {
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeDisks(request)
})
if err != nil {
return instanceDisks, WrapErrorf(err, DataDefaultErrorMsg, "alicloud_instances", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ecs.DescribeDisksResponse)
if response == nil || len(response.Disks.Disk) < 1 {
break
}
allDisks = append(allDisks, response.Disks.Disk...)
if len(response.Disks.Disk) < PageSizeXLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return instanceDisks, WrapError(err)
}
request.PageNumber = page
}
for _, disk := range allDisks {
if _, ok := instanceMap[disk.InstanceId]; !ok {
continue
}
mapping := map[string]interface{}{
"device": disk.Device,
"size": disk.Size,
"category": disk.Category,
"type": disk.Type,
}
instanceDisks[disk.InstanceId] = append(instanceDisks[disk.InstanceId], mapping)
}
return instanceDisks, nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudIotDeviceGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudIotDeviceGroupsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"group_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(0, 30),
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"iot_instance_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"super_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"device_active": {
Type: schema.TypeString,
Computed: true,
},
"device_count": {
Type: schema.TypeString,
Computed: true,
},
"device_online": {
Type: schema.TypeString,
Computed: true,
},
"error_message": {
Type: schema.TypeString,
Computed: true,
},
"group_desc": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"group_id": {
Type: schema.TypeString,
Computed: true,
},
"group_name": {
Type: schema.TypeString,
Computed: true,
},
"success": {
Type: schema.TypeBool,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudIotDeviceGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "QueryDeviceGroupList"
request := make(map[string]interface{})
if v, ok := d.GetOk("group_name"); ok {
request["GroupName"] = v
}
if v, ok := d.GetOk("iot_instance_id"); ok {
request["IotInstanceId"] = v
}
if v, ok := d.GetOk("super_group_id"); ok {
request["SuperGroupId"] = v
}
request["PageSize"] = PageSizeLarge
request["CurrentPage"] = 1
var objects []map[string]interface{}
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
nameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewIotClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_iot_device_groups", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.Data.GroupInfo", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Data.GroupInfo", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if nameRegex != nil {
if !nameRegex.MatchString(fmt.Sprint(item["GroupName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["GroupId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["CurrentPage"] = request["CurrentPage"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"error_message": response["ErrorMessage"],
"success": response["Success"],
"create_time": object["UtcCreate"],
"group_desc": object["GroupDesc"],
"group_id": object["GroupId"],
"group_name": object["GroupName"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudIotService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudIotServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudIotServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("IotServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
action := "OpenIotService"
request := map[string]interface{}{}
conn, err := meta.(*connectivity.AliyunClient).NewTeaCommonClient(connectivity.OpenIotService)
if err != nil {
return WrapError(err)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"QPS Limit Exceeded"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
addDebug(action, response, nil)
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"OrderOpend"}) {
d.SetId("IotServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_iot_service", action, AlibabaCloudSdkGoERROR)
}
d.SetId("IotServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudKmsAliases() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudKmsAliasesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"aliases": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"alias_name": {
Type: schema.TypeString,
Computed: true,
},
"key_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudKmsAliasesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListAliases"
request := make(map[string]interface{})
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var aliasNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
aliasNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewKmsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_kms_aliases", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Aliases.Alias", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Aliases.Alias", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if aliasNameRegex != nil {
if !aliasNameRegex.MatchString(fmt.Sprint(item["AliasName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["AliasName"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["AliasName"]),
"alias_name": fmt.Sprint(object["AliasName"]),
"key_id": object["KeyId"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["AliasName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("aliases", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"strconv"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudKmsCiphertext() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudKmsCiphertextRead,
Schema: map[string]*schema.Schema{
"plaintext": {
Type: schema.TypeString,
Required: true,
Sensitive: true,
},
"key_id": {
Type: schema.TypeString,
Required: true,
},
"encryption_context": {
Type: schema.TypeMap,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"ciphertext_blob": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudKmsCiphertextRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
// Since a ciphertext has no ID, we create an ID based on
// current unix time.
d.SetId(strconv.FormatInt(time.Now().Unix(), 16))
action := "Encrypt"
request := make(map[string]interface{})
request["Plaintext"] = d.Get("plaintext")
request["KeyId"] = d.Get("key_id")
request["RegionId"] = client.RegionId
if context := d.Get("encryption_context"); context != nil {
cm := context.(map[string]interface{})
contextJson, err := convertMaptoJsonString(cm)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_kms_ciphertext", action, AlibabaCloudSdkGoERROR)
}
request["EncryptionContext"] = contextJson
}
var response map[string]interface{}
conn, err := client.NewKmsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_kms_ciphertext", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.CiphertextBlob", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.CiphertextBlob", response)
}
d.Set("ciphertext_blob", resp)
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudKmsKeyVersions() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudKmsKeyVersionsRead,
Schema: map[string]*schema.Schema{
"key_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"versions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"key_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"key_version_id": {
Type: schema.TypeString,
Computed: true,
},
"creation_date": {
Type: schema.TypeString,
Computed: true,
Removed: "Attribute 'creation_date' has been removed and using 'create_time' instead.",
},
},
},
},
},
}
}
func dataSourceAlicloudKmsKeyVersionsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListKeyVersions"
request := make(map[string]interface{})
request["KeyId"] = d.Get("key_id")
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewKmsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_kms_key_versions", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.KeyVersions.KeyVersion", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.KeyVersions.KeyVersion", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["KeyVersionId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": object["CreationDate"],
"key_id": object["KeyId"],
"id": fmt.Sprint(object["KeyVersionId"]),
"key_version_id": fmt.Sprint(object["KeyVersionId"]),
"creation_date": object["CreateTime"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("versions", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudKmsKeys() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudKmsKeysRead,
Schema: map[string]*schema.Schema{
"description_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"filters": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Disabled", "Enabled", "PendingDeletion"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"keys": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"arn": {
Type: schema.TypeString,
Computed: true,
},
"automatic_rotation": {
Type: schema.TypeString,
Computed: true,
},
"creator": {
Type: schema.TypeString,
Computed: true,
},
"creation_date": {
Type: schema.TypeString,
Computed: true,
},
"delete_date": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"key_id": {
Type: schema.TypeString,
Computed: true,
},
"key_spec": {
Type: schema.TypeString,
Computed: true,
},
"key_usage": {
Type: schema.TypeString,
Computed: true,
},
"last_rotation_date": {
Type: schema.TypeString,
Computed: true,
},
"material_expire_time": {
Type: schema.TypeString,
Computed: true,
},
"next_rotation_date": {
Type: schema.TypeString,
Computed: true,
},
"origin": {
Type: schema.TypeString,
Computed: true,
},
"primary_key_version": {
Type: schema.TypeString,
Computed: true,
},
"protection_level": {
Type: schema.TypeString,
Computed: true,
},
"rotation_interval": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
},
}
}
func dataSourceAlicloudKmsKeysRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListKeys"
request := make(map[string]interface{})
if v, ok := d.GetOk("filters"); ok {
request["Filters"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var descriptionRegex *regexp.Regexp
if v, ok := d.GetOk("description_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
descriptionRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewKmsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_kms_keys", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Keys.Key", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Keys.Key", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["KeyId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"arn": object["KeyArn"],
"id": fmt.Sprint(object["KeyId"]),
"key_id": fmt.Sprint(object["KeyId"]),
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["KeyId"]))
s = append(s, mapping)
continue
}
kmsService := KmsService{client}
id := fmt.Sprint(object["KeyId"])
getResp, err := kmsService.DescribeKmsKey(id)
if _, ok := getResp["KeyState"]; !ok && err != nil {
return WrapError(err)
}
if descriptionRegex != nil {
if !descriptionRegex.MatchString(fmt.Sprint(getResp["Description"])) {
continue
}
}
if statusOk && status != "" && status != getResp["KeyState"].(string) {
continue
}
mapping["automatic_rotation"] = getResp["AutomaticRotation"]
mapping["creator"] = getResp["Creator"]
mapping["creation_date"] = getResp["CreationDate"]
mapping["delete_date"] = getResp["DeleteDate"]
mapping["description"] = getResp["Description"]
mapping["key_spec"] = getResp["KeySpec"]
mapping["key_usage"] = getResp["KeyUsage"]
mapping["last_rotation_date"] = getResp["LastRotationDate"]
mapping["material_expire_time"] = getResp["MaterialExpireTime"]
mapping["next_rotation_date"] = getResp["NextRotationDate"]
mapping["origin"] = getResp["Origin"]
mapping["primary_key_version"] = getResp["PrimaryKeyVersion"]
mapping["protection_level"] = getResp["ProtectionLevel"]
mapping["rotation_interval"] = getResp["RotationInterval"]
mapping["status"] = getResp["KeyState"]
ids = append(ids, fmt.Sprint(object["KeyId"]))
names = append(names)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("keys", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"strconv"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudKmsPlaintext() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudKmsPlaintextRead,
Schema: map[string]*schema.Schema{
"plaintext": {
Type: schema.TypeString,
Computed: true,
},
"key_id": {
Type: schema.TypeString,
Computed: true,
},
"encryption_context": {
Type: schema.TypeMap,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"ciphertext_blob": {
Type: schema.TypeString,
Required: true,
},
},
}
}
func dataSourceAlicloudKmsPlaintextRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
// Since a plaintext has no ID, we create an ID based on
// current unix time.
d.SetId(strconv.FormatInt(time.Now().Unix(), 16))
action := "Decrypt"
request := make(map[string]interface{})
request["CiphertextBlob"] = d.Get("ciphertext_blob")
request["RegionId"] = client.RegionId
if context := d.Get("encryption_context"); context != nil {
cm := context.(map[string]interface{})
contextJson, err := convertMaptoJsonString(cm)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_kms_plaintext", action, AlibabaCloudSdkGoERROR)
}
request["EncryptionContext"] = contextJson
}
var response map[string]interface{}
conn, err := client.NewKmsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_kms_ciphertext", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Plaintext", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Plaintext", response)
}
d.Set("plaintext", resp)
resp, err = jsonpath.Get("$.KeyId", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.KeyId", response)
}
d.Set("key_id", resp)
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudKmsSecretVersions() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudKmsSecretVersionsRead,
Schema: map[string]*schema.Schema{
"include_deprecated": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"secret_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"version_stage": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"versions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"secret_data": {
Type: schema.TypeString,
Computed: true,
},
"secret_data_type": {
Type: schema.TypeString,
Computed: true,
},
"secret_name": {
Type: schema.TypeString,
Computed: true,
},
"version_id": {
Type: schema.TypeString,
Computed: true,
},
"version_stages": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
},
}
}
func dataSourceAlicloudKmsSecretVersionsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListSecretVersionIds"
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok && len(v.([]interface{})) > 0 {
for _, i := range v.([]interface{}) {
if i == nil {
continue
}
idsMap[i.(string)] = i.(string)
}
}
request := make(map[string]interface{})
if v, ok := d.GetOk("include_deprecated"); ok {
request["IncludeDeprecated"] = v.(string)
}
VersionStage, okStage := d.GetOk("version_stage")
request["SecretName"] = d.Get("secret_name")
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var ids []string
var objects []map[string]interface{}
var response map[string]interface{}
conn, err := client.NewKmsClient()
if err != nil {
return WrapError(err)
}
for {
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_kms_secret_versions", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.VersionIds.VersionId", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.VersionIds.VersionId", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["VersionId"])]; !ok {
continue
}
}
if okStage && VersionStage.(string) != "" {
hasVersionStage := false
for _, VStage := range item["VersionStages"].(map[string]interface{})["VersionStage"].([]interface{}) {
if VStage == VersionStage {
hasVersionStage = true
break
}
}
if !hasVersionStage {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
secretName, err := jsonpath.Get("$.SecretName", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.SecretName", response)
}
s := make([]map[string]interface{}, len(objects))
for i, object := range objects {
mapping := map[string]interface{}{
"secret_name": secretName,
"version_id": object["VersionId"],
"version_stages": object["VersionStages"].(map[string]interface{})["VersionStage"].([]interface{}),
}
ids = append(ids, fmt.Sprint(object["VersionId"]))
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s[i] = mapping
continue
}
action := "GetSecretValue"
var response map[string]interface{}
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
request["VersionId"] = object["VersionId"]
if okStage && VersionStage.(string) != "" {
request["VersionStage"] = VersionStage
}
request["SecretName"] = secretName
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_kms_secret_versions", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
if v, err := jsonpath.Get("$.SecretData", response); err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.SecretData", response)
} else {
mapping["secret_data"] = v
}
if v, err := jsonpath.Get("$.SecretDataType", response); err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.SecretDataType", response)
} else {
mapping["secret_data_type"] = v
}
s[i] = mapping
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("versions", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudKmsSecrets() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudKmsSecretsRead,
Schema: map[string]*schema.Schema{
"fetch_tags": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"filters": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"tags": tagsSchema(),
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"secrets": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"arn": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"encryption_key_id": {
Type: schema.TypeString,
Computed: true,
},
"planned_delete_time": {
Type: schema.TypeString,
Computed: true,
},
"secret_data": {
Type: schema.TypeString,
Computed: true,
},
"secret_data_type": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"secret_name": {
Type: schema.TypeString,
Computed: true,
},
"secret_type": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"version_id": {
Type: schema.TypeString,
Computed: true,
},
"version_stages": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudKmsSecretsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListSecrets"
request := make(map[string]interface{})
if v, ok := d.GetOkExists("fetch_tags"); ok {
request["FetchTags"] = v
}
if v, ok := d.GetOk("filters"); ok {
request["Filters"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var secretNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
secretNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
tagsMap := make(map[string]interface{})
if v, ok := d.GetOk("tags"); ok && len(v.(map[string]interface{})) > 0 {
tagsMap = v.(map[string]interface{})
}
var response map[string]interface{}
conn, err := client.NewKmsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_kms_secrets", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.SecretList.Secret", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.SecretList.Secret", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if secretNameRegex != nil {
if !secretNameRegex.MatchString(fmt.Sprint(item["SecretName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["SecretName"])]; !ok {
continue
}
}
if len(tagsMap) > 0 {
if len(item["Tags"].(map[string]interface{})["Tag"].([]interface{})) != len(tagsMap) {
continue
}
match := true
for _, tag := range item["Tags"].(map[string]interface{})["Tag"].([]interface{}) {
if v, ok := tagsMap[tag.(map[string]interface{})["TagKey"].(string)]; !ok || v.(string) != tag.(map[string]interface{})["TagValue"].(string) {
match = false
break
}
}
if !match {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"planned_delete_time": object["PlannedDeleteTime"],
"id": fmt.Sprint(object["SecretName"]),
"secret_name": fmt.Sprint(object["SecretName"]),
"secret_type": object["SecretType"],
}
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags.Tag", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["TagKey"].(string)
value := t.(map[string]interface{})["TagValue"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["SecretName"]))
names = append(names, object["SecretName"])
s = append(s, mapping)
continue
}
kmsService := KmsService{client}
id := fmt.Sprint(object["SecretName"])
getResp, err := kmsService.DescribeKmsSecret(id)
if err != nil {
return WrapError(err)
}
mapping["arn"] = getResp["Arn"]
mapping["description"] = getResp["Description"]
mapping["encryption_key_id"] = getResp["EncryptionKeyId"]
getResp1, err := kmsService.GetSecretValue(id)
if err != nil {
return WrapError(err)
}
mapping["secret_data"] = getResp1["SecretData"]
mapping["secret_data_type"] = getResp1["SecretDataType"]
mapping["version_id"] = getResp1["VersionId"]
mapping["version_stages"] = getResp1["VersionStages"].(map[string]interface{})["VersionStage"]
ids = append(ids, fmt.Sprint(object["SecretName"]))
names = append(names, object["SecretName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("secrets", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudKmsService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudKmsServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudKmsServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("KmsServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
action := "OpenKmsService"
request := map[string]interface{}{}
conn, err := meta.(*connectivity.AliyunClient).NewTeaCommonClient(connectivity.OpenKmsService)
if err != nil {
return WrapError(err)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"QPS Limit Exceeded"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
addDebug(action, response, nil)
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"Forbidden.Opened"}) {
d.SetId("KmsServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_kms_service", action, AlibabaCloudSdkGoERROR)
}
d.SetId("KmsServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
package alicloud
import (
"fmt"
"regexp"
r_kvstore "github.com/aliyun/alibaba-cloud-sdk-go/services/r-kvstore"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudKvstoreAccounts() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudKvstoreAccountsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"account_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "Unavailable"}, false),
},
"ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"accounts": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"account_name": {
Type: schema.TypeString,
Computed: true,
},
"account_privilege": {
Type: schema.TypeString,
Computed: true,
},
"account_type": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudKvstoreAccountsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := r_kvstore.CreateDescribeAccountsRequest()
if v, ok := d.GetOk("account_name"); ok {
request.AccountName = v.(string)
}
request.InstanceId = d.Get("instance_id").(string)
var objects []r_kvstore.Account
var accountNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
accountNameRegex = r
}
status, statusOk := d.GetOk("status")
var response *r_kvstore.DescribeAccountsResponse
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.DescribeAccounts(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_kvstore_accounts", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ = raw.(*r_kvstore.DescribeAccountsResponse)
for _, item := range response.Accounts.Account {
if accountNameRegex != nil {
if !accountNameRegex.MatchString(item.AccountName) {
continue
}
}
if statusOk && status != "" && status != item.AccountStatus {
continue
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprintf("%v:%v", object.InstanceId, object.AccountName),
"account_name": object.AccountName,
"account_type": object.AccountType,
"description": object.AccountDescription,
"instance_id": object.InstanceId,
"status": object.AccountStatus,
}
if len(object.DatabasePrivileges.DatabasePrivilege) > 0 {
mapping["account_privilege"] = object.DatabasePrivileges.DatabasePrivilege[0].AccountPrivilege
}
ids = append(ids, fmt.Sprintf("%v:%v", object.InstanceId, object.AccountName))
names = append(names, object.AccountName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("accounts", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
r_kvstore "github.com/aliyun/alibaba-cloud-sdk-go/services/r-kvstore"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudKvstoreConnections() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudKvstoreConnectionsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Required: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
MaxItems: 1,
MinItems: 1,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"connections": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"connection_string": {
Type: schema.TypeString,
Computed: true,
},
"db_instance_net_type": {
Type: schema.TypeString,
Computed: true,
},
"expired_time": {
Type: schema.TypeString,
Computed: true,
},
"ip_address": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeString,
Computed: true,
},
"upgradeable": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudKvstoreConnectionsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := r_kvstore.CreateDescribeDBInstanceNetInfoRequest()
var objects []r_kvstore.InstanceNetInfo
var response *r_kvstore.DescribeDBInstanceNetInfoResponse
for _, id := range d.Get("ids").([]interface{}) {
request.InstanceId = id.(string)
}
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.DescribeDBInstanceNetInfo(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_kvstore_connections", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ = raw.(*r_kvstore.DescribeDBInstanceNetInfoResponse)
for _, item := range response.NetInfoItems.InstanceNetInfo {
if item.DBInstanceNetType != "0" {
continue
}
objects = append(objects, item)
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"connection_string": object.ConnectionString,
"db_instance_net_type": object.DBInstanceNetType,
"expired_time": object.ExpiredTime,
"ip_address": object.IPAddress,
"id": request.InstanceId,
"instance_id": request.InstanceId,
"port": object.Port,
"upgradeable": object.Upgradeable,
"vpc_id": object.VPCId,
"vpc_instance_id": object.VPCInstanceId,
"vswitch_id": object.VSwitchId,
}
ids = append(ids, request.InstanceId)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("connections", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"sort"
"strconv"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/bssopenapi"
r_kvstore "github.com/aliyun/alibaba-cloud-sdk-go/services/r-kvstore"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudKVStoreInstanceClasses() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudKVStoreAvailableResourceRead,
Schema: map[string]*schema.Schema{
"zone_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"engine": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
string(KVStoreMemcache),
string(KVStoreRedis),
}, false),
Default: string(KVStoreRedis),
},
"engine_version": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"product_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Local", "Tair_rdb", "Tair_scm", "Tair_essd", "OnECS"}, false),
},
"performance_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"standard_performance_type", "enhance_performance_type"}, false),
Deprecated: "The parameter 'performance_type' has been deprecated from 1.68.0.",
},
"storage_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"inmemory", "hybrid"}, false),
Deprecated: "The parameter 'storage_type' has been deprecated from 1.68.0.",
},
"package_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"standard", "customized"}, false),
Deprecated: "The parameter 'package_type' has been deprecated from 1.68.0.",
},
"architecture": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"standard", "cluster", "rwsplit"}, false),
},
"edition_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Community", "Enterprise"}, false),
},
"series_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"enhanced_performance_type", "hybrid_storage"}, false),
},
"node_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"double", "single", "readone", "readthree", "readfive"}, false),
},
"shard_number": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IntInSlice([]int{1, 2, 4, 8, 16, 32, 64, 128, 256}),
},
"instance_charge_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: PrePaid,
ValidateFunc: validation.StringInSlice([]string{string(PostPaid), string(PrePaid)}, false),
},
"sorted_by": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Price"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"instance_classes": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"classes": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"instance_class": {
Type: schema.TypeString,
Computed: true,
},
"price": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudKVStoreAvailableResourceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := r_kvstore.CreateDescribeAvailableResourceRequest()
request.RegionId = client.RegionId
request.ZoneId = d.Get("zone_id").(string)
instanceChargeType := d.Get("instance_charge_type").(string)
request.InstanceChargeType = instanceChargeType
request.Engine = d.Get("engine").(string)
request.ProductType = d.Get("product_type").(string)
var response = &r_kvstore.DescribeAvailableResourceResponse{}
err := resource.Retry(time.Minute*5, func() *resource.RetryError {
raw, err := client.WithRkvClient(func(rkvClient *r_kvstore.Client) (interface{}, error) {
return rkvClient.DescribeAvailableResource(request)
})
if err != nil {
if IsExpectedErrors(err, []string{Throttling}) {
time.Sleep(time.Duration(5) * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response = raw.(*r_kvstore.DescribeAvailableResourceResponse)
return nil
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_kvstore_instance_classes", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
var instanceClasses []string
var ids []string
engineVersion, engineVersionGot := d.GetOk("engine_version")
architecture, architectureGot := d.GetOk("architecture")
editionType, editionTypeGot := d.GetOk("edition_type")
seriesType, seriesTypeGot := d.GetOk("series_type")
shardNumber, shardNumberGot := d.GetOk("shard_number")
nodeType, nodeTypeGot := d.GetOk("node_type")
for _, AvailableZone := range response.AvailableZones.AvailableZone {
zondId := AvailableZone.ZoneId
ids = append(ids, zondId)
for _, SupportedEngine := range AvailableZone.SupportedEngines.SupportedEngine {
ids = append(ids, SupportedEngine.Engine)
for _, SupportedEditionType := range SupportedEngine.SupportedEditionTypes.SupportedEditionType {
if editionTypeGot && editionType.(string) != SupportedEditionType.EditionType {
continue
}
ids = append(ids, SupportedEditionType.EditionType)
for _, SupportedSeriesType := range SupportedEditionType.SupportedSeriesTypes.SupportedSeriesType {
if seriesTypeGot && seriesType.(string) != SupportedSeriesType.SeriesType {
continue
}
for _, SupportedEngineVersion := range SupportedSeriesType.SupportedEngineVersions.SupportedEngineVersion {
if engineVersionGot && engineVersion.(string) != SupportedEngineVersion.Version {
continue
}
for _, SupportedArchitectureType := range SupportedEngineVersion.SupportedArchitectureTypes.SupportedArchitectureType {
if architectureGot && architecture.(string) != SupportedArchitectureType.Architecture {
continue
}
for _, SupportedShardNumber := range SupportedArchitectureType.SupportedShardNumbers.SupportedShardNumber {
number, _ := strconv.Atoi(SupportedShardNumber.ShardNumber)
if shardNumberGot && shardNumber.(int) != number {
continue
}
for _, SupportedNodeType := range SupportedShardNumber.SupportedNodeTypes.SupportedNodeType {
if nodeTypeGot && nodeType.(string) != SupportedNodeType.SupportedNodeType {
continue
}
for _, AvailableResource := range SupportedNodeType.AvailableResources.AvailableResource {
instanceClasses = append(instanceClasses, AvailableResource.InstanceClass)
}
}
}
}
}
}
}
}
}
d.SetId(dataResourceIdHash(ids))
var instanceClassPrices []map[string]interface{}
sortedBy := d.Get("sorted_by").(string)
if sortedBy == "Price" && len(instanceClasses) > 0 {
bssopenapiService := BssopenapiService{client}
priceList, err := getKVStoreInstanceClassPrice(bssopenapiService, instanceChargeType, instanceClasses)
if err != nil {
return WrapError(err)
}
for i, instanceClass := range instanceClasses {
classPrice := map[string]interface{}{
"instance_class": instanceClass,
"price": fmt.Sprintf("%.4f", priceList[i]),
}
instanceClassPrices = append(instanceClassPrices, classPrice)
}
sort.SliceStable(instanceClassPrices, func(i, j int) bool {
iPrice, _ := strconv.ParseFloat(instanceClassPrices[i]["price"].(string), 64)
jPrice, _ := strconv.ParseFloat(instanceClassPrices[j]["price"].(string), 64)
return iPrice < jPrice
})
err = d.Set("classes", instanceClassPrices)
if err != nil {
return WrapError(err)
}
instanceClasses = instanceClasses[:0]
for _, instanceClass := range instanceClassPrices {
instanceClasses = append(instanceClasses, instanceClass["instance_class"].(string))
}
}
err = d.Set("instance_classes", instanceClasses)
if err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok {
err = writeToFile(output.(string), instanceClassPrices)
if err != nil {
return WrapError(err)
}
}
return nil
}
func getKVStoreInstanceClassPrice(bssopenapiService BssopenapiService, instanceChargeType string, instanceClasses []string) ([]float64, error) {
client := bssopenapiService.client
var modules interface{}
moduleCode := "InstanceClass"
var payAsYouGo []bssopenapi.GetPayAsYouGoPriceModuleList
var subsciption []bssopenapi.GetSubscriptionPriceModuleList
for _, instanceClass := range instanceClasses {
config := fmt.Sprintf("InstanceClass:%s,Region:%s", instanceClass, client.Region)
if instanceChargeType == string(PostPaid) {
payAsYouGo = append(payAsYouGo, bssopenapi.GetPayAsYouGoPriceModuleList{
ModuleCode: moduleCode,
Config: config,
PriceType: "Hour",
})
} else {
subsciption = append(subsciption, bssopenapi.GetSubscriptionPriceModuleList{
ModuleCode: moduleCode,
Config: config,
})
}
}
if len(payAsYouGo) != 0 {
modules = payAsYouGo
} else {
modules = subsciption
}
return bssopenapiService.GetInstanceTypePrice("redisa", "", modules)
}
package alicloud
import (
"strings"
"time"
r_kvstore "github.com/aliyun/alibaba-cloud-sdk-go/services/r-kvstore"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudKVStoreInstanceEngines() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudKVStoreInstanceEnginesRead,
Schema: map[string]*schema.Schema{
"zone_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"engine": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
string(KVStoreMemcache),
string(KVStoreRedis),
}, false),
Default: string(KVStoreRedis),
},
"engine_version": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"instance_charge_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: PrePaid,
ValidateFunc: validation.StringInSlice([]string{string(PostPaid), string(PrePaid)}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values.
"instance_engines": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
"engine": {
Type: schema.TypeString,
Computed: true,
},
"engine_version": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudKVStoreInstanceEnginesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := r_kvstore.CreateDescribeAvailableResourceRequest()
request.RegionId = client.RegionId
request.ZoneId = d.Get("zone_id").(string)
instanceChargeType := d.Get("instance_charge_type").(string)
request.InstanceChargeType = instanceChargeType
request.Engine = d.Get("engine").(string)
var response = &r_kvstore.DescribeAvailableResourceResponse{}
err := resource.Retry(time.Minute*5, func() *resource.RetryError {
raw, err := client.WithRkvClient(func(rkvClient *r_kvstore.Client) (interface{}, error) {
return rkvClient.DescribeAvailableResource(request)
})
if err != nil {
if IsExpectedErrors(err, []string{Throttling}) {
time.Sleep(time.Duration(5) * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response = raw.(*r_kvstore.DescribeAvailableResourceResponse)
return nil
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_kvstore_instance_engines", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
var infos []map[string]interface{}
var ids []string
engine, engineGot := d.GetOk("engine")
engine = strings.ToLower(engine.(string))
engineVersion, engineVersionGot := d.GetOk("engine_version")
for _, AvailableZone := range response.AvailableZones.AvailableZone {
zondId := AvailableZone.ZoneId
ids = append(ids, zondId)
versions := make(map[string]interface{})
for _, SupportedEngine := range AvailableZone.SupportedEngines.SupportedEngine {
if engineGot && engine != SupportedEngine.Engine {
continue
}
ids = append(ids, SupportedEngine.Engine)
if strings.ToLower(engine.(string)) == "memcache" {
info := make(map[string]interface{})
info["zone_id"] = AvailableZone.ZoneId
info["engine"] = SupportedEngine.Engine
info["engine_version"] = "2.8"
ids = append(ids, "2.8")
infos = append(infos, info)
} else {
for _, editionType := range SupportedEngine.SupportedEditionTypes.SupportedEditionType {
for _, seriesType := range editionType.SupportedSeriesTypes.SupportedSeriesType {
for _, SupportedEngineVersion := range seriesType.SupportedEngineVersions.SupportedEngineVersion {
if engineVersionGot && engineVersion.(string) != SupportedEngineVersion.Version {
continue
}
versions[SupportedEngineVersion.Version] = nil
}
}
}
for version := range versions {
info := make(map[string]interface{})
info["zone_id"] = AvailableZone.ZoneId
info["engine"] = SupportedEngine.Engine
info["engine_version"] = version
ids = append(ids, version)
infos = append(infos, info)
}
}
}
}
d.SetId(dataResourceIdHash(ids))
err = d.Set("instance_engines", infos)
if err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok {
err = writeToFile(output.(string), infos)
if err != nil {
return WrapError(err)
}
}
return nil
}
package alicloud
import (
"encoding/json"
"regexp"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
r_kvstore "github.com/aliyun/alibaba-cloud-sdk-go/services/r-kvstore"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudKvstoreInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudKvstoreInstancesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"architecture_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"SplitRW", "cluster", "standard"}, false),
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"edition_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Enterprise", "Community"}, false),
},
"engine_version": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"2.8", "4.0", "5.0", "6.0"}, false),
},
"expired": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"global_instance": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"instance_class": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"instance_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Memcache", "Redis"}, false),
},
"network_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"CLASSIC", "VPC"}, false),
},
"payment_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PostPaid", "PrePaid"}, false),
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"search_key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Changing", "CleaningUpExpiredData", "Creating", "Flushing", "HASwitching", "Inactive", "MajorVersionUpgrading", "Migrating", "NetworkModifying", "Normal", "Rebooting", "SSLModifying", "Transforming", "ZoneMigrating"}, false),
},
"tags": tagsSchema(),
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"architecture_type": {
Type: schema.TypeString,
Computed: true,
},
"auto_renew": {
Type: schema.TypeBool,
Computed: true,
},
"auto_renew_period": {
Type: schema.TypeInt,
Computed: true,
},
"bandwidth": {
Type: schema.TypeInt,
Computed: true,
},
"capacity": {
Type: schema.TypeInt,
Computed: true,
},
"config": {
Type: schema.TypeMap,
Computed: true,
},
"connection_mode": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"db_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"db_instance_name": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"destroy_time": {
Type: schema.TypeString,
Computed: true,
},
"end_time": {
Type: schema.TypeString,
Computed: true,
},
"expire_time": {
Type: schema.TypeString,
Computed: true,
},
"engine_version": {
Type: schema.TypeString,
Computed: true,
},
"has_renew_change_order": {
Type: schema.TypeBool,
Computed: true,
},
"instance_class": {
Type: schema.TypeString,
Computed: true,
},
"instance_release_protection": {
Type: schema.TypeBool,
Computed: true,
},
"instance_type": {
Type: schema.TypeString,
Computed: true,
},
"is_rds": {
Type: schema.TypeBool,
Computed: true,
},
"maintain_end_time": {
Type: schema.TypeString,
Computed: true,
},
"maintain_start_time": {
Type: schema.TypeString,
Computed: true,
},
"max_connections": {
Type: schema.TypeInt,
Computed: true,
},
"connections": {
Type: schema.TypeInt,
Computed: true,
},
"network_type": {
Type: schema.TypeString,
Computed: true,
},
"node_type": {
Type: schema.TypeString,
Computed: true,
},
"package_type": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"charge_type": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeInt,
Computed: true,
},
"private_ip": {
Type: schema.TypeString,
Computed: true,
},
"qps": {
Type: schema.TypeInt,
Computed: true,
},
"replacate_id": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"ssl_enable": {
Type: schema.TypeString,
Computed: true,
},
"search_key": {
Type: schema.TypeString,
Computed: true,
},
"security_group_id": {
Type: schema.TypeString,
Computed: true,
},
"security_ip_group_attribute": {
Type: schema.TypeString,
Computed: true,
},
"security_ip_group_name": {
Type: schema.TypeString,
Computed: true,
},
"secondary_zone_id": {
Type: schema.TypeString,
Computed: true,
},
"security_ips": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_auth_mode": {
Type: schema.TypeString,
Computed: true,
},
"vpc_cloud_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
"availability_zone": {
Type: schema.TypeString,
Computed: true,
},
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"user_name": {
Type: schema.TypeString,
Computed: true,
},
"connection_domain": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudKvstoreInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := r_kvstore.CreateDescribeInstancesRequest()
request.RegionId = client.RegionId
if v, ok := d.GetOk("architecture_type"); ok {
request.ArchitectureType = v.(string)
}
if v, ok := d.GetOk("edition_type"); ok {
request.EditionType = v.(string)
}
if v, ok := d.GetOk("engine_version"); ok {
request.EngineVersion = v.(string)
}
if v, ok := d.GetOk("expired"); ok {
request.Expired = v.(string)
}
if v, ok := d.GetOkExists("global_instance"); ok {
request.GlobalInstance = requests.NewBoolean(v.(bool))
}
if v, ok := d.GetOk("instance_class"); ok {
request.InstanceClass = v.(string)
}
if v, ok := d.GetOk("instance_type"); ok {
request.InstanceType = v.(string)
}
if v, ok := d.GetOk("network_type"); ok {
request.NetworkType = v.(string)
}
if v, ok := d.GetOk("payment_type"); ok {
request.ChargeType = v.(string)
}
if v, ok := d.GetOk("resource_group_id"); ok {
request.ResourceGroupId = v.(string)
}
if v, ok := d.GetOk("search_key"); ok {
request.SearchKey = v.(string)
}
if v, ok := d.GetOk("status"); ok {
request.InstanceStatus = v.(string)
}
if v, ok := d.GetOk("tags"); ok {
tags := make([]r_kvstore.DescribeInstancesTag, len(v.(map[string]interface{})))
i := 0
for key, value := range v.(map[string]interface{}) {
tags[i] = r_kvstore.DescribeInstancesTag{
Key: key,
Value: value.(string),
}
i++
}
request.Tag = &tags
}
if v, ok := d.GetOk("vswitch_id"); ok {
request.VSwitchId = v.(string)
}
if v, ok := d.GetOk("vpc_id"); ok {
request.VpcId = v.(string)
}
if v, ok := d.GetOk("zone_id"); ok {
request.ZoneId = v.(string)
}
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var objects []r_kvstore.KVStoreInstance
var dBInstanceNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
dBInstanceNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response *r_kvstore.DescribeInstancesResponse
for {
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.DescribeInstances(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_kvstore_instances", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ = raw.(*r_kvstore.DescribeInstancesResponse)
for _, item := range response.Instances.KVStoreInstance {
if dBInstanceNameRegex != nil {
if !dBInstanceNameRegex.MatchString(item.InstanceName) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[item.InstanceId]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(response.Instances.KVStoreInstance) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
ids := make([]string, 0)
names := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
m := make(map[string]string)
err := json.Unmarshal([]byte(object.Config), &m)
mapping := map[string]interface{}{
"architecture_type": object.ArchitectureType,
"bandwidth": object.Bandwidth,
"capacity": object.Capacity,
"config": m,
"connection_mode": object.ConnectionMode,
"id": object.InstanceId,
"db_instance_id": object.InstanceId,
"db_instance_name": object.InstanceName,
"name": object.InstanceName,
"destroy_time": object.DestroyTime,
"end_time": object.EndTime,
"expire_time": object.EndTime,
"engine_version": object.EngineVersion,
"has_renew_change_order": object.HasRenewChangeOrder,
"instance_class": object.InstanceClass,
"instance_type": object.InstanceType,
"is_rds": object.IsRds,
"max_connections": object.Connections,
"connections": object.Connections,
"network_type": object.NetworkType,
"node_type": object.NodeType,
"package_type": object.PackageType,
"payment_type": object.ChargeType,
"charge_type": object.ChargeType,
"port": object.Port,
"private_ip": object.PrivateIp,
"qps": object.QPS,
"replacate_id": object.ReplacateId,
"resource_group_id": object.ResourceGroupId,
"search_key": object.SearchKey,
"status": object.InstanceStatus,
"vswitch_id": object.VSwitchId,
"vpc_cloud_instance_id": object.VpcCloudInstanceId,
"vpc_id": object.VpcId,
"zone_id": object.ZoneId,
"availability_zone": object.ZoneId,
"region_id": object.RegionId,
"create_time": object.CreateTime,
"user_name": object.UserName,
"connection_domain": object.ConnectionDomain,
}
ids = append(ids, object.InstanceId)
tags := make(map[string]string)
for _, t := range object.Tags.Tag {
if !ignoredTags(t.Key, t.Value) {
tags[t.Key] = t.Value
}
}
mapping["tags"] = tags
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
names = append(names, object.InstanceName)
s = append(s, mapping)
continue
}
request := r_kvstore.CreateDescribeInstanceAttributeRequest()
request.RegionId = client.RegionId
request.InstanceId = object.InstanceId
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.DescribeInstanceAttribute(request)
})
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
responseGet, _ := raw.(*r_kvstore.DescribeInstanceAttributeResponse)
if len(responseGet.Instances.DBInstanceAttribute) > 0 {
mapping["instance_release_protection"] = responseGet.Instances.DBInstanceAttribute[0].InstanceReleaseProtection
mapping["maintain_end_time"] = responseGet.Instances.DBInstanceAttribute[0].MaintainEndTime
mapping["maintain_start_time"] = responseGet.Instances.DBInstanceAttribute[0].MaintainStartTime
mapping["vpc_auth_mode"] = responseGet.Instances.DBInstanceAttribute[0].VpcAuthMode
mapping["secondary_zone_id"] = responseGet.Instances.DBInstanceAttribute[0].SecondaryZoneId
}
request1 := r_kvstore.CreateDescribeInstanceAutoRenewalAttributeRequest()
request1.RegionId = client.RegionId
request1.DBInstanceId = object.InstanceId
request1.ClientToken = buildClientToken(request1.GetActionName())
raw1, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.DescribeInstanceAutoRenewalAttribute(request1)
})
if err != nil {
if !IsExpectedErrors(err, []string{"InvalidOrderCharge.NotSupport"}) {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_kvstore_instances", request1.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
addDebug(request1.GetActionName(), raw1, request1.RpcRequest, request1)
responseGet1, _ := raw1.(*r_kvstore.DescribeInstanceAutoRenewalAttributeResponse)
if len(responseGet1.Items.Item) > 0 {
mapping["auto_renew"] = responseGet1.Items.Item[0].AutoRenew
mapping["auto_renew_period"] = responseGet1.Items.Item[0].Duration
}
request2 := r_kvstore.CreateDescribeInstanceSSLRequest()
request2.RegionId = client.RegionId
request2.InstanceId = object.InstanceId
raw2, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.DescribeInstanceSSL(request2)
})
addDebug(request2.GetActionName(), raw2, request2.RpcRequest, request2)
responseGet2, _ := raw2.(*r_kvstore.DescribeInstanceSSLResponse)
mapping["ssl_enable"] = responseGet2.SSLEnabled
request3 := r_kvstore.CreateDescribeSecurityGroupConfigurationRequest()
request3.RegionId = client.RegionId
request3.InstanceId = object.InstanceId
raw3, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.DescribeSecurityGroupConfiguration(request3)
})
addDebug(request3.GetActionName(), raw3, request3.RpcRequest, request3)
responseGet3, _ := raw3.(*r_kvstore.DescribeSecurityGroupConfigurationResponse)
if len(responseGet3.Items.EcsSecurityGroupRelation) > 0 {
mapping["security_group_id"] = responseGet3.Items.EcsSecurityGroupRelation[0].SecurityGroupId
}
request4 := r_kvstore.CreateDescribeSecurityIpsRequest()
request4.RegionId = client.RegionId
request4.InstanceId = object.InstanceId
raw4, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.DescribeSecurityIps(request4)
})
addDebug(request4.GetActionName(), raw4, request4.RpcRequest, request4)
responseGet4, _ := raw4.(*r_kvstore.DescribeSecurityIpsResponse)
if len(responseGet4.SecurityIpGroups.SecurityIpGroup) > 0 {
mapping["security_ip_group_attribute"] = responseGet4.SecurityIpGroups.SecurityIpGroup[0].SecurityIpGroupAttribute
mapping["security_ip_group_name"] = responseGet4.SecurityIpGroups.SecurityIpGroup[0].SecurityIpGroupName
mapping["security_ips"] = strings.Split(responseGet4.SecurityIpGroups.SecurityIpGroup[0].SecurityIpList, ",")
}
names = append(names, object.InstanceName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
r_kvstore "github.com/aliyun/alibaba-cloud-sdk-go/services/r-kvstore"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudKVStorePermission() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudKVStorePermissionRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudKVStorePermissionRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("KVStorePermissionHasNotBeenInitialize")
d.Set("status", "")
return nil
}
client := meta.(*connectivity.AliyunClient)
request := r_kvstore.CreateInitializeKvstorePermissionRequest()
raw, err := client.WithRkvClient(func(rkvClient *r_kvstore.Client) (interface{}, error) {
return rkvClient.InitializeKvstorePermission(request)
})
if err != nil {
return WrapError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetId("KVStorePermissionHasBeenInitialize")
d.Set("status", "Initialized")
return nil
}
package alicloud
import (
"fmt"
"sort"
"strings"
r_kvstore "github.com/aliyun/alibaba-cloud-sdk-go/services/r-kvstore"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudKVStoreZones() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudKVStoreZoneRead,
Schema: map[string]*schema.Schema{
"multi": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"instance_charge_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: PostPaid,
ValidateFunc: validation.StringInSlice([]string{"PrePaid", "PostPaid"}, false),
},
"engine": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "redis",
ValidateFunc: validation.StringInSlice([]string{"redis", "memcache"}, true),
},
"product_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Local", "Tair_rdb", "Tair_scm", "Tair_essd", "OnECS"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"zones": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"multi_zone_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
},
}
}
func dataSourceAlicloudKVStoreZoneRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
multi := d.Get("multi").(bool)
var zoneIds []string
instanceChargeType := d.Get("instance_charge_type").(string)
request := r_kvstore.CreateDescribeAvailableResourceRequest()
request.RegionId = client.RegionId
request.InstanceChargeType = instanceChargeType
request.Engine = d.Get("engine").(string)
request.ProductType = d.Get("product_type").(string)
raw, err := client.WithRkvClient(func(rkvClient *r_kvstore.Client) (interface{}, error) {
return rkvClient.DescribeAvailableResource(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_kvstore_zones", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
zones, _ := raw.(*r_kvstore.DescribeAvailableResourceResponse)
if len(zones.AvailableZones.AvailableZone) <= 0 {
return WrapError(fmt.Errorf("[ERROR] There is no available zones for KVStore"))
}
for _, zone := range zones.AvailableZones.AvailableZone {
if multi && strings.Contains(zone.ZoneId, MULTI_IZ_SYMBOL) {
zoneIds = append(zoneIds, zone.ZoneId)
continue
}
if !multi && !strings.Contains(zone.ZoneId, MULTI_IZ_SYMBOL) {
zoneIds = append(zoneIds, zone.ZoneId)
}
}
if len(zoneIds) > 0 {
sort.Strings(zoneIds)
}
var s []map[string]interface{}
if !multi {
for _, zoneId := range zoneIds {
mapping := map[string]interface{}{"id": zoneId}
s = append(s, mapping)
}
} else {
for _, zoneId := range zoneIds {
mapping := map[string]interface{}{
"id": zoneId,
"multi_zone_ids": splitMultiZoneId(zoneId),
}
s = append(s, mapping)
}
}
d.SetId(dataResourceIdHash(zoneIds))
if err := d.Set("zones", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", zoneIds); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudLindormInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudLindormInstancesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"query_str": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ACTIVATION", "CLASS_CHANGING", "CREATING", "DELETED", "INSTANCE_LEVEL_MODIFY", "LOCKED", "MINOR_VERSION_TRANSING", "NET_MODIFYING", "RESIZING", "RESTARTING"}, false),
},
"support_engine": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IntBetween(1, 7),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"auto_renew": {
Type: schema.TypeString,
Computed: true,
},
"cold_storage": {
Type: schema.TypeInt,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"deletion_proection": {
Type: schema.TypeBool,
Computed: true,
},
"disk_category": {
Type: schema.TypeString,
Computed: true,
},
"disk_usage": {
Type: schema.TypeString,
Computed: true,
},
"disk_warning_threshold": {
Type: schema.TypeString,
Computed: true,
},
"engine_type": {
Type: schema.TypeInt,
Computed: true,
},
"expired_time": {
Type: schema.TypeString,
Computed: true,
},
"file_engine_node_count": {
Type: schema.TypeInt,
Computed: true,
},
"file_engine_specification": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_name": {
Type: schema.TypeString,
Computed: true,
},
"instance_storage": {
Type: schema.TypeString,
Computed: true,
},
"ip_white_list": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"lts_node_count": {
Type: schema.TypeInt,
Computed: true,
},
"lts_node_specification": {
Type: schema.TypeString,
Computed: true,
},
"network_type": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"phoenix_node_count": {
Type: schema.TypeInt,
Computed: true,
},
"phoenix_node_specification": {
Type: schema.TypeString,
Computed: true,
},
"resource_owner_id": {
Type: schema.TypeString,
Computed: true,
},
"search_engine_node_count": {
Type: schema.TypeInt,
Computed: true,
},
"search_engine_specification": {
Type: schema.TypeString,
Computed: true,
},
"service_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"table_engine_node_count": {
Type: schema.TypeInt,
Computed: true,
},
"table_engine_specification": {
Type: schema.TypeString,
Computed: true,
},
"time_series_engine_node_count": {
Type: schema.TypeInt,
Computed: true,
},
"time_serires_engine_specification": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudLindormInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "GetLindormInstanceList"
request := make(map[string]interface{})
if v, ok := d.GetOk("query_str"); ok {
request["QueryStr"] = v
}
if v, ok := d.GetOk("support_engine"); ok {
request["SupportEngine"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var instanceNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
instanceNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, val := range v.([]interface{}) {
if val == nil {
continue
}
idsMap[val.(string)] = val.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewHitsdbClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_lindorm_instances", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.InstanceList", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.InstanceList", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if instanceNameRegex != nil && !instanceNameRegex.MatchString(fmt.Sprint(item["InstanceAlias"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["InstanceId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["InstanceStatus"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": fmt.Sprint(object["CreateMilliseconds"]),
"engine_type": formatInt(object["EngineType"]),
"expired_time": fmt.Sprint(object["ExpiredMilliseconds"]),
"id": fmt.Sprint(object["InstanceId"]),
"instance_id": fmt.Sprint(object["InstanceId"]),
"instance_name": object["InstanceAlias"],
"instance_storage": object["InstanceStorage"],
"network_type": object["NetworkType"],
"payment_type": convertLindormInstancePaymentTypeResponse(object["PayType"]),
"service_type": object["ServiceType"],
"status": object["InstanceStatus"],
"vpc_id": object["VpcId"],
"zone_id": object["ZoneId"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["InstanceAlias"])
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["InstanceId"])
hitsdbService := HitsdbService{client}
ipWhiteList, err := hitsdbService.GetInstanceIpWhiteList(id)
if err != nil {
return WrapError(err)
}
mapping["ip_white_list"] = convertListToJsonString(ipWhiteList)
getResp1, err := hitsdbService.DescribeLindormInstance(id)
if err != nil {
return WrapError(err)
}
mapping["auto_renew"] = getResp1["AutoRenew"]
if v, ok := getResp1["ColdStorage"]; ok {
mapping["cold_storage"] = formatInt(v)
}
mapping["deletion_proection"] = getResp1["DeletionProtection"]
mapping["disk_category"] = getResp1["DiskCategory"]
mapping["disk_usage"] = getResp1["DiskUsage"]
mapping["disk_warning_threshold"] = getResp1["DiskThreshold"]
mapping["resource_owner_id"] = getResp1["AliUid"]
mapping["vswitch_id"] = getResp1["VswitchId"]
getResp2, err := hitsdbService.GetLindormInstanceEngineInfo(id)
if err != nil {
return WrapError(err)
}
if v, ok := getResp2["FileEngineNodeCount"]; ok {
mapping["file_engine_node_count"] = formatInt(v)
}
mapping["file_engine_specification"] = getResp2["FileEngineSpecification"]
if v, ok := getResp2["LtsNodeCount"]; ok {
mapping["lts_node_count"] = formatInt(v)
}
mapping["lts_node_specification"] = getResp2["LtsNodeSpecification"]
if v, ok := getResp2["PhoenixNodeCount"]; ok {
mapping["phoenix_node_count"] = formatInt(v)
}
mapping["phoenix_node_specification"] = getResp2["PhoenixNodeSpecification"]
if v, ok := getResp2["SearchEngineNodeCount"]; ok {
mapping["search_engine_node_count"] = formatInt(v)
}
mapping["search_engine_specification"] = getResp2["SearchEngineSpecification"]
if v, ok := getResp2["TableEngineNodeCount"]; ok {
mapping["table_engine_node_count"] = formatInt(v)
}
mapping["table_engine_specification"] = getResp2["TableEngineSpecification"]
if v, ok := getResp2["TimeSeriesNodeCount"]; ok {
mapping["time_series_engine_node_count"] = formatInt(v)
}
mapping["time_serires_engine_specification"] = getResp2["TimeSeriesSpecification"]
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
sls "github.com/aliyun/aliyun-log-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudLogProjects() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudLogProjectsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Normal", "Disable"}, true),
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"projects": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"last_modify_time": {
Type: schema.TypeString,
Computed: true,
},
"owner": {
Type: schema.TypeString,
Computed: true,
},
"project_name": {
Type: schema.TypeString,
Computed: true,
},
"region": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudLogProjectsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logService := LogService{client}
var objects []*sls.LogProject
var logProjectNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
logProjectNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response []string
err := resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
return slsClient.ListProject()
})
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout}) {
time.Sleep(5 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
response, _ = raw.([]string)
return nil
})
addDebug("ListProject", response)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_log_projects", "ListProject", AliyunLogGoSdkERROR)
}
for _, projectName := range response {
if logProjectNameRegex != nil {
if !logProjectNameRegex.MatchString(projectName) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[projectName]; !ok {
continue
}
}
project, err := logService.DescribeLogProject(projectName)
if err != nil {
if NotFoundError(err) {
log.Printf("The project '%s' is no exist! \n", projectName)
continue
}
return WrapError(err)
}
if statusOk && status.(string) != "" && status.(string) != project.Status {
continue
}
objects = append(objects, project)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": object.Name,
"description": object.Description,
"last_modify_time": object.LastModifyTime,
"owner": object.Owner,
"project_name": object.Name,
"region": object.Region,
"status": object.Status,
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object.Name)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("projects", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"time"
rpc "github.com/alibabacloud-go/tea-rpc/client"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
const maxWaitTime = 60
func dataSourceAlicloudLogService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudLogServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudLogServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("LogServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
conn, err := meta.(*connectivity.AliyunClient).NewTeaCommonClient(fmt.Sprintf("%s.log.aliyuncs.com/open-api", meta.(*connectivity.AliyunClient).RegionId))
if err != nil {
return WrapError(err)
}
isNotOpened, err := waitServiceReady(conn, false)
if err == nil {
d.SetId("LogServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
if isNotOpened {
response, err := conn.DoRequest(StringPointer("OpenSlsService"), nil, StringPointer("POST"), StringPointer("2019-10-23"), StringPointer("AK"), nil, nil, &util.RuntimeOptions{})
addDebug("OpenSlsService", response, nil)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_log_service", "OpenLogService", AlibabaCloudSdkGoERROR)
}
if response["Success"] != nil && !response["Success"].(bool) {
return WrapErrorf(fmt.Errorf("%s", response), DataDefaultErrorMsg, "alicloud_log_service", "OpenLogService", AlibabaCloudSdkGoERROR)
}
_, err = waitServiceReady(conn, true)
if err == nil {
d.SetId("LogServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapError(err)
}
return WrapError(err)
}
func waitServiceReady(conn *rpc.Client, hasOpened bool) (bool, error) {
beginTime := time.Now().Unix()
for {
response, err := conn.DoRequest(StringPointer("GetSlsService"), nil, StringPointer("POST"), StringPointer("2019-10-23"), StringPointer("AK"), nil, nil, &util.RuntimeOptions{})
addDebug("GetSlsService", response, nil)
if err != nil {
return false, WrapErrorf(err, DataDefaultErrorMsg, "alicloud_log_service", "GetLogService", AlibabaCloudSdkGoERROR)
}
if response["Success"] != nil && !response["Success"].(bool) {
return false, WrapErrorf(fmt.Errorf("%s", response), DataDefaultErrorMsg, "alicloud_log_service", "GetLogService", AlibabaCloudSdkGoERROR)
}
status := response["Status"].(string)
if "Opened" == status {
return false, nil
}
if hasOpened || "Opening" == status {
if time.Now().Unix()-beginTime >= maxWaitTime {
return false, fmt.Errorf("wait until the maxWaitTime(60s) is still in the %s state", status)
}
time.Sleep(time.Second)
continue
}
return true, fmt.Errorf("incorrect status: %s", status)
}
}
package alicloud
import (
"fmt"
"regexp"
"time"
sls "github.com/aliyun/aliyun-log-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudLogStores() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudLogStoresRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"project": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"stores": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"store_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudLogStoresRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
objects := make([]string, 0)
var logStoreNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
logStoreNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
project := d.Get("project").(string)
var response []string
err := resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
return slsClient.ListLogStore(project)
})
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout}) {
time.Sleep(5 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
response, _ = raw.([]string)
return nil
})
addDebug("ListLogStore", response)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_log_stores", "ListLogStore", AliyunLogGoSdkERROR)
}
for _, v := range response {
if logStoreNameRegex != nil {
if !logStoreNameRegex.MatchString(v) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[v]; !ok {
continue
}
}
objects = append(objects, v)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": object,
"store_name": object,
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("stores", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"github.com/aliyun/alibaba-cloud-sdk-go/services/market"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudProduct() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudProductRead,
Schema: map[string]*schema.Schema{
"product_code": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"available_region": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
// Computed values.
"product": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"code": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"skus": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"sku_code": {
Type: schema.TypeString,
Computed: true,
},
"sku_name": {
Type: schema.TypeString,
Computed: true,
},
"package_versions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
// Currently, the API products can return package_version, but others can not for ensure.
"package_version": {
Type: schema.TypeString,
Computed: true,
},
"package_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"images": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"image_id": {
Type: schema.TypeString,
Computed: true,
},
"image_name": {
Type: schema.TypeString,
Computed: true,
},
"region_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudProductRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := market.CreateDescribeProductRequest()
request.Code = d.Get("product_code").(string)
raw, err := client.WithMarketClient(func(marketClient *market.Client) (interface{}, error) {
return marketClient.DescribeProduct(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_market_product", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*market.DescribeProductResponse)
return productDescriptionAttributes(d, response)
}
func productDescriptionAttributes(d *schema.ResourceData, product *market.DescribeProductResponse) error {
var s []map[string]interface{}
var skus []map[string]interface{}
for _, sku := range product.ProductSkus.ProductSku {
skuMapping := map[string]interface{}{
"sku_code": sku.Code,
"sku_name": sku.Name,
}
var imageIdMap []map[string]interface{}
var pvMapSli []map[string]interface{}
for _, module := range sku.Modules.Module {
if module.Code == "package_version" {
for _, property := range module.Properties.Property {
if property.Key == "package_version" {
for _, value := range property.PropertyValues.PropertyValue {
pvMapping := map[string]interface{}{
"package_version": value.Value,
"package_name": value.DisplayName,
}
pvMapSli = append(pvMapSli, pvMapping)
}
}
}
} else if module.Code == "img_id" {
availableRegion := d.Get("available_region").(string)
for _, property := range module.Properties.Property {
if property.Key == "img_id" {
for _, value := range property.PropertyValues.PropertyValue {
regionId := getRegionByImageIdPrefix(value.Value)
if availableRegion != "" && availableRegion != regionId {
continue
}
imageIdMapping := map[string]interface{}{
"image_id": value.Value,
"image_name": value.DisplayName,
"region_id": regionId,
}
imageIdMap = append(imageIdMap, imageIdMapping)
}
}
}
}
}
skuMapping["package_versions"] = pvMapSli
skuMapping["images"] = imageIdMap
skus = append(skus, skuMapping)
}
mapping := map[string]interface{}{
"code": product.Code,
"name": product.Name,
"description": product.Description,
"skus": skus,
}
s = append(s, mapping)
d.SetId(dataResourceIdHash([]string{product.Code}))
if err := d.Set("product", s); err != nil {
return err
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"strconv"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/services/market"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudProducts() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudProductsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"sort": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"user_count-desc", "created_on-desc", "price-desc", "score-desc"}, false),
},
"category_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"product_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"APP", "SERVICE", "MIRROR", "DOWNLOAD", "API_SERVICE"}, false),
},
"search_term": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"supplier_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"supplier_name_keyword": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"suggested_price": {
Type: schema.TypeFloat,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
// Computed values.
"products": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"code": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"category_id": {
Type: schema.TypeInt,
Computed: true,
},
"supplier_id": {
Type: schema.TypeInt,
Computed: true,
},
"supplier_name": {
Type: schema.TypeString,
Computed: true,
},
"short_description": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeString,
Computed: true,
},
"suggested_price": {
Type: schema.TypeString,
Computed: true,
},
"target_url": {
Type: schema.TypeString,
Computed: true,
},
"image_url": {
Type: schema.TypeString,
Computed: true,
},
"score": {
Type: schema.TypeString,
Computed: true,
},
"operation_system": {
Type: schema.TypeString,
Computed: true,
},
"warranty_date": {
Type: schema.TypeString,
Computed: true,
},
"delivery_date": {
Type: schema.TypeString,
Computed: true,
},
"delivery_way": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudProductsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := market.CreateDescribeProductsRequest()
request.RegionId = client.RegionId
var productsFilter []market.DescribeProductsFilter
var product market.DescribeProductsFilter
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
if r, err := regexp.Compile(v.(string)); err == nil {
nameRegex = r
}
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
if v, ok := d.GetOk("sort"); ok && v.(string) != "" {
product.Key = "sort"
product.Value = v.(string)
productsFilter = append(productsFilter, product)
}
if v, ok := d.GetOk("category_id"); ok && v.(string) != "" {
product.Key = "categoryId"
product.Value = v.(string)
productsFilter = append(productsFilter, product)
}
if v, ok := d.GetOk("product_type"); ok && v.(string) != "" {
product.Key = "productType"
product.Value = v.(string)
productsFilter = append(productsFilter, product)
}
if v, ok := d.GetOk("search_term"); ok && v.(string) != "" {
request.SearchTerm = v.(string)
}
supplierId := d.Get("supplier_id").(string)
supplierNameKeyword := d.Get("supplier_name_keyword").(string)
suggestedPrice, suggestedPriceOk := d.GetOkExists("suggested_price")
request.Filter = &productsFilter
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var allProduct []market.ProductItem
for {
raw, err := client.WithMarketClient(func(marketClient *market.Client) (interface{}, error) {
return marketClient.DescribeProducts(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_market_products", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*market.DescribeProductsResponse)
if len(response.ProductItems.ProductItem) < 1 {
break
}
for _, item := range response.ProductItems.ProductItem {
if nameRegex != nil {
if !nameRegex.MatchString(item.Name) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[item.Code]; !ok {
continue
}
}
if supplierId != "" && supplierId != strconv.FormatInt(item.SupplierId, 10) {
continue
}
if supplierNameKeyword != "" && !strings.Contains(item.SupplierName, supplierNameKeyword) {
continue
}
if suggestedPriceOk && !strings.HasPrefix(item.SuggestedPrice, strconv.FormatFloat(suggestedPrice.(float64), 'f', -1, 64)) {
continue
}
allProduct = append(allProduct, item)
}
if len(response.ProductItems.ProductItem) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
return productsDescriptionAttributes(d, allProduct)
}
func productsDescriptionAttributes(d *schema.ResourceData, allProduct []market.ProductItem) error {
var ids []string
var s []map[string]interface{}
for _, p := range allProduct {
mapping := map[string]interface{}{
"code": p.Code,
"name": p.Name,
"category_id": p.CategoryId,
"supplier_id": p.SupplierId,
"supplier_name": p.SupplierName,
"short_description": p.ShortDescription,
"tags": p.Tags,
"suggested_price": p.SuggestedPrice,
"target_url": p.TargetUrl,
"image_url": p.ImageUrl,
"score": p.Score,
"operation_system": p.OperationSystem,
"warranty_date": p.WarrantyDate,
"delivery_date": p.DeliveryDate,
"delivery_way": p.DeliveryWay,
}
ids = append(ids, p.Code)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("products", s); err != nil {
return err
}
if err := d.Set("ids", ids); err != nil {
return err
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudMaxcomputeService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudMaxcomputeServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudMaxcomputeServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("MaxcomputeServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
action := "OpenMaxComputeService"
conn, err := meta.(*connectivity.AliyunClient).NewTeaCommonClient(connectivity.OpenMaxcomputeService)
request := map[string]interface{}{
"Region": conn.RegionId,
}
if err != nil {
return WrapError(err)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"QPS Limit Exceeded"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
addDebug(action, response, nil)
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ORDER.OPEND"}) {
d.SetId("MaxcomputeServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_maxcompute_service", action, AlibabaCloudSdkGoERROR)
}
d.SetId("MaxcomputeServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudMhubApps() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudMhubAppsRead,
Schema: map[string]*schema.Schema{
"product_id": {
Type: schema.TypeString,
Required: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"os_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Android", "iOS"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"apps": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"app_key": {
Type: schema.TypeString,
Computed: true,
},
"app_name": {
Type: schema.TypeString,
Computed: true,
},
"bundle_id": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"encoded_icon": {
Type: schema.TypeString,
Computed: true,
},
"industry_id": {
Type: schema.TypeString,
Computed: true,
},
"package_name": {
Type: schema.TypeString,
Computed: true,
},
"product_id": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudMhubAppsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListApps"
request := make(map[string]interface{})
if v, ok := d.GetOk("os_type"); ok {
request["OsType"] = convertTypeRequest(v.(string))
}
ProductId := d.Get("product_id")
request["ProductId"] = ProductId
request["PageSize"] = PageSizeLarge
request["Page"] = 1
var objects []map[string]interface{}
var appNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
appNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewMhubClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-08-25"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_mhub_apps", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.AppInfos.AppInfo", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.AppInfos.AppInfo", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if appNameRegex != nil && !appNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprintf("%s:%s", ProductId, item["AppKey"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["Page"] = request["Page"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprintf("%s:%s", ProductId, object["AppKey"]),
"app_key": fmt.Sprint(object["AppKey"]),
"app_name": object["Name"],
"bundle_id": object["BundleId"],
"encoded_icon": object["EncodedIcon"],
"industry_id": fmt.Sprint(object["IndustryId"]),
"package_name": object["PackageName"],
"type": convertTypeResponse(formatInt(object["Type"])),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["AppKey"])
mhubService := MhubService{client}
getResp, err := mhubService.DescribeMhubApp(id)
if err != nil {
return WrapError(err)
}
mapping["create_time"] = getResp["CreateTime"]
mapping["product_id"] = getResp["ProductId"]
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("apps", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudMhubProducts() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudMhubProductsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"products": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"product_id": {
Type: schema.TypeString,
Computed: true,
},
"product_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudMhubProductsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListProducts"
request := make(map[string]interface{})
request["Offset"] = 0
request["Simple"] = false
request["Size"] = PageSizeMedium
var objects []map[string]interface{}
var productNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
productNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewMhubClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-08-25"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_mhub_products", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.ProductInfos.ProductInfo", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.ProductInfos.ProductInfo", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if productNameRegex != nil && !productNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ProductId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeMedium {
break
}
request["Offset"] = request["Offset"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["ProductId"]),
"product_id": fmt.Sprint(object["ProductId"]),
"product_name": object["Name"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("products", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
ali_mns "github.com/aliyun/aliyun-mns-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudMNSQueues() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudMNSQueueRead,
Schema: map[string]*schema.Schema{
"name_prefix": {
Type: schema.TypeString,
Optional: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"queues": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"delay_seconds": {
Type: schema.TypeInt,
Computed: true,
},
"maximum_message_size": {
Type: schema.TypeInt,
Computed: true,
},
"message_retention_period": {
Type: schema.TypeInt,
Computed: true,
},
"visibility_timeouts": {
Type: schema.TypeInt,
Computed: true,
},
"polling_wait_seconds": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudMNSQueueRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var namePrefix string
if v, ok := d.GetOk("name_prefix"); ok {
namePrefix = v.(string)
}
var queueAttr []ali_mns.QueueAttribute
for {
var nextMaker string
raw, err := client.WithMnsQueueManager(func(queueManager ali_mns.AliQueueManager) (interface{}, error) {
return queueManager.ListQueueDetail(nextMaker, 1000, namePrefix)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_mns_queues", "ListQueueDetail", AliMnsERROR)
}
addDebug("ListQueueDetail", raw)
queueDetails, _ := raw.(ali_mns.QueueDetails)
for _, attr := range queueDetails.Attrs {
queueAttr = append(queueAttr, attr)
}
nextMaker = queueDetails.NextMarker
if nextMaker == "" {
break
}
}
return mnsQueueDescription(d, queueAttr)
}
func mnsQueueDescription(d *schema.ResourceData, queueAttr []ali_mns.QueueAttribute) error {
var ids []string
var names []string
var s []map[string]interface{}
for _, item := range queueAttr {
mapping := map[string]interface{}{
"id": item.QueueName,
"name": item.QueueName,
"delay_seconds": item.DelaySeconds,
"maximum_message_size": item.MaxMessageSize,
"message_retention_period": item.MessageRetentionPeriod,
"visibility_timeouts": item.VisibilityTimeout,
"polling_wait_seconds": item.PollingWaitSeconds,
}
names = append(names, item.QueueName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("queues", s); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"time"
ali_mns "github.com/aliyun/aliyun-mns-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudMnsService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudMnsServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudMnsServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("MnsServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
client := meta.(*connectivity.AliyunClient)
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := client.WithMnsClient(func(client *ali_mns.MNSClient) (interface{}, error) {
return ali_mns.NewAccountManager(*client).OpenService()
})
if err != nil {
if IsExpectedErrors(err, []string{"QPS Limit Exceeded"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
addDebug("OpenService", response, nil)
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"Forbidden.Opened"}) {
d.SetId("MnsServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_mns_service", "OpenService", AlibabaCloudSdkGoERROR)
}
d.SetId("MnsServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
package alicloud
import (
ali_mns "github.com/aliyun/aliyun-mns-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudMNSTopicSubscriptions() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudMNSTopicSubscriptionRead,
Schema: map[string]*schema.Schema{
"topic_name": {
Type: schema.TypeString,
Required: true,
},
"name_prefix": {
Type: schema.TypeString,
Optional: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"subscriptions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"topic_name": {
Type: schema.TypeString,
Computed: true,
},
"endpoint": {
Type: schema.TypeString,
Computed: true,
},
"filter_tag": {
Type: schema.TypeString,
Computed: true,
},
"notify_strategy": {
Type: schema.TypeString,
Computed: true,
},
"notify_content_format": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudMNSTopicSubscriptionRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
topicName := d.Get("topic_name").(string)
var namePrefix string
if v, ok := d.GetOk("name_prefix"); ok {
namePrefix = v.(string)
}
var subscriptionAttr []ali_mns.SubscriptionAttribute
for {
var nextMaker string
raw, err := client.WithMnsSubscriptionManagerByTopicName(topicName, func(subscriptionManager ali_mns.AliMNSTopic) (interface{}, error) {
return subscriptionManager.ListSubscriptionDetailByTopic(nextMaker, 1000, namePrefix)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_topic_subscriptions", "ListSubscriptionDetailByTopic", AliMnsERROR)
}
addDebug("ListSubscriptionDetailByTopic", raw)
subscriptionDetails, _ := raw.(ali_mns.SubscriptionDetails)
for _, attr := range subscriptionDetails.Attrs {
subscriptionAttr = append(subscriptionAttr, attr)
}
nextMaker = subscriptionDetails.NextMarker
if nextMaker == "" {
break
}
}
return mnsTopicSubcriptionDescription(d, subscriptionAttr)
}
func mnsTopicSubcriptionDescription(d *schema.ResourceData, topicAttr []ali_mns.SubscriptionAttribute) error {
var ids []string
var names []string
var s []map[string]interface{}
for _, item := range topicAttr {
mapping := map[string]interface{}{
"id": item.SubscriptionName,
"name": item.SubscriptionName,
"topic_name": item.TopicName,
"endpoint": item.Endpoint,
"filter_tag": item.FilterTag,
"notify_strategy": item.NotifyStrategy,
"notify_content_format": item.NotifyContentFormat,
}
ids = append(ids, item.SubscriptionName)
names = append(names, item.SubscriptionName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("subscriptions", s); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
ali_mns "github.com/aliyun/aliyun-mns-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudMNSTopics() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudMNSTopicRead,
Schema: map[string]*schema.Schema{
"name_prefix": {
Type: schema.TypeString,
Optional: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"topics": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"maximum_message_size": {
Type: schema.TypeInt,
Computed: true,
},
"logging_enabled": {
Type: schema.TypeBool,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudMNSTopicRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var namePrefix string
if v, ok := d.GetOk("name_prefix"); ok {
namePrefix = v.(string)
}
var topicAttr []ali_mns.TopicAttribute
for {
var nextMaker string
raw, err := client.WithMnsTopicManager(func(topicManager ali_mns.AliTopicManager) (interface{}, error) {
return topicManager.ListTopicDetail(nextMaker, 1000, namePrefix)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_mns_topics", "ListTopicDetail", AliMnsERROR)
}
addDebug("ListTopicDetail", raw)
topicDetails, _ := raw.(ali_mns.TopicDetails)
for _, attr := range topicDetails.Attrs {
topicAttr = append(topicAttr, attr)
}
nextMaker = topicDetails.NextMarker
if nextMaker == "" {
break
}
}
return mnsTopicDescription(d, topicAttr)
}
func mnsTopicDescription(d *schema.ResourceData, topicAttr []ali_mns.TopicAttribute) error {
var ids []string
var names []string
var s []map[string]interface{}
for _, item := range topicAttr {
mapping := map[string]interface{}{
"id": item.TopicName,
"name": item.TopicName,
"maximum_message_size": item.MaxMessageSize,
"logging_enabled": item.LoggingEnabled,
}
ids = append(ids, item.TopicName)
names = append(names, item.TopicName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("topics", s); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"strconv"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudMongodbAccounts() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudMongodbAccountsRead,
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"account_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"root"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"accounts": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"account_name": {
Type: schema.TypeString,
Computed: true,
},
"character_type": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudMongodbAccountsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeAccounts"
request := make(map[string]interface{})
request["DBInstanceId"] = d.Get("instance_id")
if v, ok := d.GetOk("account_name"); ok {
request["AccountName"] = v
}
var objects []map[string]interface{}
var response map[string]interface{}
conn, err := client.NewDdsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_mongodb_accounts", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Accounts.Account", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Accounts.Account", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
objects = append(objects, item)
}
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"account_description": object["AccountDescription"],
"id": fmt.Sprint(object["DBInstanceId"], ":", object["AccountName"]),
"account_name": fmt.Sprint(object["AccountName"]),
"character_type": object["CharacterType"],
"instance_id": object["DBInstanceId"],
"status": object["AccountStatus"],
}
s = append(s, mapping)
}
d.SetId(strconv.FormatInt(time.Now().Unix(), 16))
if err := d.Set("accounts", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"strconv"
"time"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudMongodbAuditPolicies() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudMongodbAuditPoliciesRead,
Schema: map[string]*schema.Schema{
"db_instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"policies": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"db_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"audit_status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudMongodbAuditPoliciesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
MongoDBService := MongoDBService{client}
dbInstanceId := d.Get("db_instance_id")
object, err := MongoDBService.DescribeMongodbAuditPolicy(dbInstanceId.(string))
if err != nil {
if NotFoundError(err) {
d.SetId("MongodbAuditPolicy")
return nil
}
return WrapError(err)
}
s := make([]map[string]interface{}, 0)
mapping := map[string]interface{}{
"id": fmt.Sprint(object["DBInstanceId"]),
"db_instance_id": fmt.Sprint(object["DBInstanceId"]),
"audit_status": convertMongodbAuditPolicyResponse(object["LogAuditStatus"].(string)),
}
s = append(s, mapping)
d.SetId(strconv.FormatInt(time.Now().Unix(), 16))
if err := d.Set("policies", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/dds"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudMongoDBInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudMongoDBInstancesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"instance_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"sharding", "replicate"}, false),
},
"instance_class": {
Type: schema.TypeString,
Optional: true,
},
"availability_zone": {
Type: schema.TypeString,
Optional: true,
},
"tags": tagsSchema(),
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"charge_type": {
Type: schema.TypeString,
Computed: true,
},
"instance_type": {
Type: schema.TypeString,
Computed: true,
},
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"creation_time": {
Type: schema.TypeString,
Computed: true,
},
"expiration_time": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"replication": {
Type: schema.TypeString,
Computed: true,
},
"engine": {
Type: schema.TypeString,
Computed: true,
},
"engine_version": {
Type: schema.TypeString,
Computed: true,
},
"network_type": {
Type: schema.TypeString,
Computed: true,
},
"lock_mode": {
Type: schema.TypeString,
Computed: true,
},
"instance_class": {
Type: schema.TypeString,
Computed: true,
},
"storage": {
Type: schema.TypeInt,
Computed: true,
},
"mongos": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"node_id": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"class": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"shards": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"node_id": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"class": {
Type: schema.TypeString,
Computed: true,
},
"storage": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"availability_zone": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudMongoDBInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ddsService := MongoDBService{client}
request := dds.CreateDescribeDBInstancesRequest()
request.RegionId = client.RegionId
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
if v, ok := d.GetOk("instance_type"); ok {
request.DBInstanceType = v.(string)
}
if v, ok := d.GetOk("tags"); ok {
var reqTags []dds.DescribeDBInstancesTag
for key, value := range v.(map[string]interface{}) {
reqTags = append(reqTags, dds.DescribeDBInstancesTag{
Key: key,
Value: value.(string),
})
}
request.Tag = &reqTags
}
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
nameRegex = regexp.MustCompile(v.(string))
}
var instClass string
if v, ok := d.GetOk("instance_class"); ok {
instClass = strings.ToLower(v.(string))
}
var az string
if v, ok := d.GetOk("availability_zone"); ok {
az = strings.ToLower(v.(string))
}
var dbi []dds.DBInstance
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
for {
raw, err := client.WithDdsClient(func(ddsClient *dds.Client) (interface{}, error) {
return ddsClient.DescribeDBInstances(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_mongodb_instances", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*dds.DescribeDBInstancesResponse)
if len(response.DBInstances.DBInstance) < 1 {
break
}
for _, item := range response.DBInstances.DBInstance {
if nameRegex != nil && !nameRegex.MatchString(item.DBInstanceDescription) {
continue
}
if len(instClass) > 0 && instClass != strings.ToLower(string(item.DBInstanceClass)) {
continue
}
if len(az) > 0 && az != strings.ToLower(string(item.ZoneId)) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[item.DBInstanceId]; !ok {
continue
}
}
dbi = append(dbi, item)
}
if len(response.DBInstances.DBInstance) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
var ids []string
var names []string
var s []map[string]interface{}
for _, item := range dbi {
mapping := map[string]interface{}{
"id": item.DBInstanceId,
"name": item.DBInstanceDescription,
"charge_type": item.ChargeType,
"instance_type": item.DBInstanceType,
"region_id": item.RegionId,
"creation_time": item.CreationTime,
"expiration_time": item.ExpireTime,
"status": item.DBInstanceStatus,
"engine": item.Engine,
"engine_version": item.EngineVersion,
"network_type": item.NetworkType,
"lock_mode": item.LockMode,
"availability_zone": item.ZoneId,
"instance_class": item.DBInstanceClass,
"storage": item.DBInstanceStorage,
"replication": item.ReplicationFactor,
"tags": ddsService.tagsToMap(item.Tags.Tag),
}
mongoList := []map[string]interface{}{}
for _, v := range item.MongosList.MongosAttribute {
mongo := map[string]interface{}{
"description": v.NodeDescription,
"node_id": v.NodeId,
"class": v.NodeClass,
}
mongoList = append(mongoList, mongo)
}
shardList := []map[string]interface{}{}
for _, v := range item.ShardList.ShardAttribute {
shard := map[string]interface{}{
"description": v.NodeDescription,
"node_id": v.NodeId,
"class": v.NodeClass,
"storage": v.NodeStorage,
}
shardList = append(shardList, shard)
}
mapping["mongos"] = mongoList
mapping["shards"] = shardList
ids = append(ids, item.DBInstanceId)
names = append(names, item.DBInstanceDescription)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
err := writeToFile(output.(string), s)
if err != nil {
return WrapError(err)
}
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudMongodbServerlessInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudMongodbServerlessInstancesRead,
Schema: map[string]*schema.Schema{
"db_instance_class": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"db_instance_description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"network_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Classic", "VPC"}, false),
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Creating", "DBInstanceClassChanging", "DBInstanceNetTypeChanging", "Deleting", "EngineVersionUpgrading", "GuardSwitching", "HASwitching", "Importing", "ImportingFromOthers", "LinkSwitching", "MinorVersionUpgrading", "NodeCreating", "NodeDeleting", "Rebooting", "Restoring", "Running", "SSLModifying", "TDEModifying", "TempDBInstanceCreating", "Transing", "TransingToOthers", "released"}, false),
},
"tags": tagsSchema(),
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"capacity_unit": {
Type: schema.TypeInt,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"db_instance_class": {
Type: schema.TypeString,
Computed: true,
},
"db_instance_description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"db_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"db_instance_release_protection": {
Type: schema.TypeBool,
Computed: true,
},
"db_instance_storage": {
Type: schema.TypeInt,
Computed: true,
},
"engine": {
Type: schema.TypeString,
Computed: true,
},
"engine_version": {
Type: schema.TypeString,
Computed: true,
},
"expire_time": {
Type: schema.TypeString,
Computed: true,
},
"kind_code": {
Type: schema.TypeString,
Computed: true,
},
"lock_mode": {
Type: schema.TypeString,
Computed: true,
},
"maintain_end_time": {
Type: schema.TypeString,
Computed: true,
},
"maintain_start_time": {
Type: schema.TypeString,
Computed: true,
},
"max_connections": {
Type: schema.TypeInt,
Computed: true,
},
"max_iops": {
Type: schema.TypeInt,
Computed: true,
},
"network_type": {
Type: schema.TypeString,
Computed: true,
},
"protocol_type": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"security_ip_groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"security_ip_group_attribute": {
Type: schema.TypeString,
Computed: true,
},
"security_ip_group_name": {
Type: schema.TypeString,
Computed: true,
},
"security_ip_list": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"storage_engine": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_auth_mode": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudMongodbServerlessInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDBInstances"
request := make(map[string]interface{})
if v, ok := d.GetOk("db_instance_class"); ok {
request["DBInstanceClass"] = v
}
if v, ok := d.GetOk("db_instance_description"); ok {
request["DBInstanceDescription"] = v
}
request["DBInstanceType"] = "serverless"
if v, ok := d.GetOk("network_type"); ok {
request["NetworkType"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
status, statusOk := d.GetOk("status")
if v, ok := d.GetOk("tags"); ok {
tags := make([]map[string]interface{}, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, map[string]interface{}{
"Key": key,
"Value": value.(string),
})
}
request["Tag"] = tags
}
if v, ok := d.GetOk("vswitch_id"); ok {
request["VSwitchId"] = v
}
if v, ok := d.GetOk("vpc_id"); ok {
request["VpcId"] = v
}
if v, ok := d.GetOk("zone_id"); ok {
request["ZoneId"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewDdsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_mongodb_serverless_instances", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.DBInstances.DBInstance", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.DBInstances.DBInstance", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DBInstanceId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["DBInstanceStatus"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"payment_type": convertMongodbServerlessInstancePayTypeResponse(object["ChargeType"].(string)),
"db_instance_class": object["DBInstanceClass"],
"db_instance_description": object["DBInstanceDescription"],
"id": fmt.Sprint(object["DBInstanceId"]),
"db_instance_id": fmt.Sprint(object["DBInstanceId"]),
"db_instance_storage": formatInt(object["DBInstanceStorage"]),
"engine": object["Engine"],
"engine_version": object["EngineVersion"],
"expire_time": object["ExpireTime"],
"kind_code": object["KindCode"],
"lock_mode": object["LockMode"],
"network_type": object["NetworkType"],
"resource_group_id": object["ResourceGroupId"],
"status": object["DBInstanceStatus"],
"vpc_auth_mode": object["VpcAuthMode"],
"zone_id": object["ZoneId"],
}
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags.Tag", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["Key"].(string)
value := t.(map[string]interface{})["Value"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
ids = append(ids, fmt.Sprint(mapping["id"]))
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["DBInstanceId"])
MongoDBService := MongoDBService{client}
getResp, err := MongoDBService.DescribeMongodbServerlessInstance(id)
if err != nil {
return WrapError(err)
}
mapping["capacity_unit"] = formatInt(getResp["CapacityUnit"])
mapping["db_instance_release_protection"] = getResp["DBInstanceReleaseProtection"]
mapping["maintain_end_time"] = getResp["MaintainEndTime"]
mapping["maintain_start_time"] = getResp["MaintainStartTime"]
if v, ok := getResp["MaxConnections"]; ok && fmt.Sprint(v) != "0" {
mapping["max_connections"] = formatInt(v)
}
if v, ok := getResp["MaxIOPS"]; ok && fmt.Sprint(v) != "0" {
mapping["max_iops"] = formatInt(v)
}
mapping["protocol_type"] = getResp["ProtocolType"]
mapping["storage_engine"] = convertMongodbServerlessInstanceStorageEngineResponse(getResp["StorageEngine"].(string))
mapping["vswitch_id"] = getResp["VSwitchId"]
mapping["vpc_id"] = getResp["VPCId"]
getResp1, err := MongoDBService.DescribeSecurityIps(id)
if err != nil {
return WrapError(err)
}
iPArray := make([]map[string]interface{}, 0)
if securityIpGroup, ok := getResp1["SecurityIpGroups"].(map[string]interface{})["SecurityIpGroup"].([]interface{}); ok {
for _, v := range securityIpGroup {
if m1, ok := v.(map[string]interface{}); ok {
if m1["SecurityIpGroupName"].(string) == "default" {
continue
}
temp1 := map[string]interface{}{
"security_ip_group_attribute": m1["SecurityIpGroupAttribute"],
"security_ip_group_name": m1["SecurityIpGroupName"],
"security_ip_list": m1["SecurityIpList"],
}
iPArray = append(iPArray, temp1)
}
}
}
mapping["security_ip_groups"] = iPArray
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"strconv"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudMongodbShardingNetworkPublicAddresses() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudMongodbShardingNetworkPublicAddressesRead,
Schema: map[string]*schema.Schema{
"db_instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"node_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"role": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Primary", "Secondary"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"addresses": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"db_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"expired_time": {
Type: schema.TypeString,
Computed: true,
},
"ip_address": {
Type: schema.TypeString,
Computed: true,
},
"network_address": {
Type: schema.TypeString,
Computed: true,
},
"network_type": {
Type: schema.TypeString,
Computed: true,
},
"node_id": {
Type: schema.TypeString,
Computed: true,
},
"node_type": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeString,
Computed: true,
},
"role": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudMongodbShardingNetworkPublicAddressesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeShardingNetworkAddress"
request := make(map[string]interface{})
request["DBInstanceId"] = d.Get("db_instance_id")
if v, ok := d.GetOk("node_id"); ok {
request["NodeId"] = v
}
role, roleOk := d.GetOk("role")
var response map[string]interface{}
var objects []map[string]interface{}
conn, err := client.NewDdsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_mongodb_sharding_network_public_addresses", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.NetworkAddresses.NetworkAddress", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.NetworkAddresses.NetworkAddress", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if roleOk && role.(string) != "" && role.(string) != item["Role"].(string) {
continue
}
if item["NetworkType"].(string) != "Public" {
continue
}
objects = append(objects, item)
}
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"db_instance_id": request["DBInstanceId"],
"expired_time": object["ExpiredTime"],
"ip_address": object["IPAddress"],
"network_address": object["NetworkAddress"],
"network_type": object["NetworkType"],
"node_type": object["NodeType"],
"port": object["Port"],
"role": object["Role"],
"vpc_id": object["VPCId"],
"vswitch_id": object["VswitchId"],
}
if v, ok := d.GetOk("node_id"); ok {
mapping["node_id"] = v
} else {
mapping["node_id"] = object["NodeId"]
}
s = append(s, mapping)
}
d.SetId(strconv.FormatInt(time.Now().Unix(), 16))
if err := d.Set("addresses", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"sort"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/services/dds"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudMongoDBZones() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudMongoDBZonesRead,
Schema: map[string]*schema.Schema{
"multi": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"zones": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"multi_zone_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
},
}
}
func dataSourceAlicloudMongoDBZonesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
multi := d.Get("multi").(bool)
var zoneIds []string
request := dds.CreateDescribeRegionsRequest()
request.RegionId = client.RegionId
raw, err := client.WithDdsClient(func(ddsClient *dds.Client) (interface{}, error) {
return ddsClient.DescribeRegions(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_mongodb_zones", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
regions, _ := raw.(*dds.DescribeRegionsResponse)
if len(regions.Regions.DdsRegion) <= 0 {
return WrapError(fmt.Errorf("[ERROR] There is no available region for MongoDB."))
}
for _, r := range regions.Regions.DdsRegion {
for _, zonid := range r.Zones.Zone {
if multi && strings.Contains(zonid.ZoneId, MULTI_IZ_SYMBOL) && r.RegionId == string(client.Region) {
zoneIds = append(zoneIds, zonid.ZoneId)
continue
}
if !multi && !strings.Contains(zonid.ZoneId, MULTI_IZ_SYMBOL) && r.RegionId == string(client.Region) {
zoneIds = append(zoneIds, zonid.ZoneId)
continue
}
}
}
if len(zoneIds) > 0 {
sort.Strings(zoneIds)
}
var s []map[string]interface{}
if !multi {
for _, zoneId := range zoneIds {
mapping := map[string]interface{}{"id": zoneId}
s = append(s, mapping)
}
} else {
for _, zoneId := range zoneIds {
mapping := map[string]interface{}{
"id": zoneId,
"multi_zone_ids": splitMultiZoneId(zoneId),
}
s = append(s, mapping)
}
}
d.SetId(dataResourceIdHash(zoneIds))
if err := d.Set("zones", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", zoneIds); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudMscSubContacts() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudMscSubContactsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"contacts": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_uid": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"contact_id": {
Type: schema.TypeString,
Computed: true,
},
"contact_name": {
Type: schema.TypeString,
Computed: true,
},
"email": {
Type: schema.TypeString,
Computed: true,
},
"is_account": {
Type: schema.TypeBool,
Computed: true,
},
"is_obsolete": {
Type: schema.TypeBool,
Computed: true,
},
"is_verified_email": {
Type: schema.TypeBool,
Computed: true,
},
"is_verified_mobile": {
Type: schema.TypeBool,
Computed: true,
},
"last_email_verification_time_stamp": {
Type: schema.TypeString,
Computed: true,
},
"last_mobile_verification_time_stamp": {
Type: schema.TypeString,
Computed: true,
},
"mobile": {
Type: schema.TypeString,
Computed: true,
},
"position": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudMscSubContactsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListContacts"
request := make(map[string]interface{})
request["Locale"] = "en"
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var contactNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
contactNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewMscopensubscriptionClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2021-07-13"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_msc_sub_contacts", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.Contacts", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Contacts", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if contactNameRegex != nil && !contactNameRegex.MatchString(fmt.Sprint(item["ContactName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ContactId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"account_uid": fmt.Sprint(object["AccountUid"]),
"id": fmt.Sprint(object["ContactId"]),
"contact_id": fmt.Sprint(object["ContactId"]),
"contact_name": object["ContactName"],
"email": object["Email"],
"is_account": object["IsAccount"],
"is_obsolete": object["IsObsolete"],
"is_verified_email": object["IsVerifiedEmail"],
"is_verified_mobile": object["IsVerifiedMobile"],
"last_email_verification_time_stamp": fmt.Sprint(object["LastEmailVerificationTimeStamp"]),
"last_mobile_verification_time_stamp": fmt.Sprint(object["LastMobileVerificationTimeStamp"]),
"mobile": object["Mobile"],
"position": convertMscSubContactPositionResponse(fmt.Sprint(object["Position"])),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["ContactName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("contacts", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"strconv"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudMscSubSubscriptions() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudMscSubSubscriptionsRead,
Schema: map[string]*schema.Schema{
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"subscriptions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"channel": {
Type: schema.TypeString,
Computed: true,
},
"contact_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeInt},
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"email_status": {
Type: schema.TypeInt,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"item_id": {
Type: schema.TypeString,
Computed: true,
},
"item_name": {
Type: schema.TypeString,
Computed: true,
},
"pmsg_status": {
Type: schema.TypeInt,
Computed: true,
},
"sms_status": {
Type: schema.TypeInt,
Computed: true,
},
"tts_status": {
Type: schema.TypeInt,
Computed: true,
},
"webhook_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeInt},
},
"webhook_status": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudMscSubSubscriptionsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListSubscriptionItems"
request := make(map[string]interface{})
if v, ok := d.GetOk("filter"); ok {
request["Filter"] = v
}
request["Locale"] = "en"
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var response map[string]interface{}
conn, err := client.NewMscopensubscriptionClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2021-07-13"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_msc_sub_subscriptions", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.SubscriptionItems", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.SubscriptionItems", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"channel": object["Channel"],
"contact_ids": object["ContactIds"],
"description": object["Description"],
"email_status": formatInt(object["EmailStatus"]),
"id": fmt.Sprint(object["ItemId"]),
"item_id": fmt.Sprint(object["ItemId"]),
"item_name": object["ItemName"],
"pmsg_status": formatInt(object["PmsgStatus"]),
"sms_status": formatInt(object["SmsStatus"]),
"tts_status": formatInt(object["TtsStatus"]),
"webhook_ids": object["WebhookIds"],
"webhook_status": formatInt(object["WebhookStatus"]),
}
s = append(s, mapping)
}
d.SetId(strconv.FormatInt(time.Now().Unix(), 16))
if err := d.Set("subscriptions", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudMscSubWebhooks() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudMscSubWebhooksRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"webhooks": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"server_url": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"webhook_id": {
Type: schema.TypeString,
Computed: true,
},
"webhook_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudMscSubWebhooksRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListWebhooks"
request := make(map[string]interface{})
request["Locale"] = "en"
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var webhookNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
webhookNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewMscopensubscriptionClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2021-07-13"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_msc_sub_webhooks", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.Webhooks", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Webhooks", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if webhookNameRegex != nil && !webhookNameRegex.MatchString(fmt.Sprint(item["WebhookName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["WebhookId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"server_url": object["ServerUrl"],
"id": fmt.Sprint(object["WebhookId"]),
"webhook_id": fmt.Sprint(object["WebhookId"]),
"webhook_name": object["WebhookName"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["WebhookName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("webhooks", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudMseClusters() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudMseClustersRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"cluster_alias_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"request_pars": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"DESTROY_FAILED", "DESTROY_ING", "DESTROY_SUCCESS", "INIT_FAILED", "INIT_ING", "INIT_SUCCESS", "INIT_TIME_OUT", "RESTART_FAILED", "RESTART_ING", "RESTART_SUCCESS", "SCALE_FAILED", "SCALE_ING", "SCALE_SUCCESS"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"clusters": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"acl_id": {
Type: schema.TypeString,
Computed: true,
},
"app_version": {
Type: schema.TypeString,
Computed: true,
},
"cluster_id": {
Type: schema.TypeString,
Computed: true,
},
"cluster_name": {
Type: schema.TypeString,
Computed: true,
},
"cluster_type": {
Type: schema.TypeString,
Computed: true,
},
"cpu": {
Type: schema.TypeInt,
Computed: true,
},
"health_status": {
Type: schema.TypeString,
Computed: true,
},
"init_cost_time": {
Type: schema.TypeInt,
Computed: true,
},
"instance_count": {
Type: schema.TypeInt,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_models": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"health_status": {
Type: schema.TypeString,
Computed: true,
},
"instance_type": {
Type: schema.TypeString,
Computed: true,
},
"internet_ip": {
Type: schema.TypeString,
Computed: true,
},
"ip": {
Type: schema.TypeString,
Computed: true,
},
"pod_name": {
Type: schema.TypeString,
Computed: true,
},
"role": {
Type: schema.TypeString,
Computed: true,
},
"single_tunnel_vip": {
Type: schema.TypeString,
Computed: true,
},
"vip": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"internet_address": {
Type: schema.TypeString,
Computed: true,
},
"internet_domain": {
Type: schema.TypeString,
Computed: true,
},
"internet_port": {
Type: schema.TypeString,
Computed: true,
},
"intranet_address": {
Type: schema.TypeString,
Computed: true,
},
"intranet_domain": {
Type: schema.TypeString,
Computed: true,
},
"intranet_port": {
Type: schema.TypeString,
Computed: true,
},
"memory_capacity": {
Type: schema.TypeInt,
Computed: true,
},
"pay_info": {
Type: schema.TypeString,
Computed: true,
},
"pub_network_flow": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudMseClustersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListClusters"
request := make(map[string]interface{})
if v, ok := d.GetOk("cluster_alias_name"); ok {
request["ClusterAliasName"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("request_pars"); ok {
request["RequestPars"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNum"] = 1
var objects []map[string]interface{}
var clusterNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
clusterNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewMseClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-05-31"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_mse_clusters", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Data", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Data", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if clusterNameRegex != nil {
if !clusterNameRegex.MatchString(fmt.Sprint(item["ClusterAliasName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["InstanceId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["InitStatus"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNum"] = request["PageNum"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"app_version": object["AppVersion"],
"cluster_id": object["ClusterId"],
"cluster_name": object["ClusterAliasName"],
"cluster_type": object["ClusterType"],
"id": fmt.Sprint(object["InstanceId"]),
"instance_id": fmt.Sprint(object["InstanceId"]),
"internet_address": object["InternetAddress"],
"internet_domain": object["InternetDomain"],
"intranet_address": object["IntranetAddress"],
"intranet_domain": object["IntranetDomain"],
"status": object["InitStatus"],
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["InstanceId"]))
names = append(names, object["ClusterAliasName"])
s = append(s, mapping)
continue
}
mseService := MseService{client}
id := fmt.Sprint(object["InstanceId"])
getResp, err := mseService.DescribeMseCluster(id)
if err != nil {
return WrapError(err)
}
mapping["acl_id"] = getResp["AclId"]
mapping["cpu"] = getResp["Cpu"]
mapping["health_status"] = getResp["HealthStatus"]
mapping["init_cost_time"] = getResp["InitCostTime"]
mapping["instance_count"] = getResp["InstanceCount"]
instanceModels := make([]map[string]interface{}, 0)
if instanceModelsList, ok := getResp["InstanceModels"].([]interface{}); ok {
for _, v := range instanceModelsList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"health_status": m1["HealthStatus"],
"instance_type": m1["InstanceType"],
"internet_ip": m1["InternetIp"],
"ip": m1["Ip"],
"pod_name": m1["PodName"],
"role": m1["Role"],
"single_tunnel_vip": m1["SingleTunnelVip"],
"vip": m1["Vip"],
}
instanceModels = append(instanceModels, temp1)
}
}
}
mapping["instance_models"] = instanceModels
mapping["internet_port"] = getResp["InternetPort"]
mapping["intranet_port"] = getResp["IntranetPort"]
mapping["memory_capacity"] = getResp["MemoryCapacity"]
mapping["pay_info"] = getResp["PayInfo"]
mapping["pub_network_flow"] = getResp["PubNetworkFlow"]
ids = append(ids, fmt.Sprint(object["InstanceId"]))
names = append(names, object["ClusterAliasName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("clusters", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudNasAccessGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudNasAccessGroupsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Deprecated: "Field 'type' has been deprecated from provider version 1.95.0. New field 'access_group_type' replaces it.",
},
"access_group_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"access_group_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"file_system_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "standard",
ValidateFunc: validation.StringInSlice([]string{"extreme", "standard"}, false),
},
"useutc_date_time": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"access_group_name": {
Type: schema.TypeString,
Computed: true,
},
"access_group_type": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"mount_target_count": {
Type: schema.TypeInt,
Computed: true,
},
"rule_count": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudNasAccessGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeAccessGroups"
request := make(map[string]interface{})
if v, ok := d.GetOk("access_group_name"); ok {
request["AccessGroupName"] = v
}
if v, ok := d.GetOk("file_system_type"); ok {
request["FileSystemType"] = v
}
if v, ok := d.GetOkExists("useutc_date_time"); ok {
request["UseUTCDateTime"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var accessGroupNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
accessGroupNameRegex = r
}
var response map[string]interface{}
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_nas_access_groups", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.AccessGroups.AccessGroup", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.AccessGroups.AccessGroup", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if accessGroupNameRegex != nil {
if !accessGroupNameRegex.MatchString(fmt.Sprint(item["AccessGroupName"])) {
continue
}
}
if v, ok := d.GetOk("type"); ok && v.(string) != "" && item["AccessGroupType"].(string) != v.(string) {
continue
}
if v, ok := d.GetOk("access_group_type"); ok && v.(string) != "" && item["AccessGroupType"].(string) != v.(string) {
continue
}
if v, ok := d.GetOk("description"); ok && v.(string) != "" && item["Description"].(string) != v.(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["AccessGroupName"], ":", request["FileSystemType"]),
"access_group_name": object["AccessGroupName"],
"access_group_type": object["AccessGroupType"],
"type": object["AccessGroupType"],
"description": object["Description"],
"mount_target_count": formatInt(object["MountTargetCount"]),
"rule_count": formatInt(object["RuleCount"]),
}
ids = append(ids, fmt.Sprint(object["AccessGroupName"], ":", request["FileSystemType"]))
names = append(names, object["AccessGroupName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudAccessRules() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAccessRulesRead,
Schema: map[string]*schema.Schema{
"source_cidr_ip": {
Type: schema.TypeString,
Optional: true,
},
"access_group_name": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"user_access": {
Type: schema.TypeString,
Optional: true,
},
"rw_access": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"source_cidr_ip": {
Type: schema.TypeString,
Computed: true,
},
"priority": {
Type: schema.TypeInt,
Computed: true,
},
"access_rule_id": {
Type: schema.TypeString,
Computed: true,
},
"user_access": {
Type: schema.TypeString,
Computed: true,
},
"rw_access": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudAccessRulesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeAccessRules"
request := make(map[string]interface{})
request["AccessGroupName"] = d.Get("access_group_name")
request["RegionId"] = client.Region
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_nas_access_rules", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.AccessRules.AccessRule", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.AccessRules.AccessRule", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if v, ok := d.GetOk("source_cidr_ip"); ok && v.(string) != "" && item["SourceCidrIp"].(string) != v.(string) {
continue
}
if v, ok := d.GetOk("user_access"); ok && v.(string) != "" && item["UserAccess"].(string) != v.(string) {
continue
}
if v, ok := d.GetOk("rw_access"); ok && v.(string) != "" && item["RWAccess"].(string) != v.(string) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["AccessRuleId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"source_cidr_ip": object["SourceCidrIp"],
"priority": formatInt(object["Priority"]),
"access_rule_id": object["AccessRuleId"],
"user_access": object["UserAccess"],
"rw_access": object["RWAccess"],
}
ids = append(ids, fmt.Sprint(object["AccessRuleId"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("rules", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"strings"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudNasAutoSnapshotPolicies() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudNasAutoSnapshotPoliciesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "Creating"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"policies": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"auto_snapshot_policy_id": {
Type: schema.TypeString,
Computed: true,
},
"auto_snapshot_policy_name": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"file_system_nums": {
Type: schema.TypeInt,
Computed: true,
},
"repeat_weekdays": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"retention_days": {
Type: schema.TypeInt,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"time_points": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
},
},
},
}
}
func dataSourceAlicloudNasAutoSnapshotPoliciesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeAutoSnapshotPolicies"
request := make(map[string]interface{})
request["FileSystemType"] = "extreme"
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var autoSnapshotPolicyNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
autoSnapshotPolicyNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_nas_auto_snapshot_policies", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.AutoSnapshotPolicies.AutoSnapshotPolicy", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.AutoSnapshotPolicies.AutoSnapshotPolicy", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if autoSnapshotPolicyNameRegex != nil && !autoSnapshotPolicyNameRegex.MatchString(fmt.Sprint(item["AutoSnapshotPolicyName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["AutoSnapshotPolicyId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["AutoSnapshotPolicyId"]),
"auto_snapshot_policy_id": fmt.Sprint(object["AutoSnapshotPolicyId"]),
"auto_snapshot_policy_name": object["AutoSnapshotPolicyName"],
"create_time": object["CreateTime"],
"file_system_nums": formatInt(object["FileSystemNums"]),
"repeat_weekdays": strings.Split(object["RepeatWeekdays"].(string), ","),
"retention_days": formatInt(object["RetentionDays"]),
"status": object["Status"],
"time_points": strings.Split(object["TimePoints"].(string), ","),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["AutoSnapshotPolicyName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("policies", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudNasDataFlows() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudNasDataFlowsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"file_system_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Starting", "Running", "Stopped", "Updating", "Deleting", "Stopping", "Misconfigured"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"flows": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"data_flow_id": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"error_message": {
Type: schema.TypeString,
Computed: true,
},
"file_system_id": {
Type: schema.TypeString,
Computed: true,
},
"file_system_path": {
Type: schema.TypeString,
Computed: true,
},
"fset_description": {
Type: schema.TypeString,
Computed: true,
},
"fset_id": {
Type: schema.TypeString,
Computed: true,
},
"source_security_type": {
Type: schema.TypeString,
Computed: true,
},
"source_storage": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"throughput": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudNasDataFlowsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDataFlows"
request := make(map[string]interface{})
request["FileSystemId"] = d.Get("file_system_id")
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_nas_data_flows", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.DataFlowInfo.DataFlow", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.DataFlowInfo.DataFlow", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["FileSystemId"], ":", item["DataFlowId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": object["CreateTime"],
"id": fmt.Sprint(object["FileSystemId"], ":", object["DataFlowId"]),
"data_flow_id": fmt.Sprint(object["DataFlowId"]),
"description": object["Description"],
"error_message": object["ErrorMessage"],
"file_system_id": object["FileSystemId"],
"file_system_path": object["FileSystemPath"],
"fset_description": object["FsetDescription"],
"fset_id": object["FsetId"],
"source_security_type": object["SourceSecurityType"],
"source_storage": object["SourceStorage"],
"status": object["Status"],
"throughput": formatInt(object["Throughput"]),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("flows", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudFileSystems() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudFileSystemsRead,
Schema: map[string]*schema.Schema{
"storage_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Capacity", "Performance", "standard", "advance"}, false),
},
"protocol_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"NFS", "SMB"}, false),
},
"description_regex": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.ValidateRegexp,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"descriptions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"systems": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"protocol_type": {
Type: schema.TypeString,
Computed: true,
},
"storage_type": {
Type: schema.TypeString,
Computed: true,
},
"metered_size": {
Type: schema.TypeInt,
Computed: true,
},
"encrypt_type": {
Type: schema.TypeInt,
Computed: true,
},
"file_system_type": {
Type: schema.TypeString,
Computed: true,
},
"capacity": {
Type: schema.TypeInt,
Computed: true,
},
"kms_key_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudFileSystemsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeFileSystems"
request := make(map[string]interface{})
request["RegionId"] = client.Region
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var filesystemDescriptionRegex *regexp.Regexp
if v, ok := d.GetOk("description_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
filesystemDescriptionRegex = r
}
var response map[string]interface{}
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_nas_file_systems", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.FileSystems.FileSystem", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.FileSystems.FileSystem", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if filesystemDescriptionRegex != nil {
if !filesystemDescriptionRegex.MatchString(fmt.Sprint(item["Description"])) {
continue
}
}
if v, ok := d.GetOk("storage_type"); ok && v.(string) != "" && item["StorageType"].(string) != v.(string) {
continue
}
if v, ok := d.GetOk("protocol_type"); ok && v.(string) != "" && item["ProtocolType"].(string) != v.(string) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["FileSystemId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
descriptions := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["FileSystemId"]),
"region_id": object["RegionId"],
"create_time": object["CreateTime"],
"description": object["Description"],
"protocol_type": object["ProtocolType"],
"storage_type": object["StorageType"],
"metered_size": formatInt(object["MeteredSize"]),
"encrypt_type": object["EncryptType"],
"file_system_type": object["FileSystemType"],
"capacity": object["Capacity"],
"kms_key_id": object["KMSKeyId"],
"zone_id": object["ZoneId"],
}
ids = append(ids, fmt.Sprint(object["FileSystemId"]))
descriptions = append(descriptions, object["Description"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("descriptions", descriptions); err != nil {
return WrapError(err)
}
if err := d.Set("systems", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudNasFilesets() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudNasFilesetsRead,
Schema: map[string]*schema.Schema{
"file_system_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"CREATED", "CREATING", "RELEASED", "RELEASING"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"filesets": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"file_system_id": {
Type: schema.TypeString,
Computed: true,
},
"file_system_path": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"fileset_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"update_time": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudNasFilesetsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeFilesets"
request := make(map[string]interface{})
request["FileSystemId"] = d.Get("file_system_id")
request["MaxResults"] = PageSizeMedium
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_nas_filesets", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Entries.Entrie", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Entries.Entrie", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(request["FileSystemId"], ":", item["FsetId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": object["CreateTime"],
"description": object["Description"],
"file_system_id": request["FileSystemId"],
"file_system_path": object["FileSystemPath"],
"id": fmt.Sprint(request["FileSystemId"], ":", object["FsetId"]),
"fileset_id": fmt.Sprint(object["FsetId"]),
"status": object["Status"],
"update_time": object["UpdateTiem"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("filesets", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudNasLifecyclePolicies() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudNasLifecyclePoliciesRead,
Schema: map[string]*schema.Schema{
"file_system_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"policies": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"file_system_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"lifecycle_policy_name": {
Type: schema.TypeString,
Computed: true,
},
"lifecycle_rule_name": {
Type: schema.TypeString,
Computed: true,
},
"paths": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"storage_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudNasLifecyclePoliciesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeLifecyclePolicies"
request := make(map[string]interface{})
request["FileSystemId"] = d.Get("file_system_id")
request["PageSize"] = PageSizeMedium
request["PageNumber"] = 1
var objects []map[string]interface{}
var lifecyclePolicyNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
lifecyclePolicyNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2017-06-26"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_nas_lifecycle_policies", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.LifecyclePolicies", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.LifecyclePolicies", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if lifecyclePolicyNameRegex != nil && !lifecyclePolicyNameRegex.MatchString(fmt.Sprint(item["LifecyclePolicyName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["FileSystemId"], ":", item["LifecyclePolicyName"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeMedium {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": object["CreateTime"],
"file_system_id": object["FileSystemId"],
"id": fmt.Sprint(object["FileSystemId"], ":", object["LifecyclePolicyName"]),
"lifecycle_policy_name": fmt.Sprint(object["LifecyclePolicyName"]),
"lifecycle_rule_name": object["LifecycleRuleName"],
"paths": object["Paths"],
"storage_type": object["StorageType"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["LifecyclePolicyName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("policies", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudNasMountTargets() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudNasMountTargetsRead,
Schema: map[string]*schema.Schema{
"access_group_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"mount_target_domain": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Deprecated: "Field 'mount_target_domain' has been deprecated from provider version 1.53.0. New field 'ids' replaces it.",
},
"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Deprecated: "Field 'type' has been deprecated from provider version 1.95.0. New field 'network_type' replaces it.",
},
"network_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"file_system_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Inactive", "Pending"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"targets": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"access_group_name": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"mount_target_domain": {
Type: schema.TypeString,
Computed: true,
},
"network_type": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudNasMountTargetsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeMountTargets"
request := make(map[string]interface{})
request["FileSystemId"] = d.Get("file_system_id")
request["RegionId"] = client.RegionId
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_nas_mount_targets", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.MountTargets.MountTarget", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.MountTargets.MountTarget", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if v, ok := d.GetOk("access_group_name"); ok && v.(string) != "" && item["AccessGroup"].(string) != v.(string) {
continue
}
if v, ok := d.GetOk("mount_target_domain"); ok && v.(string) != "" && item["MountTargetDomain"].(string) != v.(string) {
continue
}
if v, ok := d.GetOk("type"); ok && v.(string) != "" && item["NetworkType"].(string) != v.(string) {
continue
}
if v, ok := d.GetOk("network_type"); ok && v.(string) != "" && item["NetworkType"].(string) != v.(string) {
continue
}
if v, ok := d.GetOk("vpc_id"); ok && v.(string) != "" && item["VpcId"].(string) != v.(string) {
continue
}
if v, ok := d.GetOk("vswitch_id"); ok && v.(string) != "" && item["VswId"].(string) != v.(string) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["MountTargetDomain"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"access_group_name": object["AccessGroup"],
"id": fmt.Sprint(object["MountTargetDomain"]),
"mount_target_domain": fmt.Sprint(object["MountTargetDomain"]),
"network_type": object["NetworkType"],
"type": object["NetworkType"],
"status": object["Status"],
"vpc_id": object["VpcId"],
"vswitch_id": object["VswId"],
}
ids = append(ids, fmt.Sprint(object["MountTargetDomain"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("targets", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"strings"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudNasProtocols() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudNasProtocolsRead,
Schema: map[string]*schema.Schema{
"type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
"Capacity",
"Performance",
}, false),
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"protocols": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
}
}
func dataSourceAlicloudNasProtocolsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeZones"
var response map[string]interface{}
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_nas_protocols", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Zones.Zone", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Zones.Zone", response)
}
var nasProtocol [][]interface{}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if v, ok := d.GetOk("zone_id"); ok && v.(string) != "" && item["ZoneId"].(string) != v.(string) {
continue
}
if v, ok := d.GetOk("type"); ok {
if Trim(v.(string)) == "Performance" {
protocol, _ := item["Performance"].(map[string]interface{})["Protocol"].([]interface{})
if len(protocol) == 0 {
continue
} else {
nasProtocol = append(nasProtocol, protocol)
}
}
if Trim(v.(string)) == "Capacity" {
protocol, _ := item["Capacity"].(map[string]interface{})["Protocol"].([]interface{})
if len(protocol) == 0 {
continue
} else {
nasProtocol = append(nasProtocol, protocol)
}
}
}
}
var s []string
var ids []string
for _, val := range nasProtocol {
for _, protocol := range val {
s = append(s, strings.ToUpper(protocol.(string)))
ids = append(ids, protocol.(string))
}
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("protocols", s); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudNasService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudNasServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudNasServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("NasServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
conn, err := meta.(*connectivity.AliyunClient).NewTeaCommonClient(connectivity.OpenNasService)
if err != nil {
return WrapError(err)
}
response, err := conn.DoRequest(StringPointer("OpenNASService"), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, nil, &util.RuntimeOptions{})
addDebug("OpenNASService", response, nil)
if err != nil {
if IsExpectedErrors(err, []string{"ORDER.OPENDError", "ORDER.OPEND"}) {
d.SetId("NasServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_nas_service", "OpenNASService", AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprintf("%v", response["OrderId"]))
d.Set("status", "Opened")
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudNasSnapshots() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudNasSnapshotsRead,
Schema: map[string]*schema.Schema{
"file_system_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"snapshot_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"accomplished", "failed", "progressing"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"snapshots": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"encrypt_type": {
Type: schema.TypeInt,
Computed: true,
},
"progress": {
Type: schema.TypeString,
Computed: true,
},
"remain_time": {
Type: schema.TypeInt,
Computed: true,
},
"retention_days": {
Type: schema.TypeInt,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"snapshot_id": {
Type: schema.TypeString,
Computed: true,
},
"snapshot_name": {
Type: schema.TypeString,
Computed: true,
},
"source_file_system_id": {
Type: schema.TypeString,
Computed: true,
},
"source_file_system_size": {
Type: schema.TypeString,
Computed: true,
},
"source_file_system_version": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudNasSnapshotsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeSnapshots"
request := make(map[string]interface{})
if v, ok := d.GetOk("file_system_id"); ok {
request["FileSystemId"] = v
}
request["FileSystemType"] = "extreme"
if v, ok := d.GetOk("snapshot_name"); ok {
request["SnapshotName"] = v
}
if v, ok := d.GetOk("snapshot_type"); ok {
request["SnapshotType"] = v
}
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var snapshotNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
snapshotNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_nas_snapshots", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Snapshots.Snapshot", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Snapshots.Snapshot", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if snapshotNameRegex != nil && !snapshotNameRegex.MatchString(fmt.Sprint(item["SnapshotName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["SnapshotId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": object["CreateTime"],
"description": object["Description"],
"encrypt_type": formatInt(object["EncryptType"]),
"progress": object["Progress"],
"remain_time": formatInt(object["RemainTime"]),
"retention_days": formatInt(object["RetentionDays"]),
"id": fmt.Sprint(object["SnapshotId"]),
"snapshot_id": fmt.Sprint(object["SnapshotId"]),
"snapshot_name": object["SnapshotName"],
"source_file_system_id": object["SourceFileSystemId"],
"source_file_system_size": fmt.Sprint(object["SourceFileSystemSize"]),
"source_file_system_version": object["SourceFileSystemVersion"],
"status": object["Status"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["SnapshotName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("snapshots", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"strconv"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudNasZones() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudNasZonesRead,
Schema: map[string]*schema.Schema{
"file_system_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"standard", "extreme", "cpfs"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"zones": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_types": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"storage_type": {
Type: schema.TypeString,
Computed: true,
},
"protocol_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudNasZonesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeZones"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("file_system_type"); ok {
request["FileSystemType"] = v
}
var objects []map[string]interface{}
var response map[string]interface{}
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_nas_zones", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Zones.Zone", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Zones.Zone", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
objects = append(objects, item)
}
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"zone_id": object["ZoneId"],
}
InstanceTypes := make([]map[string]interface{}, 0)
if InstanceTypesList, ok := object["InstanceTypes"]; ok {
if data, ok := InstanceTypesList.(map[string]interface{}); ok {
for _, v := range data {
if m1, ok := v.([]interface{}); ok {
for _, vv := range m1 {
if res, ok := vv.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"storage_type": res["StorageType"],
"protocol_type": res["ProtocolType"],
}
InstanceTypes = append(InstanceTypes, temp1)
}
}
}
}
}
}
mapping["instance_types"] = InstanceTypes
s = append(s, mapping)
}
d.SetId(strconv.FormatInt(time.Now().Unix(), 16))
if err := d.Set("zones", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudNatGateways() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudNatGatewaysRead,
Schema: map[string]*schema.Schema{
"dry_run": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"nat_gateway_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"nat_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Enhanced", "Normal"}, false),
},
"payment_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo", "Subscription"}, false),
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"specification": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Large", "Middle", "Small", "XLarge.1"}, false),
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "Converting", "Creating", "Deleting", "Modifying"}, false),
},
"tags": tagsSchema(),
"vpc_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"page_number": {
Type: schema.TypeInt,
Optional: true,
},
"page_size": {
Type: schema.TypeInt,
Optional: true,
Default: 50,
},
"gateways": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"business_status": {
Type: schema.TypeString,
Computed: true,
},
"deletion_protection": {
Type: schema.TypeBool,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"ecs_metric_enabled": {
Type: schema.TypeBool,
Computed: true,
},
"expired_time": {
Type: schema.TypeString,
Computed: true,
},
"forward_table_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"internet_charge_type": {
Type: schema.TypeString,
Computed: true,
},
"ip_lists": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"nat_gateway_id": {
Type: schema.TypeString,
Computed: true,
},
"nat_gateway_name": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"nat_type": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"snat_table_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"specification": {
Type: schema.TypeString,
Computed: true,
},
"spec": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"network_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"total_count": {
Type: schema.TypeInt,
Computed: true,
},
},
}
}
func dataSourceAlicloudNatGatewaysRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeNatGateways"
request := make(map[string]interface{})
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
if v, ok := d.GetOk("nat_gateway_name"); ok {
request["Name"] = v
}
if v, ok := d.GetOk("nat_type"); ok {
request["NatType"] = v
}
if v, ok := d.GetOk("payment_type"); ok {
request["InstanceChargeType"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("specification"); ok {
request["Spec"] = v
}
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
if v, ok := d.GetOk("tags"); ok {
tags := make([]map[string]interface{}, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, map[string]interface{}{
"Key": key,
"Value": value.(string),
})
}
request["Tag"] = tags
}
if v, ok := d.GetOk("vpc_id"); ok {
request["VpcId"] = v
}
if v, ok := d.GetOk("page_number"); ok && v.(int) > 0 {
request["PageNumber"] = v.(int)
} else {
request["PageNumber"] = 1
}
if v, ok := d.GetOk("page_size"); ok && v.(int) > 0 {
request["PageSize"] = v.(int)
} else {
request["PageSize"] = PageSizeLarge
}
var objects []interface{}
var natGatewayNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
natGatewayNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_nat_gateways", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.NatGateways.NatGateway", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.NatGateways.NatGateway", response)
}
result, _ := resp.([]interface{})
if isPagingRequest(d) {
objects = result
break
}
for _, v := range result {
item := v.(map[string]interface{})
if natGatewayNameRegex != nil {
if !natGatewayNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["NatGatewayId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, v := range objects {
object := v.(map[string]interface{})
mapping := map[string]interface{}{
"business_status": object["BusinessStatus"],
"deletion_protection": object["DeletionProtection"],
"description": object["Description"],
"ecs_metric_enabled": object["EcsMetricEnabled"],
"expired_time": object["ExpiredTime"],
"forward_table_ids": object["ForwardTableIds"].(map[string]interface{})["ForwardTableId"],
"internet_charge_type": object["InternetChargeType"],
"id": fmt.Sprint(object["NatGatewayId"]),
"nat_gateway_id": fmt.Sprint(object["NatGatewayId"]),
"nat_gateway_name": object["Name"],
"name": object["Name"],
"nat_type": object["NatType"],
"network_type": object["NetworkType"],
"payment_type": convertNatGatewayPaymentTypeResponse(object["InstanceChargeType"].(string)),
"resource_group_id": object["ResourceGroupId"],
"snat_table_ids": object["SnatTableIds"].(map[string]interface{})["SnatTableId"],
"specification": object["Spec"],
"spec": object["Spec"],
"status": object["Status"],
"vswitch_id": object["NatGatewayPrivateInfo"].(map[string]interface{})["VswitchId"],
"vpc_id": object["VpcId"],
}
ipList := make([]string, 0)
if ipListList, ok := object["IpLists"].(map[string]interface{})["IpList"].([]interface{}); ok {
for _, v := range ipListList {
if m1, ok := v.(map[string]interface{}); ok {
ipList = append(ipList, fmt.Sprint(m1["IpAddress"]))
}
}
}
mapping["ip_lists"] = ipList
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["NatGatewayId"]))
names = append(names, object["Name"])
s = append(s, mapping)
continue
}
vpcService := VpcService{client}
id := fmt.Sprint(object["NatGatewayId"])
getResp, err := vpcService.ListTagResources(id, "NATGATEWAY")
if err != nil {
return WrapError(err)
}
mapping["tags"] = tagsToMap(getResp)
ids = append(ids, fmt.Sprint(object["NatGatewayId"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("gateways", s); err != nil {
return WrapError(err)
}
if err := d.Set("total_count", formatInt(response["TotalCount"])); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudNetworkAcls() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudNetworkAclsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"network_acl_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"resource_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"resource_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "Modifying"}, false),
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"acls": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Computed: true,
},
"egress_acl_entries": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Computed: true,
},
"destination_cidr_ip": {
Type: schema.TypeString,
Computed: true,
},
"network_acl_entry_name": {
Type: schema.TypeString,
Computed: true,
},
"policy": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeString,
Computed: true,
},
"protocol": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"ingress_acl_entries": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Computed: true,
},
"network_acl_entry_name": {
Type: schema.TypeString,
Computed: true,
},
"policy": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeString,
Computed: true,
},
"protocol": {
Type: schema.TypeString,
Computed: true,
},
"source_cidr_ip": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"network_acl_id": {
Type: schema.TypeString,
Computed: true,
},
"network_acl_name": {
Type: schema.TypeString,
Computed: true,
},
"resources": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"resource_id": {
Type: schema.TypeString,
Computed: true,
},
"resource_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudNetworkAclsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeNetworkAcls"
request := make(map[string]interface{})
if v, ok := d.GetOk("network_acl_name"); ok {
request["NetworkAclName"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_id"); ok {
request["ResourceId"] = v
}
if v, ok := d.GetOk("resource_type"); ok {
request["ResourceType"] = v
}
if v, ok := d.GetOk("vpc_id"); ok {
request["VpcId"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var networkAclNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
networkAclNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_network_acls", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.NetworkAcls.NetworkAcl", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.NetworkAcls.NetworkAcl", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if networkAclNameRegex != nil {
if !networkAclNameRegex.MatchString(fmt.Sprint(item["NetworkAclName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["NetworkAclId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"description": object["Description"],
"id": fmt.Sprint(object["NetworkAclId"]),
"network_acl_id": fmt.Sprint(object["NetworkAclId"]),
"network_acl_name": object["NetworkAclName"],
"status": object["Status"],
"vpc_id": object["VpcId"],
}
egressAclEntry := make([]map[string]interface{}, 0)
if egressAclEntryList, ok := object["EgressAclEntries"].(map[string]interface{})["EgressAclEntry"].([]interface{}); ok {
for _, v := range egressAclEntryList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"description": m1["Description"],
"destination_cidr_ip": m1["DestinationCidrIp"],
"network_acl_entry_name": m1["NetworkAclEntryName"],
"policy": m1["Policy"],
"port": m1["Port"],
"protocol": m1["Protocol"],
}
egressAclEntry = append(egressAclEntry, temp1)
}
}
}
mapping["egress_acl_entries"] = egressAclEntry
ingressAclEntry := make([]map[string]interface{}, 0)
if ingressAclEntryList, ok := object["IngressAclEntries"].(map[string]interface{})["IngressAclEntry"].([]interface{}); ok {
for _, v := range ingressAclEntryList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"description": m1["Description"],
"network_acl_entry_name": m1["NetworkAclEntryName"],
"policy": m1["Policy"],
"port": m1["Port"],
"protocol": m1["Protocol"],
"source_cidr_ip": m1["SourceCidrIp"],
}
ingressAclEntry = append(ingressAclEntry, temp1)
}
}
}
mapping["ingress_acl_entries"] = ingressAclEntry
resourceMap := make([]map[string]interface{}, 0)
if resourceMapList, ok := object["Resources"].(map[string]interface{})["Resource"].([]interface{}); ok {
for _, v := range resourceMapList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"resource_id": m1["ResourceId"],
"resource_type": m1["ResourceType"],
"status": m1["Status"],
}
resourceMap = append(resourceMap, temp1)
}
}
}
mapping["resources"] = resourceMap
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["NetworkAclName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("acls", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudOnsGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudOnsGroupsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"group_id_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"group_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "tcp",
ValidateFunc: validation.StringInSlice([]string{"http", "tcp"}, false),
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"tags": tagsSchema(),
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"group_name": {
Type: schema.TypeString,
Computed: true,
},
"group_type": {
Type: schema.TypeString,
Computed: true,
},
"independent_naming": {
Type: schema.TypeBool,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"owner": {
Type: schema.TypeString,
Computed: true,
},
"remark": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudOnsGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "OnsGroupList"
request := make(map[string]interface{})
if v, ok := d.GetOk("group_type"); ok {
request["GroupType"] = v
}
if v, ok := d.GetOk("instance_id"); ok {
request["InstanceId"] = v
}
if v, ok := d.GetOk("tags"); ok {
tags := make([]map[string]interface{}, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, map[string]interface{}{
"Key": key,
"Value": value.(string),
})
}
request["Tag"] = tags
}
var objects []map[string]interface{}
var groupNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
groupNameRegex = r
}
if v, ok := d.GetOk("group_id_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
groupNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewOnsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-02-14"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ons_groups", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Data.SubscribeInfoDo", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Data.SubscribeInfoDo", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if groupNameRegex != nil {
if !groupNameRegex.MatchString(fmt.Sprint(item["GroupId"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["GroupId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["GroupId"]),
"group_name": fmt.Sprint(object["GroupId"]),
"group_type": object["GroupType"],
"independent_naming": object["IndependentNaming"],
"instance_id": object["InstanceId"],
"owner": object["Owner"],
"remark": object["Remark"],
}
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags.Tag", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["Key"].(string)
value := t.(map[string]interface{})["Value"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
ids = append(ids, fmt.Sprint(object["GroupId"]))
names = append(names, object["GroupId"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudOnsInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudOnsInstancesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IntInSlice([]int{0, 2, 5, 7}),
},
"tags": tagsSchema(),
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"http_internal_endpoint": {
Type: schema.TypeString,
Computed: true,
},
"http_internet_endpoint": {
Type: schema.TypeString,
Computed: true,
},
"http_internet_secure_endpoint": {
Type: schema.TypeString,
Computed: true,
},
"independent_naming": {
Type: schema.TypeBool,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_name": {
Type: schema.TypeString,
Computed: true,
},
"instance_type": {
Type: schema.TypeInt,
Computed: true,
},
"release_time": {
Type: schema.TypeString,
Computed: true,
},
"remark": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeInt,
Computed: true,
},
"instance_status": {
Type: schema.TypeInt,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"tcp_endpoint": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudOnsInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "OnsInstanceInServiceList"
request := make(map[string]interface{})
if v, ok := d.GetOk("tags"); ok {
tags := make([]map[string]interface{}, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, map[string]interface{}{
"Key": key,
"Value": value.(string),
})
}
request["Tag"] = tags
}
var objects []map[string]interface{}
var instanceNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
instanceNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOkExists("status")
var response map[string]interface{}
conn, err := client.NewOnsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-02-14"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ons_instances", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Data.InstanceVO", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Data.InstanceVO", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if instanceNameRegex != nil {
if !instanceNameRegex.MatchString(fmt.Sprint(item["InstanceName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["InstanceId"])]; !ok {
continue
}
}
if statusOk && status.(int) != formatInt(item["InstanceStatus"]) {
continue
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"independent_naming": object["IndependentNaming"],
"id": fmt.Sprint(object["InstanceId"]),
"instance_id": fmt.Sprint(object["InstanceId"]),
"instance_name": object["InstanceName"],
"instance_type": formatInt(object["InstanceType"]),
"release_time": fmt.Sprint(formatInt(object["ReleaseTime"])),
"status": formatInt(object["InstanceStatus"]),
"instance_status": formatInt(object["InstanceStatus"]),
}
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags.Tag", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["Key"].(string)
value := t.(map[string]interface{})["Value"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["InstanceId"]))
names = append(names, object["InstanceName"])
s = append(s, mapping)
continue
}
onsService := OnsService{client}
id := fmt.Sprint(object["InstanceId"])
getResp, err := onsService.DescribeOnsInstance(id)
if err != nil {
return WrapError(err)
}
mapping["http_internal_endpoint"] = getResp["Endpoints"].(map[string]interface{})["HttpInternalEndpoint"]
mapping["http_internet_endpoint"] = getResp["Endpoints"].(map[string]interface{})["HttpInternetEndpoint"]
mapping["http_internet_secure_endpoint"] = getResp["Endpoints"].(map[string]interface{})["HttpInternetSecureEndpoint"]
mapping["remark"] = getResp["Remark"]
mapping["tcp_endpoint"] = getResp["Endpoints"].(map[string]interface{})["TcpEndpoint"]
ids = append(ids, fmt.Sprint(object["InstanceId"]))
names = append(names, object["InstanceName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudOnsService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudOnsServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudOnsServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("OnsServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
action := "OpenOnsService"
request := map[string]interface{}{}
conn, err := meta.(*connectivity.AliyunClient).NewTeaCommonClient(connectivity.OpenOnsService)
if err != nil {
return WrapError(err)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-02-14"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"QPS Limit Exceeded"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
addDebug(action, response, nil)
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"OrderOpend"}) {
d.SetId("OnsServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ons_service", action, AlibabaCloudSdkGoERROR)
}
d.SetId("OnsServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudOnsTopics() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudOnsTopicsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"tags": tagsSchema(),
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"topics": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"independent_naming": {
Type: schema.TypeBool,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"message_type": {
Type: schema.TypeInt,
Computed: true,
},
"owner": {
Type: schema.TypeString,
Computed: true,
},
"perm": {
Type: schema.TypeInt,
Computed: true,
},
"relation": {
Type: schema.TypeInt,
Computed: true,
},
"relation_name": {
Type: schema.TypeString,
Computed: true,
},
"remark": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"topic_name": {
Type: schema.TypeString,
Computed: true,
},
"topic": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudOnsTopicsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "OnsTopicList"
request := make(map[string]interface{})
if v, ok := d.GetOk("instance_id"); ok {
request["InstanceId"] = v
}
if v, ok := d.GetOk("tags"); ok {
tags := make([]map[string]interface{}, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, map[string]interface{}{
"Key": key,
"Value": value.(string),
})
}
request["Tag"] = tags
}
var objects []map[string]interface{}
var topicNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
topicNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewOnsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-02-14"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ons_topics", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Data.PublishInfoDo", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Data.PublishInfoDo", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if topicNameRegex != nil {
if !topicNameRegex.MatchString(fmt.Sprint(item["Topic"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Topic"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"independent_naming": object["IndependentNaming"],
"instance_id": object["InstanceId"],
"message_type": formatInt(object["MessageType"]),
"owner": object["Owner"],
"relation": formatInt(object["Relation"]),
"relation_name": object["RelationName"],
"remark": object["Remark"],
"id": fmt.Sprint(object["Topic"]),
"topic_name": fmt.Sprint(object["Topic"]),
"topic": fmt.Sprint(object["Topic"]),
}
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags.Tag", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["Key"].(string)
value := t.(map[string]interface{})["Value"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["Topic"]))
names = append(names, object["Topic"])
s = append(s, mapping)
continue
}
onsService := OnsService{client}
id := fmt.Sprint(object["InstanceId"], ":", object["Topic"])
getResp, err := onsService.OnsTopicStatus(id)
if err != nil {
return WrapError(err)
}
mapping["perm"] = getResp["Perm"]
ids = append(ids, fmt.Sprint(object["Topic"]))
names = append(names, object["Topic"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("topics", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudOosApplicationGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudOosApplicationGroupsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"application_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"deploy_region_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"application_group_name": {
Type: schema.TypeString,
Computed: true,
},
"application_name": {
Type: schema.TypeString,
Computed: true,
},
"cms_group_id": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"update_time": {
Type: schema.TypeString,
Computed: true,
},
"deploy_region_id": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"import_tag_key": {
Type: schema.TypeString,
Computed: true,
},
"import_tag_value": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudOosApplicationGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListApplicationGroups"
request := make(map[string]interface{})
request["ApplicationName"] = d.Get("application_name")
if v, ok := d.GetOk("deploy_region_id"); ok {
request["DeployRegionId"] = v
}
request["RegionId"] = client.RegionId
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var applicationGroupNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
applicationGroupNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_oos_application_groups", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.ApplicationGroups", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.ApplicationGroups", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if applicationGroupNameRegex != nil && !applicationGroupNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Name"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["Name"]),
"application_group_name": fmt.Sprint(object["Name"]),
"application_name": object["ApplicationName"],
"cms_group_id": object["CmsGroupId"],
"create_time": object["CreateDate"],
"deploy_region_id": object["DeployRegionId"],
"description": object["Description"],
"import_tag_key": object["ImportTagKey"],
"import_tag_value": object["ImportTagValue"],
"update_time": object["UpdateDate"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudOosApplications() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudOosApplicationsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"tags": tagsSchema(),
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"applications": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"application_name": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"update_time": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudOosApplicationsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListApplications"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
nameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
tagsMap := make(map[string]interface{})
if v, ok := d.GetOk("tags"); ok && len(v.(map[string]interface{})) > 0 {
tagsMap = v.(map[string]interface{})
}
var response map[string]interface{}
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_oos_applications", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Applications", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Applications", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if nameRegex != nil && !nameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Name"])]; !ok {
continue
}
}
if len(tagsMap) > 0 {
tagsItem := tagsToMap(item["Tags"])
if len(tagsItem) != len(tagsMap) {
continue
}
match := true
for key, value := range tagsItem {
if v, ok := tagsMap[key]; !ok || v.(string) != value {
match = false
break
}
}
if !match {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["Name"]),
"application_name": fmt.Sprint(object["Name"]),
"create_time": object["CreateDate"],
"update_time": object["UpdateDate"],
"description": object["Description"],
"resource_group_id": object["ResourceGroupId"],
"tags": tagsToMap(object["Tags"]),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("applications", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudOosExecutions() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudOosExecutionsRead,
Schema: map[string]*schema.Schema{
"category": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"AlarmTrigger", "EventTrigger", "Other", "TimerTrigger"}, false),
},
"end_date": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"end_date_after": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"executed_by": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"include_child_execution": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"mode": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "Automatic",
ValidateFunc: validation.StringInSlice([]string{"Automatic", "Debug"}, false),
},
"parent_execution_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ram_role": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"sort_field": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"sort_order": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"start_date_after": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"start_date_before": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Cancelled", "Failed", "Queued", "Running", "Started", "Success", "Waiting"}, false),
},
"tags": tagsSchema(),
"template_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"executions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"category": {
Type: schema.TypeString,
Computed: true,
},
"counters": {
Type: schema.TypeString,
Computed: true,
},
"create_date": {
Type: schema.TypeString,
Computed: true,
},
"end_date": {
Type: schema.TypeString,
Computed: true,
},
"executed_by": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"execution_id": {
Type: schema.TypeString,
Computed: true,
},
"is_parent": {
Type: schema.TypeBool,
Computed: true,
},
"mode": {
Type: schema.TypeString,
Computed: true,
},
"outputs": {
Type: schema.TypeString,
Computed: true,
},
"parameters": {
Type: schema.TypeString,
Computed: true,
},
"parent_execution_id": {
Type: schema.TypeString,
Computed: true,
},
"ram_role": {
Type: schema.TypeString,
Computed: true,
},
"start_date": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"status_message": {
Type: schema.TypeString,
Computed: true,
},
"status_reason": {
Type: schema.TypeString,
Computed: true,
},
"template_id": {
Type: schema.TypeString,
Computed: true,
},
"template_name": {
Type: schema.TypeString,
Computed: true,
},
"template_version": {
Type: schema.TypeString,
Computed: true,
},
"update_date": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudOosExecutionsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListExecutions"
request := make(map[string]interface{})
if v, ok := d.GetOk("category"); ok {
request["Category"] = v
}
if v, ok := d.GetOk("end_date"); ok {
request["EndDateBefore"] = v
}
if v, ok := d.GetOk("end_date_after"); ok {
request["EndDateAfter"] = v
}
if v, ok := d.GetOk("executed_by"); ok {
request["ExecutedBy"] = v
}
if v, ok := d.GetOkExists("include_child_execution"); ok {
request["IncludeChildExecution"] = v
}
if v, ok := d.GetOk("mode"); ok {
request["Mode"] = v
}
if v, ok := d.GetOk("parent_execution_id"); ok {
request["ParentExecutionId"] = v
}
if v, ok := d.GetOk("ram_role"); ok {
request["RamRole"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("sort_field"); ok {
request["SortField"] = v
}
if v, ok := d.GetOk("sort_order"); ok {
request["SortOrder"] = v
}
if v, ok := d.GetOk("start_date_after"); ok {
request["StartDateAfter"] = v
}
if v, ok := d.GetOk("start_date_before"); ok {
request["StartDateBefore"] = v
}
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
if v, ok := d.GetOk("tags"); ok {
respJson, err := convertMaptoJsonString(v.(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request["Tags"] = respJson
}
if v, ok := d.GetOk("template_name"); ok {
request["TemplateName"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_oos_executions", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Executions", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Executions", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ExecutionId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
parameters, _ := convertMaptoJsonString(object["Parameters"].(map[string]interface{}))
counters, _ := convertMapFloat64ToJsonString(object["Counters"].(map[string]interface{}))
mapping := map[string]interface{}{
"category": object["Category"],
"counters": counters,
"create_date": object["CreateDate"],
"end_date": object["EndDate"],
"executed_by": object["ExecutedBy"],
"id": fmt.Sprint(object["ExecutionId"]),
"execution_id": fmt.Sprint(object["ExecutionId"]),
"is_parent": object["IsParent"],
"mode": object["Mode"],
"outputs": object["Outputs"],
"parameters": parameters,
"parent_execution_id": object["ParentExecutionId"],
"ram_role": object["RamRole"],
"start_date": object["StartDate"],
"status": object["Status"],
"status_message": object["StatusMessage"],
"status_reason": object["StatusReason"],
"template_id": object["TemplateId"],
"template_name": object["TemplateName"],
"template_version": object["TemplateVersion"],
"update_date": object["UpdateDate"],
}
ids = append(ids, fmt.Sprint(object["ExecutionId"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("executions", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudOosParameters() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudOosParametersRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"parameter_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"sort_field": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Name", "CreatedDate"}, false),
},
"sort_order": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Ascending", "Descending"}, false),
},
"tags": tagsSchema(),
"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"String", "StringList"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"parameters": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"constraints": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"created_by": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"parameter_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"parameter_name": {
Type: schema.TypeString,
Computed: true,
},
"parameter_version": {
Type: schema.TypeInt,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"share_type": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"updated_by": {
Type: schema.TypeString,
Computed: true,
},
"updated_date": {
Type: schema.TypeString,
Computed: true,
},
"value": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudOosParametersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListParameters"
request := make(map[string]interface{})
if v, ok := d.GetOk("parameter_name"); ok {
request["Name"] = v
}
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("sort_field"); ok {
request["SortField"] = v
}
if v, ok := d.GetOk("sort_order"); ok {
request["SortOrder"] = v
}
if v, ok := d.GetOk("type"); ok {
request["Type"] = v
}
if v, ok := d.GetOk("tags"); ok {
respJson, err := convertMaptoJsonString(v.(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request["Tags"] = respJson
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var parameterNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
parameterNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_oos_parameters", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Parameters", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Parameters", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if parameterNameRegex != nil && !parameterNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Name"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": object["CreatedDate"],
"created_by": object["CreatedBy"],
"description": object["Description"],
"parameter_id": object["Id"],
"id": fmt.Sprint(object["Name"]),
"parameter_name": fmt.Sprint(object["Name"]),
"parameter_version": formatInt(object["ParameterVersion"]),
"resource_group_id": object["ResourceGroupId"],
"share_type": object["ShareType"],
"type": object["Type"],
"updated_by": object["UpdatedBy"],
"updated_date": object["UpdatedDate"],
}
mapping["tags"] = tagsToMap(object["Tags"])
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["Name"])
oosService := OosService{client}
getResp, err := oosService.DescribeOosParameter(id)
if err != nil {
return WrapError(err)
}
mapping["constraints"] = getResp["Constraints"]
mapping["value"] = getResp["Value"]
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("parameters", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudOosPatchBaselines() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudOosPatchBaselinesRead,
Schema: map[string]*schema.Schema{
"operation_system": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"AliyunLinux", "Anolis", "Centos", "Debian", "RedhatEnterpriseLinux", "Ubuntu", "Windows"}, false),
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"share_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Private", "Public"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"baselines": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"approval_rules": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"created_by": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"is_default": {
Type: schema.TypeBool,
Computed: true,
},
"operation_system": {
Type: schema.TypeString,
Computed: true,
},
"patch_baseline_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"patch_baseline_name": {
Type: schema.TypeString,
Computed: true,
},
"share_type": {
Type: schema.TypeString,
Computed: true,
},
"updated_by": {
Type: schema.TypeString,
Computed: true,
},
"updated_date": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudOosPatchBaselinesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListPatchBaselines"
request := make(map[string]interface{})
if v, ok := d.GetOk("operation_system"); ok {
request["OperationSystem"] = v
}
if v, ok := d.GetOk("share_type"); ok {
request["ShareType"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var patchBaselineNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
patchBaselineNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_oos_patch_baselines", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.PatchBaselines", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.PatchBaselines", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if patchBaselineNameRegex != nil && !patchBaselineNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Name"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": object["CreatedDate"],
"created_by": object["CreatedBy"],
"description": object["Description"],
"is_default": object["IsDefault"],
"operation_system": object["OperationSystem"],
"patch_baseline_id": object["Id"],
"id": fmt.Sprint(object["Name"]),
"patch_baseline_name": fmt.Sprint(object["Name"]),
"share_type": object["ShareType"],
"updated_by": object["UpdatedBy"],
"updated_date": object["UpdatedDate"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["Name"])
oosService := OosService{client}
getResp, err := oosService.DescribeOosPatchBaseline(id)
if err != nil {
return WrapError(err)
}
if v, err := convertMaptoJsonString(getResp["ApprovalRules"].(map[string]interface{})); err == nil {
mapping["approval_rules"] = v
}
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("baselines", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudOosSecretParameters() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudOosSecretParametersRead,
Schema: map[string]*schema.Schema{
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"secret_parameter_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"sort_field": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Name", "CreatedDate"}, false),
},
"sort_order": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Ascending", "Descending"}, false),
},
"tags": tagsSchema(),
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"parameters": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"constraints": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"created_by": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"key_id": {
Type: schema.TypeString,
Computed: true,
},
"parameter_version": {
Type: schema.TypeInt,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"secret_parameter_id": {
Type: schema.TypeString,
Computed: true,
},
"secret_parameter_name": {
Type: schema.TypeString,
Computed: true,
},
"share_type": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"updated_by": {
Type: schema.TypeString,
Computed: true,
},
"updated_date": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudOosSecretParametersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListSecretParameters"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("secret_parameter_name"); ok {
request["Name"] = v
}
if v, ok := d.GetOk("sort_field"); ok {
request["SortField"] = v
}
if v, ok := d.GetOk("sort_order"); ok {
request["SortOrder"] = v
}
if v, ok := d.GetOk("tags"); ok {
respJson, err := convertMaptoJsonString(v.(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request["Tags"] = respJson
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var secretParameterNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
secretParameterNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_oos_secret_parameters", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Parameters", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Parameters", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Name"])]; !ok {
continue
}
}
if secretParameterNameRegex != nil && !secretParameterNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["Name"]),
"create_time": object["CreatedDate"],
"created_by": object["CreatedBy"],
"description": object["Description"],
"key_id": object["KeyId"],
"parameter_version": formatInt(object["ParameterVersion"]),
"resource_group_id": object["ResourceGroupId"],
"secret_parameter_id": object["Id"],
"secret_parameter_name": object["Name"],
"share_type": object["ShareType"],
"type": object["Type"],
"updated_by": object["UpdatedBy"],
"updated_date": object["UpdatedDate"],
}
mapping["tags"] = tagsToMap(object["Tags"])
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["Name"])
oosService := OosService{client}
getResp, err := oosService.DescribeOosSecretParameter(id)
if err != nil {
return WrapError(err)
}
mapping["constraints"] = getResp["Constraints"]
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("parameters", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudOosStateConfigurations() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudOosStateConfigurationsRead,
Schema: map[string]*schema.Schema{
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"tags": tagsSchema(),
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"configurations": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"configure_mode": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"update_time": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"parameters": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"schedule_expression": {
Type: schema.TypeString,
Computed: true,
},
"schedule_type": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"state_configuration_id": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"targets": {
Type: schema.TypeString,
Computed: true,
},
"template_id": {
Type: schema.TypeString,
Computed: true,
},
"template_name": {
Type: schema.TypeString,
Computed: true,
},
"template_version": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudOosStateConfigurationsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListStateConfigurations"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
tagsMap := make(map[string]interface{})
if v, ok := d.GetOk("tags"); ok && len(v.(map[string]interface{})) > 0 {
tagsMap = v.(map[string]interface{})
}
var response map[string]interface{}
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_oos_state_configurations", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.StateConfigurations", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.StateConfigurations", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["StateConfigurationId"])]; !ok {
continue
}
}
if len(tagsMap) > 0 {
match := true
tagsItem := tagsToMap(item["Tags"])
for key, value := range tagsItem {
if v, ok := tagsMap[key]; !ok || v.(string) != value {
match = false
break
}
}
if !match {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"configure_mode": object["ConfigureMode"],
"create_time": object["CreateTime"],
"update_time": object["UpdateTime"],
"description": object["Description"],
"parameters": object["Parameters"],
"resource_group_id": object["ResourceGroupId"],
"schedule_expression": object["ScheduleExpression"],
"schedule_type": object["ScheduleType"],
"id": fmt.Sprint(object["StateConfigurationId"]),
"state_configuration_id": fmt.Sprint(object["StateConfigurationId"]),
"targets": object["Targets"],
"template_id": object["TemplateId"],
"template_name": object["TemplateName"],
"template_version": object["TemplateVersion"],
}
mapping["tags"] = tagsToMap(object["Tags"])
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("configurations", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudOosTemplates() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudOosTemplatesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"category": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"created_by": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"created_date": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"created_date_after": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"has_trigger": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"share_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Private", "Public"}, false),
},
"sort_field": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "TotalExecutionCount",
ValidateFunc: validation.StringInSlice([]string{"CreatedDate", "Popularity", "TemplateName", "TotalExecutionCount"}, false),
},
"sort_order": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "Descending",
ValidateFunc: validation.StringInSlice([]string{"Ascending", "Descending"}, false),
},
"tags": tagsSchema(),
"template_format": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"JSON", "YAML"}, false),
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"template_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"templates": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"category": {
Type: schema.TypeString,
Computed: true,
},
"created_by": {
Type: schema.TypeString,
Computed: true,
},
"created_date": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"has_trigger": {
Type: schema.TypeBool,
Computed: true,
},
"share_type": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"template_format": {
Type: schema.TypeString,
Computed: true,
},
"template_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"template_name": {
Type: schema.TypeString,
Computed: true,
},
"template_type": {
Type: schema.TypeString,
Computed: true,
},
"template_version": {
Type: schema.TypeString,
Computed: true,
},
"updated_by": {
Type: schema.TypeString,
Computed: true,
},
"updated_date": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudOosTemplatesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListTemplates"
request := make(map[string]interface{})
if v, ok := d.GetOk("category"); ok {
request["Category"] = v
}
if v, ok := d.GetOk("created_by"); ok {
request["CreatedBy"] = v
}
if v, ok := d.GetOk("created_date"); ok {
request["CreatedDateBefore"] = v
}
if v, ok := d.GetOk("created_date_after"); ok {
request["CreatedDateAfter"] = v
}
if v, ok := d.GetOkExists("has_trigger"); ok {
request["HasTrigger"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("share_type"); ok {
request["ShareType"] = v
}
if v, ok := d.GetOk("sort_field"); ok {
request["SortField"] = v
}
if v, ok := d.GetOk("sort_order"); ok {
request["SortOrder"] = v
}
if v, ok := d.GetOk("tags"); ok {
respJson, err := convertMaptoJsonString(v.(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request["Tags"] = respJson
}
if v, ok := d.GetOk("template_format"); ok {
request["TemplateFormat"] = v
}
if v, ok := d.GetOk("template_type"); ok {
request["TemplateType"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var templateNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
templateNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_oos_templates", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Templates", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Templates", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if templateNameRegex != nil {
if !templateNameRegex.MatchString(fmt.Sprint(item["TemplateName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["TemplateName"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"category": object["Category"],
"created_by": object["CreatedBy"],
"created_date": object["CreatedDate"],
"description": object["Description"],
"has_trigger": object["HasTrigger"],
"share_type": object["ShareType"],
"tags": object["Tags"],
"template_format": object["TemplateFormat"],
"template_id": object["TemplateId"],
"id": fmt.Sprint(object["TemplateName"]),
"template_name": fmt.Sprint(object["TemplateName"]),
"template_type": object["TemplateType"],
"template_version": object["TemplateVersion"],
"updated_by": object["UpdatedBy"],
"updated_date": object["UpdatedDate"],
}
ids = append(ids, fmt.Sprint(object["TemplateName"]))
names = append(names, object["TemplateName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("templates", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"encoding/json"
"fmt"
"regexp"
"strconv"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudOpenSearchAppGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudOpenSearchAppGroupsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{`standard`, `enhanced`}, false),
},
"name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"app_group_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"app_group_name": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"charge_way": {
Type: schema.TypeInt,
Computed: true,
},
"commodity_code": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeInt,
Computed: true,
},
"current_version": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"domain": {
Type: schema.TypeString,
Computed: true,
},
"expire_on": {
Type: schema.TypeString,
Computed: true,
},
"first_rank_algo_deployment_id": {
Type: schema.TypeInt,
Computed: true,
},
"has_pending_quota_review_task": {
Type: schema.TypeInt,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"lock_mode": {
Type: schema.TypeString,
Computed: true,
},
"locked_by_expiration": {
Type: schema.TypeInt,
Computed: true,
},
"pending_second_rank_algo_deployment_id": {
Type: schema.TypeInt,
Computed: true,
},
"processing_order_id": {
Type: schema.TypeString,
Computed: true,
},
"produced": {
Type: schema.TypeInt,
Computed: true,
},
"project_id": {
Type: schema.TypeString,
Computed: true,
},
"quota": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"compute_resource": {
Type: schema.TypeString,
Computed: true,
},
"doc_size": {
Type: schema.TypeString,
Computed: true,
},
"spec": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"second_rank_algo_deployment_id": {
Type: schema.TypeInt,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"switched_time": {
Type: schema.TypeInt,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudOpenSearchAppGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "/v4/openapi/app-groups"
request := make(map[string]*string)
if v, ok := d.GetOk("instance_id"); ok {
request["instanceId"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("resource_group_id"); ok {
request["resourceGroupId"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("type"); ok {
request["type"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("name"); ok {
request["name"] = StringPointer(v.(string))
}
request["PageSize"] = StringPointer(strconv.Itoa(PageSizeLarge))
request["PageNumber"] = StringPointer("1")
var objects []map[string]interface{}
var appGroupNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
appGroupNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewOpensearchClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2017-12-25"), nil, StringPointer("GET"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug("GET "+action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_open_search_app_groups", action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return WrapError(fmt.Errorf("%s failed, response: %v", "GET "+action, response))
}
resp, err := jsonpath.Get("$.result", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.result", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if appGroupNameRegex != nil && !appGroupNameRegex.MatchString(fmt.Sprint(item["name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["name"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"payment_type": convertOpenSearchAppGroupPaymentTypeResponse(object["chargeType"].(string)),
"charge_way": formatInt(object["chargingWay"]),
"commodity_code": object["commodityCode"],
"create_time": formatInt(object["created"]),
"current_version": object["currentVersion"],
"description": object["description"],
"domain": object["domain"],
"expire_on": object["expireOn"],
"first_rank_algo_deployment_id": formatInt(object["firstRankAlgoDeploymentId"]),
"has_pending_quota_review_task": formatInt(object["hasPendingQuotaReviewTask"]),
"instance_id": object["instanceId"],
"lock_mode": object["lockMode"],
"locked_by_expiration": formatInt(object["lockedByExpiration"]),
"pending_second_rank_algo_deployment_id": formatInt(object["pendingSecondRankAlgoDeploymentId"]),
"processing_order_id": object["processingOrderId"],
"produced": formatInt(object["produced"]),
"project_id": object["projectId"],
"second_rank_algo_deployment_id": formatInt(object["secondRankAlgoDeploymentId"]),
"status": object["status"],
"switched_time": formatInt(object["switchedTime"]),
"type": object["type"],
}
quotaSli := make([]map[string]interface{}, 0)
if _, exist := object["quota"]; exist {
quotaval := object["quota"].(map[string]interface{})
quotaSli = append(quotaSli, map[string]interface{}{
"doc_size": quotaval["docSize"].(json.Number).String(),
"compute_resource": quotaval["computeResource"].(json.Number).String(),
"spec": quotaval["spec"],
})
}
mapping["quota"] = quotaSli
ids = append(ids, fmt.Sprint(mapping["name"]))
names = append(names, fmt.Sprint(mapping["name"]))
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["name"])
openSearchService := OpenSearchService{client}
getResp, err := openSearchService.DescribeOpenSearchAppGroup(id)
if err != nil {
return WrapError(err)
}
mapping["app_group_id"] = getResp["id"]
mapping["app_group_name"] = getResp["name"]
mapping["resource_group_id"] = getResp["resourceGroupId"]
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"log"
"regexp"
"strings"
"time"
"net/http"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudOssBucketObjects() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudOssBucketObjectsRead,
Schema: map[string]*schema.Schema{
"bucket_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"key_prefix": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"key_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"objects": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Computed: true,
},
"acl": {
Type: schema.TypeString,
Computed: true,
},
"content_type": {
Type: schema.TypeString,
Computed: true,
},
"content_length": {
Type: schema.TypeString,
Computed: true,
},
"cache_control": {
Type: schema.TypeString,
Computed: true,
},
"content_disposition": {
Type: schema.TypeString,
Computed: true,
},
"content_encoding": {
Type: schema.TypeString,
Computed: true,
},
"content_md5": {
Type: schema.TypeString,
Computed: true,
},
"expires": {
Type: schema.TypeString,
Computed: true,
},
"server_side_encryption": {
Type: schema.TypeString,
Computed: true,
},
"sse_kms_key_id": {
Type: schema.TypeString,
Computed: true,
},
"etag": {
Type: schema.TypeString,
Computed: true,
},
"storage_class": {
Type: schema.TypeString,
Computed: true,
},
"last_modification_time": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudOssBucketObjectsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
bucketName := d.Get("bucket_name").(string)
// List bucket objects
var initialOptions []oss.Option
if v, ok := d.GetOk("key_prefix"); ok && v.(string) != "" {
keyPrefix := v.(string)
initialOptions = append(initialOptions, oss.Prefix(keyPrefix))
}
var requestInfo *oss.Client
var allObjects []oss.ObjectProperties
nextMarker := ""
for {
var options []oss.Option
options = append(options, initialOptions...)
if nextMarker != "" {
options = append(options, oss.Marker(nextMarker))
}
raw, err := client.WithOssBucketByName(bucketName, func(bucket *oss.Bucket) (interface{}, error) {
requestInfo = &bucket.Client
return bucket.ListObjects(options...)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_oss_bucket_object", "ListObjects", AliyunOssGoSdk)
}
if debugOn() {
addDebug("ListObjects", raw, requestInfo, map[string]interface{}{"options": options})
}
response, _ := raw.(oss.ListObjectsResult)
if response.Objects == nil || len(response.Objects) < 1 {
break
}
if len(response.Objects) < 1 {
break
}
allObjects = append(allObjects, response.Objects...)
nextMarker = response.NextMarker
if nextMarker == "" {
break
}
}
var filteredObjectsTemp []oss.ObjectProperties
keyRegex, ok := d.GetOk("key_regex")
if ok && keyRegex.(string) != "" {
var r *regexp.Regexp
if keyRegex != "" {
r = regexp.MustCompile(keyRegex.(string))
}
for _, object := range allObjects {
if r != nil && !r.MatchString(object.Key) {
continue
}
filteredObjectsTemp = append(filteredObjectsTemp, object)
}
} else {
filteredObjectsTemp = allObjects
}
return bucketObjectsDescriptionAttributes(d, bucketName, filteredObjectsTemp, meta)
}
func bucketObjectsDescriptionAttributes(d *schema.ResourceData, bucketName string, objects []oss.ObjectProperties, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var ids []string
var s []map[string]interface{}
var requestInfo *oss.Client
for _, object := range objects {
mapping := map[string]interface{}{
"key": object.Key,
"etag": strings.Trim(object.ETag, `"`),
"storage_class": object.StorageClass,
"last_modification_time": object.LastModified.Format(time.RFC3339),
}
// Add metadata information
raw, err := client.WithOssBucketByName(bucketName, func(bucket *oss.Bucket) (interface{}, error) {
requestInfo = &bucket.Client
return bucket.GetObjectDetailedMeta(object.Key)
})
if err != nil {
log.Printf("[ERROR] Unable to get metadata for the object %s: %v", object.Key, err)
} else {
objectHeader, _ := raw.(http.Header)
mapping["content_type"] = objectHeader.Get("Content-Type")
mapping["content_length"] = objectHeader.Get("Content-Length")
mapping["cache_control"] = objectHeader.Get("Cache-Control")
mapping["content_disposition"] = objectHeader.Get("Content-Disposition")
mapping["content_encoding"] = objectHeader.Get("Content-Encoding")
mapping["content_md5"] = objectHeader.Get("Content-Md5")
mapping["expires"] = objectHeader.Get("Expires")
mapping["server_side_encryption"] = objectHeader.Get(oss.HTTPHeaderOssServerSideEncryption)
mapping["sse_kms_key_id"] = objectHeader.Get(oss.HTTPHeaderOssServerSideEncryptionKeyID)
}
if debugOn() {
addDebug("GetObjectDetailedMeta", raw, requestInfo, map[string]string{"objectKey": object.Key})
}
// Add ACL information
raw, err = client.WithOssBucketByName(bucketName, func(bucket *oss.Bucket) (interface{}, error) {
requestInfo = &bucket.Client
return bucket.GetObjectACL(object.Key)
})
if err != nil {
log.Printf("[ERROR] Unable to get ACL for the object %s: %v", object.Key, err)
} else {
objectACL, _ := raw.(oss.GetObjectACLResult)
mapping["acl"] = objectACL.ACL
}
if debugOn() {
addDebug("GetObjectACL", raw, requestInfo, map[string]string{"objectKey": object.Key})
}
ids = append(ids, object.Key)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("objects", s); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"io/ioutil"
"log"
"regexp"
"time"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudOssBuckets() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudOssBucketsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"buckets": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Computed: true,
},
"acl": {
Type: schema.TypeString,
Computed: true,
},
"extranet_endpoint": {
Type: schema.TypeString,
Computed: true,
},
"intranet_endpoint": {
Type: schema.TypeString,
Computed: true,
},
"location": {
Type: schema.TypeString,
Computed: true,
},
"owner": {
Type: schema.TypeString,
Computed: true,
},
"storage_class": {
Type: schema.TypeString,
Computed: true,
},
"redundancy_type": {
Type: schema.TypeString,
Computed: true,
},
"creation_date": {
Type: schema.TypeString,
Computed: true,
},
"cors_rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"allowed_headers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"allowed_methods": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"allowed_origins": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"expose_headers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"max_age_seconds": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"website": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"index_document": {
Type: schema.TypeString,
Computed: true,
},
"error_document": {
Type: schema.TypeString,
Computed: true,
},
},
},
MaxItems: 1,
},
"logging": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"target_bucket": {
Type: schema.TypeString,
Computed: true,
},
"target_prefix": {
Type: schema.TypeString,
Computed: true,
},
},
},
MaxItems: 1,
},
"referer_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"allow_empty": {
Type: schema.TypeBool,
Computed: true,
},
"referers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
MaxItems: 1,
},
"lifecycle_rule": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"prefix": {
Type: schema.TypeString,
Computed: true,
},
"enabled": {
Type: schema.TypeBool,
Computed: true,
},
"expiration": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"date": {
Type: schema.TypeString,
Optional: true,
},
"days": {
Type: schema.TypeInt,
Optional: true,
},
},
},
MaxItems: 1,
},
},
},
},
"policy": {
Type: schema.TypeString,
Optional: true,
},
"server_side_encryption_rule": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"sse_algorithm": {
Type: schema.TypeString,
Computed: true,
},
"kms_master_key_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
MaxItems: 1,
},
"tags": tagsSchemaComputed(),
"versioning": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
MaxItems: 1,
},
},
},
},
},
}
}
func dataSourceAlicloudOssBucketsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var requestInfo *oss.Client
var allBuckets []oss.BucketProperties
nextMarker := ""
for {
var options []oss.Option
if nextMarker != "" {
options = append(options, oss.Marker(nextMarker))
}
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return ossClient.ListBuckets(options...)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_oss_bucket", "CreateBucket", AliyunOssGoSdk)
}
if debugOn() {
addDebug("ListBuckets", raw, requestInfo, map[string]interface{}{"options": options})
}
response, _ := raw.(oss.ListBucketsResult)
if response.Buckets == nil || len(response.Buckets) < 1 {
break
}
allBuckets = append(allBuckets, response.Buckets...)
nextMarker = response.NextMarker
if nextMarker == "" {
break
}
}
var filteredBucketsTemp []oss.BucketProperties
nameRegex, ok := d.GetOk("name_regex")
if ok && nameRegex.(string) != "" {
var ossBucketNameRegex *regexp.Regexp
if nameRegex != "" {
r, err := regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
ossBucketNameRegex = r
}
for _, bucket := range allBuckets {
if ossBucketNameRegex != nil && !ossBucketNameRegex.MatchString(bucket.Name) {
continue
}
filteredBucketsTemp = append(filteredBucketsTemp, bucket)
}
} else {
filteredBucketsTemp = allBuckets
}
return bucketsDescriptionAttributes(d, filteredBucketsTemp, meta)
}
func bucketsDescriptionAttributes(d *schema.ResourceData, buckets []oss.BucketProperties, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var ids []string
var s []map[string]interface{}
var names []string
var requestInfo *oss.Client
for _, bucket := range buckets {
mapping := map[string]interface{}{
"name": bucket.Name,
"location": bucket.Location,
"storage_class": bucket.StorageClass,
"creation_date": bucket.CreationDate.Format("2006-01-02"),
}
// Add additional information
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return ossClient.GetBucketInfo(bucket.Name)
})
if err == nil {
if debugOn() {
addDebug("GetBucketInfo", raw, requestInfo, map[string]string{"bucketName": bucket.Name})
}
response, _ := raw.(oss.GetBucketInfoResult)
mapping["acl"] = response.BucketInfo.ACL
mapping["extranet_endpoint"] = response.BucketInfo.ExtranetEndpoint
mapping["intranet_endpoint"] = response.BucketInfo.IntranetEndpoint
mapping["owner"] = response.BucketInfo.Owner.ID
mapping["redundancy_type"] = response.BucketInfo.RedundancyType
//Add ServerSideEncryption information
var sseconfig []map[string]interface{}
if &response.BucketInfo.SseRule != nil {
if len(response.BucketInfo.SseRule.SSEAlgorithm) > 0 && response.BucketInfo.SseRule.SSEAlgorithm != "None" {
data := map[string]interface{}{
"sse_algorithm": response.BucketInfo.SseRule.SSEAlgorithm,
}
if response.BucketInfo.SseRule.KMSMasterKeyID != "" {
data["kms_master_key_id"] = response.BucketInfo.SseRule.KMSMasterKeyID
}
sseconfig = make([]map[string]interface{}, 0)
sseconfig = append(sseconfig, data)
}
}
mapping["server_side_encryption_rule"] = sseconfig
//Add versioning information
var versioning []map[string]interface{}
if response.BucketInfo.Versioning != "" {
data := map[string]interface{}{
"status": response.BucketInfo.Versioning,
}
versioning = make([]map[string]interface{}, 0)
versioning = append(versioning, data)
}
mapping["versioning"] = versioning
} else {
log.Printf("[WARN] Unable to get additional information for the bucket %s: %v", bucket.Name, err)
}
// Add CORS rule information
var ruleMappings []map[string]interface{}
raw, err = client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return ossClient.GetBucketCORS(bucket.Name)
})
if err == nil {
if debugOn() {
addDebug("GetBucketCORS", raw, requestInfo, map[string]string{"bucketName": bucket.Name})
}
cors, _ := raw.(oss.GetBucketCORSResult)
if cors.CORSRules != nil {
for _, rule := range cors.CORSRules {
ruleMapping := make(map[string]interface{})
ruleMapping["allowed_headers"] = rule.AllowedHeader
ruleMapping["allowed_methods"] = rule.AllowedMethod
ruleMapping["allowed_origins"] = rule.AllowedOrigin
ruleMapping["expose_headers"] = rule.ExposeHeader
ruleMapping["max_age_seconds"] = rule.MaxAgeSeconds
ruleMappings = append(ruleMappings, ruleMapping)
}
}
} else if !IsExpectedErrors(err, []string{"NoSuchCORSConfiguration"}) {
log.Printf("[WARN] Unable to get CORS information for the bucket %s: %v", bucket.Name, err)
}
mapping["cors_rules"] = ruleMappings
// Add website configuration
var websiteMappings []map[string]interface{}
raw, err = client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return ossClient.GetBucketWebsite(bucket.Name)
})
if err == nil {
if debugOn() {
addDebug("GetBucketWebsite", raw, requestInfo, map[string]string{"bucketName": bucket.Name})
}
ws, _ := raw.(oss.GetBucketWebsiteResult)
websiteMapping := make(map[string]interface{})
if v := &ws.IndexDocument; v != nil {
websiteMapping["index_document"] = v.Suffix
}
if v := &ws.ErrorDocument; v != nil {
websiteMapping["error_document"] = v.Key
}
websiteMappings = append(websiteMappings, websiteMapping)
} else if !IsExpectedErrors(err, []string{"NoSuchWebsiteConfiguration"}) {
log.Printf("[WARN] Unable to get website information for the bucket %s: %v", bucket.Name, err)
}
mapping["website"] = websiteMappings
// Add logging information
var loggingMappings []map[string]interface{}
raw, err = client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
return ossClient.GetBucketLogging(bucket.Name)
})
if err == nil {
addDebug("GetBucketLogging", raw)
logging, _ := raw.(oss.GetBucketLoggingResult)
if logging.LoggingEnabled.TargetBucket != "" || logging.LoggingEnabled.TargetPrefix != "" {
loggingMapping := map[string]interface{}{
"target_bucket": logging.LoggingEnabled.TargetBucket,
"target_prefix": logging.LoggingEnabled.TargetPrefix,
}
loggingMappings = append(loggingMappings, loggingMapping)
}
} else {
log.Printf("[WARN] Unable to get logging information for the bucket %s: %v", bucket.Name, err)
}
mapping["logging"] = loggingMappings
// Add referer information
var refererMappings []map[string]interface{}
raw, err = client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return ossClient.GetBucketReferer(bucket.Name)
})
if err == nil {
if debugOn() {
addDebug("GetBucketReferer", raw, requestInfo, map[string]string{"bucketName": bucket.Name})
}
referer, _ := raw.(oss.GetBucketRefererResult)
refererMapping := map[string]interface{}{
"allow_empty": referer.AllowEmptyReferer,
"referers": referer.RefererList,
}
refererMappings = append(refererMappings, refererMapping)
} else {
log.Printf("[WARN] Unable to get referer information for the bucket %s: %v", bucket.Name, err)
}
mapping["referer_config"] = refererMappings
// Add lifecycle information
var lifecycleRuleMappings []map[string]interface{}
raw, err = client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return ossClient.GetBucketLifecycle(bucket.Name)
})
if err == nil {
if debugOn() {
addDebug("GetBucketLifecycle", raw, requestInfo, map[string]string{"bucketName": bucket.Name})
}
lifecycle, _ := raw.(oss.GetBucketLifecycleResult)
if len(lifecycle.Rules) > 0 {
for _, lifecycleRule := range lifecycle.Rules {
ruleMapping := make(map[string]interface{})
ruleMapping["id"] = lifecycleRule.ID
ruleMapping["prefix"] = lifecycleRule.Prefix
if LifecycleRuleStatus(lifecycleRule.Status) == ExpirationStatusEnabled {
ruleMapping["enabled"] = true
} else {
ruleMapping["enabled"] = false
}
// Expiration
expirationMapping := make(map[string]interface{})
if lifecycleRule.Expiration.Date != "" {
t, err := time.Parse("2006-01-02T15:04:05.000Z", lifecycleRule.Expiration.Date)
if err != nil {
return WrapError(err)
}
expirationMapping["date"] = t.Format("2006-01-02")
}
if &lifecycleRule.Expiration.Days != nil {
expirationMapping["days"] = int(lifecycleRule.Expiration.Days)
}
ruleMapping["expiration"] = []map[string]interface{}{expirationMapping}
lifecycleRuleMappings = append(lifecycleRuleMappings, ruleMapping)
}
}
} else {
log.Printf("[WARN] Unable to get lifecycle information for the bucket %s: %v", bucket.Name, err)
}
mapping["lifecycle_rule"] = lifecycleRuleMappings
// Add policy information
var policy string
raw, err = client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
params := map[string]interface{}{}
params["policy"] = nil
return ossClient.Conn.Do("GET", bucket.Name, "", params, nil, nil, 0, nil)
})
if err == nil {
if debugOn() {
addDebug("GetPolicyByConn", raw, requestInfo, map[string]string{"bucketName": bucket.Name})
}
rawResp := raw.(*oss.Response)
rawData, err := ioutil.ReadAll(rawResp.Body)
if err != nil {
return WrapError(err)
}
policy = string(rawData)
} else {
log.Printf("[WARN] Unable to get policy information for the bucket %s: %v", bucket.Name, err)
}
mapping["policy"] = policy
// Add tags information
tagsMap := make(map[string]string)
raw, err = client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return ossClient.GetBucketTagging(bucket.Name)
})
if err == nil {
if debugOn() {
addDebug("GetBucketTagging", raw, requestInfo, map[string]string{"bucketName": bucket.Name})
}
tagging, _ := raw.(oss.GetBucketTaggingResult)
for _, t := range tagging.Tags {
tagsMap[t.Key] = t.Value
}
} else {
log.Printf("[WARN] Unable to get tagging information for the bucket %s: %v", bucket.Name, err)
}
mapping["tags"] = tagsMap
ids = append(ids, bucket.Name)
s = append(s, mapping)
names = append(names, bucket.Name)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("buckets", s); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudOssService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudOssServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudOssServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("OssServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
conn, err := meta.(*connectivity.AliyunClient).NewTeaCommonClient(connectivity.OpenOssService)
if err != nil {
return WrapError(err)
}
response, err := conn.DoRequest(StringPointer("OpenOssService"), nil, StringPointer("POST"), StringPointer("2019-04-22"), StringPointer("AK"), nil, nil, &util.RuntimeOptions{})
addDebug("OpenOssService", response, nil)
if err != nil {
if IsExpectedErrors(err, []string{"SYSTEM.SALE_VALIDATE_NO_SPECIFIC_CODE_FAILEDError", "ORDER.OPEND"}) {
d.SetId("OssServicHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_oss_service", "OpenOssService", AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprintf("%v", response["OrderId"]))
d.Set("status", "Opened")
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ots"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudOtsInstanceAttachments() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudOtsInstanceAttachmentsRead,
Schema: map[string]*schema.Schema{
"instance_name": {
Type: schema.TypeString,
Required: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"vpc_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"attachments": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"domain": {
Type: schema.TypeString,
Computed: true,
},
"endpoint": {
Type: schema.TypeString,
Computed: true,
},
"region": {
Type: schema.TypeString,
Computed: true,
},
"instance_name": {
Type: schema.TypeString,
Computed: true,
},
"vpc_name": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudOtsInstanceAttachmentsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
otsService := OtsService{client}
instanceName := d.Get("instance_name").(string)
allVpcs, err := otsService.ListOtsInstanceVpc(instanceName)
if err != nil {
return WrapError(err)
}
var filteredVpcs []ots.VpcInfo
if v, ok := d.GetOk("name_regex"); ok && v.(string) != "" {
r := regexp.MustCompile(v.(string))
for _, vpc := range allVpcs {
if r.MatchString(vpc.InstanceVpcName) {
filteredVpcs = append(filteredVpcs, vpc)
}
}
} else {
filteredVpcs = allVpcs[:]
}
return otsAttachmentsDescriptionAttributes(d, filteredVpcs, meta)
}
func otsAttachmentsDescriptionAttributes(d *schema.ResourceData, vpcInfos []ots.VpcInfo, meta interface{}) error {
var ids []string
var names []string
var vpcIds []string
var s []map[string]interface{}
for _, vpc := range vpcInfos {
mapping := map[string]interface{}{
"id": vpc.InstanceName,
"domain": vpc.Domain,
"endpoint": vpc.Endpoint,
"region": vpc.RegionNo,
"instance_name": vpc.InstanceName,
"vpc_name": vpc.InstanceVpcName,
"vpc_id": vpc.VpcId,
}
names = append(names, vpc.InstanceVpcName)
ids = append(ids, vpc.InstanceName)
vpcIds = append(vpcIds, vpc.VpcId)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("attachments", s); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("vpc_ids", vpcIds); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ots"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudOtsInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudOtsInstancesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
MinItems: 1,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.ValidateRegexp,
},
"tags": tagsSchema(),
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"write_capacity": {
Type: schema.TypeInt,
Computed: true,
},
"read_capacity": {
Type: schema.TypeInt,
Computed: true,
},
"cluster_type": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"user_id": {
Type: schema.TypeString,
Computed: true,
},
"network": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"entity_quota": {
Type: schema.TypeInt,
Computed: true,
},
"tags": tagsSchemaComputed(),
},
},
},
},
}
}
func dataSourceAlicloudOtsInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
otsService := OtsService{client}
allInstanceNames, err := otsService.ListOtsInstance(PageSizeLarge, 1)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ots_instances", "ListOtsInstance", AlibabaCloudSdkGoERROR)
}
idsMap := make(map[string]bool)
if v, ok := d.GetOk("ids"); ok && len(v.([]interface{})) > 0 {
for _, x := range v.([]interface{}) {
if x == nil {
continue
}
idsMap[x.(string)] = true
}
}
var nameReg *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok && v.(string) != "" {
nameReg = regexp.MustCompile(v.(string))
}
var filteredInstanceNames []string
for _, instanceName := range allInstanceNames {
// name_regex mismatch
if nameReg != nil && !nameReg.MatchString(instanceName) {
continue
}
// ids mismatch
if len(idsMap) != 0 {
if _, ok := idsMap[instanceName]; !ok {
continue
}
}
filteredInstanceNames = append(filteredInstanceNames, instanceName)
}
// get full instance info via GetInstance
var allInstances []ots.InstanceInfo
for _, instanceName := range filteredInstanceNames {
instanceInfo, err := otsService.DescribeOtsInstance(instanceName)
if err != nil {
return WrapError(err)
}
allInstances = append(allInstances, instanceInfo)
}
// filter by tag.
var filteredInstances []ots.InstanceInfo
if v, ok := d.GetOk("tags"); ok {
if vmap, ok := v.(map[string]interface{}); ok && len(vmap) > 0 {
for _, instance := range allInstances {
if tagsMapEqual(vmap, otsTagsToMap(instance.TagInfos.TagInfo)) {
filteredInstances = append(filteredInstances, instance)
}
}
} else {
filteredInstances = allInstances[:]
}
} else {
filteredInstances = allInstances[:]
}
return otsInstancesDecriptionAttributes(d, filteredInstances, meta)
}
func otsInstancesDecriptionAttributes(d *schema.ResourceData, instances []ots.InstanceInfo, meta interface{}) error {
var ids []string
var names []string
var s []map[string]interface{}
for _, instance := range instances {
mapping := map[string]interface{}{
"id": instance.InstanceName,
"name": instance.InstanceName,
"status": string(convertOtsInstanceStatusConvert(instance.Status)),
"write_capacity": instance.WriteCapacity,
"read_capacity": instance.ReadCapacity,
"cluster_type": instance.ClusterType,
"create_time": instance.CreateTime,
"user_id": instance.UserId,
"network": instance.Network,
"description": instance.Description,
"entity_quota": instance.Quota.EntityQuota,
"tags": otsTagsToMap(instance.TagInfos.TagInfo),
}
names = append(names, instance.InstanceName)
ids = append(ids, instance.InstanceName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudOtsService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudOtsServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudOtsServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("OtsServicHasNotBeenOpened")
d.Set("status", "")
return nil
}
conn, err := meta.(*connectivity.AliyunClient).NewTeaCommonClient(connectivity.OpenOtsService)
if err != nil {
return WrapError(err)
}
action := "OpenOtsService"
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-06-20"), StringPointer("AK"), nil, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
return resource.RetryableError(err)
}
addDebug(action, response, nil)
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
d.SetId(fmt.Sprintf("%v", response["OrderId"]))
d.Set("status", "Opened")
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ORDER.OPEND"}) {
d.SetId("OtsServicHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ots_service", "OpenOtsService", AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudOtsTables() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudOtsTablesRead,
Schema: map[string]*schema.Schema{
"instance_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
MinItems: 1,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.ValidateRegexp,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"tables": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"instance_name": {
Type: schema.TypeString,
Computed: true,
},
"table_name": {
Type: schema.TypeString,
Computed: true,
},
"primary_key": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
},
MaxItems: 4,
},
"time_to_live": {
Type: schema.TypeInt,
Computed: true,
},
"max_version": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
type OtsTableInfo struct {
instanceName string
tableName string
primaryKey []*tablestore.PrimaryKeySchema
timeToLive int
maxVersion int
}
func dataSourceAlicloudOtsTablesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
otsService := OtsService{client}
instanceName := d.Get("instance_name").(string)
object, err := otsService.ListOtsTable(instanceName)
if err != nil {
return WrapError(err)
}
idsMap := make(map[string]bool)
if v, ok := d.GetOk("ids"); ok && len(v.([]interface{})) > 0 {
for _, x := range v.([]interface{}) {
if x == nil {
continue
}
idsMap[x.(string)] = true
}
}
var nameReg *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok && v.(string) != "" {
nameReg = regexp.MustCompile(v.(string))
}
var filteredTableNames []string
for _, tableName := range object.TableNames {
//name_regex mismatch
if nameReg != nil && !nameReg.MatchString(tableName) {
continue
}
// ids mismatch
if len(idsMap) != 0 {
id := fmt.Sprintf("%s%s%s", instanceName, COLON_SEPARATED, tableName)
if _, ok := idsMap[id]; !ok {
continue
}
}
filteredTableNames = append(filteredTableNames, tableName)
}
// get full table info via DescribeTable
var allTableInfos []OtsTableInfo
for _, tableName := range filteredTableNames {
object, err := otsService.DescribeOtsTable(fmt.Sprintf("%s%s%s", instanceName, COLON_SEPARATED, tableName))
if err != nil {
return WrapError(err)
}
allTableInfos = append(allTableInfos, OtsTableInfo{
instanceName: instanceName,
tableName: object.TableMeta.TableName,
primaryKey: object.TableMeta.SchemaEntry,
timeToLive: object.TableOption.TimeToAlive,
maxVersion: object.TableOption.MaxVersion,
})
}
return otsTablesDescriptionAttributes(d, allTableInfos, meta)
}
func otsTablesDescriptionAttributes(d *schema.ResourceData, tableInfos []OtsTableInfo, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
otsService := OtsService{client}
var ids []string
var names []string
var s []map[string]interface{}
for _, table := range tableInfos {
id := fmt.Sprintf("%s:%s", table.instanceName, table.tableName)
mapping := map[string]interface{}{
"id": id,
"instance_name": table.instanceName,
"table_name": table.tableName,
"time_to_live": table.timeToLive,
"max_version": table.maxVersion,
}
var primaryKey []map[string]interface{}
for _, pk := range table.primaryKey {
pkColumn := make(map[string]interface{})
pkColumn["name"] = *pk.Name
pkColumn["type"] = otsService.convertPrimaryKeyType(*pk.Type)
primaryKey = append(primaryKey, pkColumn)
}
mapping["primary_key"] = primaryKey
names = append(names, table.tableName)
ids = append(ids, id)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("tables", s); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/services/polardb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudPolarDBAccounts() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudPolarDBAccountsRead,
Schema: map[string]*schema.Schema{
"db_cluster_id": {
Type: schema.TypeString,
Required: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"accounts": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_description": {
Type: schema.TypeString,
Computed: true,
},
"account_lock_state": {
Type: schema.TypeString,
Computed: true,
},
"account_name": {
Type: schema.TypeString,
Computed: true,
},
"account_status": {
Type: schema.TypeString,
Computed: true,
},
"account_type": {
Type: schema.TypeString,
Computed: true,
},
"database_privileges": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_privilege": {
Type: schema.TypeString,
Computed: true,
},
"db_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudPolarDBAccountsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := polardb.CreateDescribeAccountsRequest()
request.RegionId = client.RegionId
request.DBClusterId = d.Get("db_cluster_id").(string)
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
nameRegex = r
}
raw, err := client.WithPolarDBClient(func(client *polardb.Client) (interface{}, error) {
return client.DescribeAccounts(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_polardb_accounts", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*polardb.DescribeAccountsResponse)
var ids []string
var accounts []map[string]interface{}
if len(response.Accounts) > 0 {
for _, item := range response.Accounts {
if nameRegex != nil {
if !nameRegex.MatchString(item.AccountName) {
continue
}
}
var nodes []map[string]interface{}
for _, node := range item.DatabasePrivileges {
nodeMap := map[string]interface{}{
"account_privilege": node.AccountPrivilege,
"db_name": node.DBName,
}
nodes = append(nodes, nodeMap)
}
mapping := map[string]interface{}{
"account_description": item.AccountDescription,
"account_lock_state": item.AccountLockState,
"account_name": item.AccountName,
"account_status": item.AccountStatus,
"account_type": item.AccountType,
"database_privileges": nodes,
}
ids = append(ids, item.AccountName)
accounts = append(accounts, mapping)
}
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("accounts", accounts); err != nil {
return WrapError(err)
}
if err := d.Set("names", ids); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), accounts)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/polardb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudPolarDBClusters() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudPolarDBClustersRead,
Schema: map[string]*schema.Schema{
"description_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"status": {
Type: schema.TypeString,
Optional: true,
},
"db_type": {
Type: schema.TypeString,
Optional: true,
},
"tags": tagsSchema(),
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"descriptions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"clusters": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"charge_type": {
Type: schema.TypeString,
Computed: true,
},
"network_type": {
Type: schema.TypeString,
Computed: true,
},
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
"expire_time": {
Type: schema.TypeString,
Computed: true,
},
"expired": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"engine": {
Type: schema.TypeString,
Computed: true,
},
"db_type": {
Type: schema.TypeString,
Computed: true,
},
"db_version": {
Type: schema.TypeString,
Computed: true,
},
"lock_mode": {
Type: schema.TypeString,
Computed: true,
},
"delete_lock": {
Type: schema.TypeInt,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"db_node_number": {
Type: schema.TypeInt,
Computed: true,
},
"db_node_class": {
Type: schema.TypeString,
Computed: true,
},
"storage_used": {
Type: schema.TypeInt,
Computed: true,
},
"db_nodes": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"db_node_class": {
Type: schema.TypeString,
Computed: true,
},
"max_iops": {
Type: schema.TypeInt,
Computed: true,
},
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"db_node_role": {
Type: schema.TypeString,
Computed: true,
},
"max_connections": {
Type: schema.TypeInt,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
"db_node_status": {
Type: schema.TypeString,
Computed: true,
},
"db_node_id": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudPolarDBClustersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := polardb.CreateDescribeDBClustersRequest()
request.RegionId = client.RegionId
request.DBClusterStatus = d.Get("status").(string)
request.DBType = d.Get("db_type").(string)
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var dbi []polardb.DBCluster
var descriptionRegex *regexp.Regexp
if v, ok := d.GetOk("description_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
descriptionRegex = r
}
// ids
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
if v, ok := d.GetOk("tags"); ok {
var reqTags []polardb.DescribeDBClustersTag
for key, value := range v.(map[string]interface{}) {
reqTags = append(reqTags, polardb.DescribeDBClustersTag{
Key: key,
Value: value.(string),
})
}
request.Tag = &reqTags
}
for {
raw, err := client.WithPolarDBClient(func(polardbClient *polardb.Client) (interface{}, error) {
return polardbClient.DescribeDBClusters(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_polardb_clusters", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*polardb.DescribeDBClustersResponse)
if len(response.Items.DBCluster) < 1 {
break
}
for _, item := range response.Items.DBCluster {
if descriptionRegex != nil {
if !descriptionRegex.MatchString(item.DBClusterDescription) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[item.DBClusterId]; !ok {
continue
}
}
dbi = append(dbi, item)
}
if len(response.Items.DBCluster) < PageSizeLarge {
break
}
if page, err := getNextpageNumber(request.PageNumber); err != nil {
return WrapError(err)
} else {
request.PageNumber = page
}
}
return polarDBClustersDescription(d, dbi)
}
func polarDBClustersDescription(d *schema.ResourceData, dbi []polardb.DBCluster) error {
var ids []string
var descriptions []string
var s []map[string]interface{}
for _, item := range dbi {
var nodes []map[string]interface{}
for _, node := range item.DBNodes.DBNode {
nodeMap := map[string]interface{}{
"db_node_class": node.DBNodeClass,
"max_iops": node.MaxIOPS,
"db_node_role": node.DBNodeRole,
"region_id": node.RegionId,
"max_connections": node.MaxConnections,
"zone_id": node.ZoneId,
"db_node_status": node.DBNodeStatus,
"db_node_id": node.DBNodeId,
"create_time": node.CreationTime,
}
nodes = append(nodes, nodeMap)
}
mapping := map[string]interface{}{
"id": item.DBClusterId,
"description": item.DBClusterDescription,
"charge_type": getChargeType(item.PayType),
"network_type": item.DBClusterNetworkType,
"region_id": item.RegionId,
"zone_id": item.ZoneId,
"expire_time": item.ExpireTime,
"expired": item.Expired,
"status": item.DBClusterStatus,
"engine": item.Engine,
"db_type": item.DBType,
"db_version": item.DBVersion,
"lock_mode": item.LockMode,
"delete_lock": item.DeletionLock,
"create_time": item.CreateTime,
"vpc_id": item.VpcId,
"db_node_number": item.DBNodeNumber,
"db_node_class": item.DBNodeClass,
"storage_used": item.StorageUsed,
"db_nodes": nodes,
}
ids = append(ids, item.DBClusterId)
descriptions = append(descriptions, item.DBClusterDescription)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("clusters", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("descriptions", descriptions); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/services/polardb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudPolarDBDatabases() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudPolarDBDatabasesRead,
Schema: map[string]*schema.Schema{
"db_cluster_id": {
Type: schema.TypeString,
Required: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"databases": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"character_set_name": {
Type: schema.TypeString,
Computed: true,
},
"db_description": {
Type: schema.TypeString,
Computed: true,
},
"db_name": {
Type: schema.TypeString,
Computed: true,
},
"db_status": {
Type: schema.TypeString,
Computed: true,
},
"engine": {
Type: schema.TypeString,
Computed: true,
},
"accounts": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_name": {
Type: schema.TypeString,
Computed: true,
},
"account_status": {
Type: schema.TypeString,
Computed: true,
},
"privilege_status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudPolarDBDatabasesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := polardb.CreateDescribeDatabasesRequest()
request.RegionId = client.RegionId
request.DBClusterId = d.Get("db_cluster_id").(string)
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
nameRegex = r
}
raw, err := client.WithPolarDBClient(func(client *polardb.Client) (interface{}, error) {
return client.DescribeDatabases(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_polardb_databases", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*polardb.DescribeDatabasesResponse)
var ids []string
var databases []map[string]interface{}
if len(response.Databases.Database) > 0 {
for _, item := range response.Databases.Database {
if nameRegex != nil {
if !nameRegex.MatchString(item.DBName) {
continue
}
}
var nodes []map[string]interface{}
for _, node := range item.Accounts.Account {
nodeMap := map[string]interface{}{
"account_name": node.AccountName,
"account_status": node.AccountStatus,
"privilege_status": node.PrivilegeStatus,
}
nodes = append(nodes, nodeMap)
}
mapping := map[string]interface{}{
"character_set_name": item.CharacterSetName,
"db_description": item.DBDescription,
"db_name": item.DBName,
"db_status": item.DBStatus,
"engine": item.Engine,
"accounts": nodes,
}
ids = append(ids, item.DBName)
databases = append(databases, mapping)
}
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("databases", databases); err != nil {
return WrapError(err)
}
if err := d.Set("names", ids); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), databases)
}
return nil
}
package alicloud
import (
"github.com/aliyun/alibaba-cloud-sdk-go/services/polardb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudPolarDBEndpoints() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudPolarDBEndpointsRead,
Schema: map[string]*schema.Schema{
"db_cluster_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"db_endpoint_id": {
Type: schema.TypeString,
Optional: true,
},
"endpoints": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"db_endpoint_id": {
Type: schema.TypeString,
Computed: true,
},
"auto_add_new_nodes": {
Type: schema.TypeString,
Computed: true,
},
"endpoint_config": {
Type: schema.TypeString,
Computed: true,
},
"endpoint_type": {
Type: schema.TypeString,
Computed: true,
},
"nodes": {
Type: schema.TypeString,
Computed: true,
},
"read_write_mode": {
Type: schema.TypeString,
Computed: true,
},
"address_items": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"net_type": {
Type: schema.TypeString,
Computed: true,
},
"connection_string": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"ip_address": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudPolarDBEndpointsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := polardb.CreateDescribeDBClusterEndpointsRequest()
request.RegionId = client.RegionId
request.DBClusterId = d.Get("db_cluster_id").(string)
if v, ok := d.GetOk("db_endpoint_id"); ok && v.(string) != "" {
request.DBEndpointId = v.(string)
}
var dbi []polardb.DBEndpoint
raw, err := client.WithPolarDBClient(func(polardbClient *polardb.Client) (interface{}, error) {
return polardbClient.DescribeDBClusterEndpoints(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_polardb_endpoints", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*polardb.DescribeDBClusterEndpointsResponse)
for _, item := range response.Items {
dbi = append(dbi, item)
}
return polarDBClusterEndpointsDescription(d, dbi)
}
func polarDBClusterEndpointsDescription(d *schema.ResourceData, dbi []polardb.DBEndpoint) error {
var ids []string
var s []map[string]interface{}
for _, item := range dbi {
var addrs []map[string]interface{}
for _, addr := range item.AddressItems {
addrMap := map[string]interface{}{
"net_type": addr.NetType,
"connection_string": addr.ConnectionString,
"port": addr.Port,
"vpc_id": addr.VPCId,
"vswitch_id": addr.VSwitchId,
"ip_address": addr.IPAddress,
}
addrs = append(addrs, addrMap)
}
mapping := map[string]interface{}{
"db_endpoint_id": item.DBEndpointId,
"auto_add_new_nodes": item.AutoAddNewNodes,
"endpoint_config": item.EndpointConfig,
"endpoint_type": item.EndpointType,
"nodes": item.Nodes,
"read_write_mode": item.ReadWriteMode,
"address_items": addrs,
}
ids = append(ids, item.DBEndpointId)
s = append(s, mapping)
}
if err := d.Set("endpoints", s); err != nil {
return WrapError(err)
}
d.SetId(dataResourceIdHash(ids))
// create a json file in current directory and write data source to it
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/aliyun/alibaba-cloud-sdk-go/services/polardb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudPolarDBNodeClasses() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudPolarDBInstanceClassesRead,
Schema: map[string]*schema.Schema{
"pay_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{string(PostPaid), string(PrePaid)}, false),
},
"db_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"db_version": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"db_node_class": {
Type: schema.TypeString,
Optional: true,
},
"region_id": {
Type: schema.TypeString,
Optional: true,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values.
"classes": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
"supported_engines": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"available_resources": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"db_node_class": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"engine": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudPolarDBInstanceClassesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := polardb.CreateDescribeDBClusterAvailableResourcesRequest()
payType := d.Get("pay_type").(string)
if payType == string(PostPaid) {
request.PayType = "Postpaid"
} else if payType == string(PrePaid) {
request.PayType = "Prepaid"
}
dbType, dbTypeGot := d.GetOk("db_type")
dbVersion, dbVersionGot := d.GetOk("db_version")
if dbTypeGot && dbVersionGot {
request.DBType = dbType.(string)
request.DBVersion = dbVersion.(string)
}
if dbNodeClass, ok := d.GetOk("db_node_class"); ok {
request.DBNodeClass = dbNodeClass.(string)
}
if regionId, ok := d.GetOk("region_id"); ok {
request.RegionId = regionId.(string)
}
if zoneId, ok := d.GetOk("zone_id"); ok {
request.ZoneId = zoneId.(string)
}
var response = &polardb.DescribeDBClusterAvailableResourcesResponse{}
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithPolarDBClient(func(polardbClient *polardb.Client) (interface{}, error) {
return polardbClient.DescribeDBClusterAvailableResources(request)
})
if err != nil {
if IsExpectedErrors(err, []string{Throttling}) {
time.Sleep(time.Duration(5) * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response = raw.(*polardb.DescribeDBClusterAvailableResourcesResponse)
return nil
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_polardb_node_classes", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
ids := []string{}
var availableClasses []interface{}
for _, AvailableZone := range response.AvailableZones {
zondId := AvailableZone.ZoneId
ids = append(ids, zondId)
supportedEngines := make([]interface{}, 0)
for _, supportedEngine := range AvailableZone.SupportedEngines {
if len(supportedEngine.AvailableResources) == 0 {
continue
}
if dbTypeGot && !strings.Contains(strings.ToLower(supportedEngine.Engine), strings.ToLower(dbType.(string))) {
continue
}
if dbVersionGot && !strings.Contains(strings.ToLower(supportedEngine.Engine), strings.ToLower(dbVersion.(string))) {
continue
}
var dbNodeClasses []map[string]string
for _, availableResource := range supportedEngine.AvailableResources {
dbNodeClass := map[string]string{"db_node_class": availableResource.DBNodeClass}
dbNodeClasses = append(dbNodeClasses, dbNodeClass)
}
availableResources := map[string]interface{}{
"engine": supportedEngine.Engine,
"available_resources": dbNodeClasses,
}
supportedEngines = append(supportedEngines, availableResources)
ids = append(ids, supportedEngine.Engine)
}
var availableClass map[string]interface{}
if len(supportedEngines) > 0 {
availableClass = map[string]interface{}{
"zone_id": zondId,
"supported_engines": supportedEngines,
}
}
if len(availableClass) > 0 {
availableClasses = append(availableClasses, availableClass)
}
}
d.SetId(dataResourceIdHash(ids))
err = d.Set("classes", availableClasses)
if err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok {
err = writeToFile(output.(string), availableClasses)
if err != nil {
return WrapError(err)
}
}
return nil
}
package alicloud
import (
"fmt"
"sort"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/services/polardb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudPolarDBZones() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudZonesPolarDBRead,
Schema: map[string]*schema.Schema{
"multi": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"zones": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"multi_zone_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
},
}
}
func dataSourceAlicloudZonesPolarDBRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
multi := d.Get("multi").(bool)
var zoneIds []string
request := polardb.CreateDescribeRegionsRequest()
request.RegionId = client.RegionId
raw, err := client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.DescribeRegions(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_polardb_zones", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
regions, _ := raw.(*polardb.DescribeRegionsResponse)
if len(regions.Regions.Region) <= 0 {
return WrapError(fmt.Errorf("[ERROR] There is no available region for PolarDB."))
}
for _, r := range regions.Regions.Region {
for _, zone := range r.Zones.Zone {
if multi && strings.Contains(zone.ZoneId, MULTI_IZ_SYMBOL) && r.RegionId == string(client.Region) {
zoneIds = append(zoneIds, zone.ZoneId)
continue
}
if !multi && !strings.Contains(zone.ZoneId, MULTI_IZ_SYMBOL) && r.RegionId == string(client.Region) {
zoneIds = append(zoneIds, zone.ZoneId)
continue
}
}
}
if len(zoneIds) > 0 {
sort.Strings(zoneIds)
}
var s []map[string]interface{}
if !multi {
for _, zoneId := range zoneIds {
mapping := map[string]interface{}{"id": zoneId}
s = append(s, mapping)
}
} else {
for _, zoneId := range zoneIds {
mapping := map[string]interface{}{
"id": zoneId,
"multi_zone_ids": splitMultiZoneId(zoneId),
}
s = append(s, mapping)
}
}
d.SetId(dataResourceIdHash(zoneIds))
if err := d.Set("zones", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", zoneIds); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudPrivateLinkService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudPrivateLinkServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudPrivateLinkServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("PrivateLinkServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
action := "OpenPrivateLinkService"
request := map[string]interface{}{}
conn, err := meta.(*connectivity.AliyunClient).NewTeaCommonClient(connectivity.OpenPrivateLinkService)
if err != nil {
return WrapError(err)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"QPS Limit Exceeded"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
addDebug(action, response, nil)
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"OrderOpend"}) {
d.SetId("PrivateLinkServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_privatelink_service", action, AlibabaCloudSdkGoERROR)
}
d.SetId("PrivateLinkServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
package alicloud
import (
"fmt"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudPrivatelinkVpcEndpointConnections() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudPrivatelinkVpcEndpointConnectionsRead,
Schema: map[string]*schema.Schema{
"endpoint_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"endpoint_owner_id": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"service_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Connected", "Connecting", "Deleted", "Deleting", "Disconnected", "Disconnecting", "Pending", "ServiceDeleted"}, false),
},
"ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"connections": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"bandwidth": {
Type: schema.TypeInt,
Computed: true,
},
"endpoint_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudPrivatelinkVpcEndpointConnectionsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListVpcEndpointConnections"
request := make(map[string]interface{})
if v, ok := d.GetOk("endpoint_id"); ok {
request["EndpointId"] = v
}
if v, ok := d.GetOk("endpoint_owner_id"); ok {
request["EndpointOwnerId"] = v
}
request["RegionId"] = client.RegionId
request["ServiceId"] = d.Get("service_id")
if v, ok := d.GetOk("status"); ok {
request["ConnectionStatus"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var response map[string]interface{}
conn, err := client.NewPrivatelinkClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_privatelink_vpc_endpoint_connections", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Connections", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Connections", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["ServiceId"], ":", object["EndpointId"]),
"bandwidth": object["Bandwidth"],
"endpoint_id": object["EndpointId"],
"status": object["ConnectionStatus"],
}
ids = append(ids, fmt.Sprint(object["ServiceId"], ":", object["EndpointId"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("connections", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudPrivatelinkVpcEndpointServiceResources() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudPrivatelinkVpcEndpointServiceResourcesRead,
Schema: map[string]*schema.Schema{
"service_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"resources": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"resource_id": {
Type: schema.TypeString,
Computed: true,
},
"resource_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudPrivatelinkVpcEndpointServiceResourcesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListVpcEndpointServiceResources"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
request["ServiceId"] = d.Get("service_id")
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var response map[string]interface{}
conn, err := client.NewPrivatelinkClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_privatelink_vpc_endpoint_service_resources", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Resources", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Resources", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(request["ServiceId"], ":", object["ResourceId"]),
"resource_id": object["ResourceId"],
"resource_type": object["ResourceType"],
}
ids = append(ids, fmt.Sprint(request["ServiceId"], ":", object["ResourceId"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("resources", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudPrivatelinkVpcEndpointServiceUsers() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudPrivatelinkVpcEndpointServiceUsersRead,
Schema: map[string]*schema.Schema{
"service_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"user_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"users": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"user_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudPrivatelinkVpcEndpointServiceUsersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListVpcEndpointServiceUsers"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
request["ServiceId"] = d.Get("service_id")
if v, ok := d.GetOk("user_id"); ok {
request["UserId"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var response map[string]interface{}
conn, err := client.NewPrivatelinkClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_privatelink_vpc_endpoint_service_users", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Users", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Users", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(request["ServiceId"], ":", object["UserId"]),
"user_id": fmt.Sprint(formatInt(object["UserId"])),
}
ids = append(ids, fmt.Sprint(request["ServiceId"], ":", object["UserId"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("users", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudPrivatelinkVpcEndpointServices() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudPrivatelinkVpcEndpointServicesRead,
Schema: map[string]*schema.Schema{
"auto_accept_connection": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: false,
},
"service_business_status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "Normal",
ValidateFunc: validation.StringInSlice([]string{"Normal", "FinancialLocked", "SecurityLocked"}, false),
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Creating", "Deleted", "Deleting", "Pending"}, false),
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"vpc_endpoint_service_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"services": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"auto_accept_connection": {
Type: schema.TypeBool,
Computed: true,
},
"connect_bandwidth": {
Type: schema.TypeInt,
Computed: true,
},
"service_business_status": {
Type: schema.TypeString,
Computed: true,
},
"service_description": {
Type: schema.TypeString,
Computed: true,
},
"service_domain": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"service_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vpc_endpoint_service_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudPrivatelinkVpcEndpointServicesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListVpcEndpointServices"
request := make(map[string]interface{})
if v, ok := d.GetOkExists("auto_accept_connection"); ok {
request["AutoAcceptEnabled"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("service_business_status"); ok {
request["ServiceBusinessStatus"] = v
}
if v, ok := d.GetOk("status"); ok {
request["ServiceStatus"] = v
}
if v, ok := d.GetOk("vpc_endpoint_service_name"); ok {
request["ServiceName"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var vpcEndpointServiceNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
vpcEndpointServiceNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewPrivatelinkClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_privatelink_vpc_endpoint_services", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Services", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Services", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if vpcEndpointServiceNameRegex != nil {
if !vpcEndpointServiceNameRegex.MatchString(fmt.Sprint(item["ServiceName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ServiceId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"auto_accept_connection": object["AutoAcceptEnabled"],
"connect_bandwidth": formatInt(object["ConnectBandwidth"]),
"service_business_status": object["ServiceBusinessStatus"],
"service_description": object["ServiceDescription"],
"service_domain": object["ServiceDomain"],
"id": fmt.Sprint(object["ServiceId"]),
"service_id": fmt.Sprint(object["ServiceId"]),
"status": object["ServiceStatus"],
"vpc_endpoint_service_name": object["ServiceName"],
}
ids = append(ids, fmt.Sprint(object["ServiceId"]))
names = append(names, object["ServiceName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("services", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudPrivatelinkVpcEndpointZones() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudPrivatelinkVpcEndpointZonesRead,
Schema: map[string]*schema.Schema{
"endpoint_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Connected", "Connecting", "Creating", "Deleted", "Deleting", "Disconnected", "Disconnecting", "Wait"}, false),
},
"ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"zones": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"eni_id": {
Type: schema.TypeString,
Computed: true,
},
"eni_ip": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_domain": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudPrivatelinkVpcEndpointZonesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListVpcEndpointZones"
request := make(map[string]interface{})
request["EndpointId"] = d.Get("endpoint_id")
request["RegionId"] = client.RegionId
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewPrivatelinkClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_privatelink_vpc_endpoint_zones", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Zones", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Zones", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if statusOk && status.(string) != "" && status.(string) != item["ZoneStatus"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(request["EndpointId"], ":", object["ZoneId"]),
"eni_id": object["EniId"],
"eni_ip": object["EniIp"],
"status": object["ZoneStatus"],
"vswitch_id": object["VSwitchId"],
"zone_domain": object["ZoneDomain"],
"zone_id": object["ZoneId"],
}
ids = append(ids, fmt.Sprint(request["EndpointId"], ":", object["ZoneId"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("zones", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudPrivatelinkVpcEndpoints() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudPrivatelinkVpcEndpointsRead,
Schema: map[string]*schema.Schema{
"connection_status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Pending", "Connecting", "Connected", "Disconnecting", "Disconnected", "Deleting", "ServiceDeleted"}, false),
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"service_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Creating", "Deleted", "Deleting", "Inactive", "Pending"}, false),
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"vpc_endpoint_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"endpoints": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"bandwidth": {
Type: schema.TypeInt,
Computed: true,
},
"connection_status": {
Type: schema.TypeString,
Computed: true,
},
"endpoint_business_status": {
Type: schema.TypeString,
Computed: true,
},
"endpoint_description": {
Type: schema.TypeString,
Computed: true,
},
"endpoint_domain": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"endpoint_id": {
Type: schema.TypeString,
Computed: true,
},
"security_group_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"service_id": {
Type: schema.TypeString,
Computed: true,
},
"service_name": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vpc_endpoint_name": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudPrivatelinkVpcEndpointsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListVpcEndpoints"
request := make(map[string]interface{})
if v, ok := d.GetOk("connection_status"); ok {
request["ConnectionStatus"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("service_name"); ok {
request["ServiceName"] = v
}
if v, ok := d.GetOk("status"); ok {
request["EndpointStatus"] = v
}
if v, ok := d.GetOk("vpc_endpoint_name"); ok {
request["EndpointName"] = v
}
if v, ok := d.GetOk("vpc_id"); ok {
request["VpcId"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var vpcEndpointNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
vpcEndpointNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewPrivatelinkClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_privatelink_vpc_endpoints", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Endpoints", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Endpoints", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if vpcEndpointNameRegex != nil {
if !vpcEndpointNameRegex.MatchString(fmt.Sprint(item["EndpointName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["EndpointId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"bandwidth": object["Bandwidth"],
"connection_status": object["ConnectionStatus"],
"endpoint_business_status": object["EndpointBusinessStatus"],
"endpoint_description": object["EndpointDescription"],
"endpoint_domain": object["EndpointDomain"],
"id": fmt.Sprint(object["EndpointId"]),
"endpoint_id": fmt.Sprint(object["EndpointId"]),
"service_id": object["ServiceId"],
"service_name": object["ServiceName"],
"status": object["EndpointStatus"],
"vpc_endpoint_name": object["EndpointName"],
"vpc_id": object["VpcId"],
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["EndpointId"]))
names = append(names, object["EndpointName"])
s = append(s, mapping)
continue
}
privatelinkService := PrivatelinkService{client}
id := fmt.Sprint(object["EndpointId"])
getResp, err := privatelinkService.ListVpcEndpointSecurityGroups(id)
if err != nil {
return WrapError(err)
}
if v := getResp["SecurityGroups"].([]interface{}); len(v) > 0 {
mapping["security_group_ids"] = convertSecurityGroupIdToStringList(v)
}
ids = append(ids, fmt.Sprint(object["EndpointId"]))
names = append(names, object["EndpointName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("endpoints", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudPvtzEndpoints() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudPvtzEndpointsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"CHANGE_FAILED", "EXCEPTION", "FAILED", "INIT", "SUCCESS"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"endpoints": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"endpoint_name": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"ip_configs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cidr_block": {
Type: schema.TypeString,
Computed: true,
},
"ip": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"security_group_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_name": {
Type: schema.TypeString,
Computed: true,
},
"vpc_region_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudPvtzEndpointsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeResolverEndpoints"
request := make(map[string]interface{})
request["Lang"] = "en"
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var endpointNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
endpointNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_pvtz_endpoints", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Endpoints", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Endpoints", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if endpointNameRegex != nil && !endpointNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Id"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": object["CreateTime"],
"endpoint_name": object["Name"],
"id": object["Id"],
"security_group_id": object["SecurityGroupId"],
"status": object["Status"],
"vpc_id": object["VpcId"],
"vpc_name": object["VpcName"],
"vpc_region_id": object["VpcRegionId"],
}
ipConfigsSli := make([]map[string]interface{}, 0)
if ipConfigs, ok := object["IpConfigs"].([]interface{}); ok {
for _, ipConfigArgs := range ipConfigs {
ipConfigArg := ipConfigArgs.(map[string]interface{})
ipConfigsMap := make(map[string]interface{})
ipConfigsMap["zone_id"] = ipConfigArg["AzId"]
ipConfigsMap["cidr_block"] = ipConfigArg["CidrBlock"]
ipConfigsMap["ip"] = ipConfigArg["Ip"]
ipConfigsMap["vswitch_id"] = ipConfigArg["VSwitchId"]
ipConfigsSli = append(ipConfigsSli, ipConfigsMap)
}
}
mapping["ip_configs"] = ipConfigsSli
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, fmt.Sprint(mapping["endpoint_name"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("endpoints", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"strconv"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudPvtzResolverZones() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudPvtzResolverZonesRead,
Schema: map[string]*schema.Schema{
"status": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"SOLD_OUT", "NORMAL"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"zones": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"status": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudPvtzResolverZonesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeResolverAvailableZones"
request := make(map[string]interface{})
request["ResolverRegionId"] = client.RegionId
var objects []map[string]interface{}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_pvtz_resolver_zones", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.AvailableZones", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.AvailableZones", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"status": object["Status"],
"zone_id": object["AzId"],
}
s = append(s, mapping)
}
d.SetId(strconv.FormatInt(time.Now().Unix(), 16))
if err := d.Set("zones", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudPvtzRules() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudPvtzRulesRead,
Schema: map[string]*schema.Schema{
"endpoint_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"endpoint_id": {
Type: schema.TypeString,
Computed: true,
},
"forward_ips": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ip": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"endpoint_name": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"rule_id": {
Type: schema.TypeString,
Computed: true,
},
"rule_name": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"zone_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudPvtzRulesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeResolverRules"
request := make(map[string]interface{})
if v, ok := d.GetOk("endpoint_id"); ok {
request["EndpointId"] = v
}
request["Lang"] = "en"
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var ruleNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
ruleNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_pvtz_rules", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Rules", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Rules", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if ruleNameRegex != nil && !ruleNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Id"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": object["CreateTime"],
"endpoint_id": object["EndpointId"],
"endpoint_name": object["EndpointName"],
"id": fmt.Sprint(object["Id"]),
"rule_id": fmt.Sprint(object["Id"]),
"rule_name": object["Name"],
"type": object["Type"],
"zone_name": object["ZoneName"],
}
forwardConfigsSli := make([]map[string]interface{}, 0)
if forwardConfigs, ok := object["ForwardIps"].([]interface{}); ok {
for _, forwardConfigArgs := range forwardConfigs {
forwardConfigArg := forwardConfigArgs.(map[string]interface{})
forwardConfigsMap := make(map[string]interface{})
forwardConfigsMap["ip"] = forwardConfigArg["Ip"]
forwardConfigsMap["port"] = formatInt(forwardConfigArg["Port"])
forwardConfigsSli = append(forwardConfigsSli, forwardConfigsMap)
}
}
mapping["forward_ips"] = forwardConfigsSli
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("rules", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudPvtzService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudPvtzServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudPvtzServiceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("PvtzServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
var response map[string]interface{}
action := "CreateInstance"
request := map[string]interface{}{
"ProductCode": "pvtz",
"ProductType": "pvtzpost",
"SubscriptionType": "PayAsYouGo",
"Parameter.1.Code": "CommodityType",
"Parameter.1.Value": "pvtz",
}
conn, err := client.NewBssopenapiClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-14"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"NotApplicable"}) {
conn.Endpoint = String(connectivity.BssOpenAPIEndpointInternational)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, nil)
if err != nil {
if IsExpectedErrors(err, []string{"SYSTEM.SALE_VALIDATE_NO_SPECIFIC_CODE_FAILED"}) {
d.SetId("PvtzServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_pvtz_service", action, AlibabaCloudSdkGoERROR)
}
if response["Success"] != nil && !response["Success"].(bool) {
if response["Code"] != nil && response["Code"].(string) == "SYSTEM.SALE_VALIDATE_NO_SPECIFIC_CODE_FAILED" {
d.SetId("PvtzServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(fmt.Errorf("%s", response), DataDefaultErrorMsg, "alicloud_pvtz_service", action, AlibabaCloudSdkGoERROR)
}
if response["Data"] != nil {
d.SetId(fmt.Sprintf("%v", response["Data"].(map[string]interface{})["OrderId"]))
} else {
log.Printf("[ERROR] When opening pvtz service, invoking %s got an nil data. Response: %s.", action, response)
d.SetId("PvtzServiceHasBeenOpened")
}
d.Set("status", "Opened")
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudPvtzZoneRecords() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudPvtzZoneRecordsRead,
Schema: map[string]*schema.Schema{
"keyword": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"lang": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"search_mode": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"DISABLE", "ENABLE"}, false),
},
"tag": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"user_client_ip": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"zone_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
Optional: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"records": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"priority": {
Type: schema.TypeInt,
Computed: true,
},
"record_id": {
Type: schema.TypeString,
Computed: true,
},
"remark": {
Type: schema.TypeString,
Computed: true,
},
"rr": {
Type: schema.TypeString,
Computed: true,
},
"resource_record": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"ttl": {
Type: schema.TypeInt,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"value": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudPvtzZoneRecordsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeZoneRecords"
request := make(map[string]interface{})
if v, ok := d.GetOk("keyword"); ok {
request["Keyword"] = v
}
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
if v, ok := d.GetOk("search_mode"); ok {
request["SearchMode"] = v
}
if v, ok := d.GetOk("tag"); ok {
request["Tag"] = v
}
if v, ok := d.GetOk("user_client_ip"); ok {
request["UserClientIp"] = v
}
request["ZoneId"] = d.Get("zone_id")
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err := resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"System.Busy", "ServiceUnavailable", "Throttling.User"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_pvtz_zone_records", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Records.Record", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Records.Record", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["RecordId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["RecordId"], ":", request["ZoneId"]),
"priority": formatInt(object["Priority"]),
"record_id": fmt.Sprint(object["RecordId"]),
"remark": object["Remark"],
"rr": object["Rr"],
"resource_record": object["Rr"],
"status": object["Status"],
"ttl": formatInt(object["Ttl"]),
"type": object["Type"],
"value": object["Value"],
}
ids = append(ids, fmt.Sprint(object["RecordId"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("records", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudPvtzZones() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudPvtzZonesRead,
Schema: map[string]*schema.Schema{
"keyword": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"lang": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"en", "jp", "zh"}, false),
},
"query_region_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"query_vpc_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"search_mode": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"LIKE", "EXACT"}, false),
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"zones": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"bind_vpcs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"region_name": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"create_timestamp": {
Type: schema.TypeInt,
Computed: true,
},
"is_ptr": {
Type: schema.TypeBool,
Computed: true,
},
"proxy_pattern": {
Type: schema.TypeString,
Computed: true,
},
"record_count": {
Type: schema.TypeInt,
Computed: true,
},
"remark": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"slave_dns": {
Type: schema.TypeBool,
Computed: true,
},
"update_timestamp": {
Type: schema.TypeInt,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_name": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"creation_time": {
Type: schema.TypeString,
Computed: true,
Removed: "Field 'creation_time' has been removed from provider version 1.107.0",
},
"update_time": {
Type: schema.TypeString,
Computed: true,
Removed: "Field 'update_time' has been removed from provider version 1.107.0",
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudPvtzZonesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeZones"
request := make(map[string]interface{})
if v, ok := d.GetOk("keyword"); ok {
request["Keyword"] = v
}
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
if v, ok := d.GetOk("query_region_id"); ok {
request["QueryRegionId"] = v
}
if v, ok := d.GetOk("query_vpc_id"); ok {
request["QueryVpcId"] = v
}
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("search_mode"); ok {
request["SearchMode"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var zoneNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
zoneNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_pvtz_zones", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Zones.Zone", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Zones.Zone", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if zoneNameRegex != nil {
if !zoneNameRegex.MatchString(item["ZoneName"].(string)) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ZoneId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_timestamp": formatInt(object["CreateTimestamp"]),
"is_ptr": object["IsPtr"],
"proxy_pattern": object["ProxyPattern"],
"record_count": formatInt(object["RecordCount"]),
"remark": object["Remark"],
"resource_group_id": object["ResourceGroupId"],
"update_timestamp": formatInt(object["UpdateTimestamp"]),
"id": fmt.Sprint(object["ZoneId"]),
"zone_id": fmt.Sprint(object["ZoneId"]),
"zone_name": object["ZoneName"],
"name": object["ZoneName"],
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["ZoneId"]))
names = append(names, object["ZoneName"].(string))
s = append(s, mapping)
continue
}
pvtzService := PvtzService{client}
id := fmt.Sprint(object["ZoneId"])
getResp, err := pvtzService.DescribePvtzZone(id)
if err != nil {
return WrapError(err)
}
vpc := make([]map[string]interface{}, 0)
if vpcList, ok := getResp["BindVpcs"].(map[string]interface{})["Vpc"].([]interface{}); ok {
for _, v := range vpcList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"region_id": m1["RegionId"],
"region_name": m1["RegionName"],
"vpc_id": m1["VpcId"],
"vpc_name": m1["VpcName"],
}
vpc = append(vpc, temp1)
}
}
}
mapping["bind_vpcs"] = vpc
mapping["slave_dns"] = getResp["SlaveDns"]
ids = append(ids, fmt.Sprint(object["ZoneId"]))
names = append(names, object["ZoneName"].(string))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("zones", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudQuickBiUsers() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudQuickBiUsersRead,
Schema: map[string]*schema.Schema{
"keyword": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"users": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_id": {
Type: schema.TypeString,
Computed: true,
},
"account_name": {
Type: schema.TypeString,
Computed: true,
},
"admin_user": {
Type: schema.TypeBool,
Computed: true,
},
"auth_admin_user": {
Type: schema.TypeBool,
Computed: true,
},
"email": {
Type: schema.TypeString,
Computed: true,
},
"nick_name": {
Type: schema.TypeString,
Computed: true,
},
"phone": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"user_id": {
Type: schema.TypeString,
Computed: true,
},
"user_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudQuickBiUsersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "QueryUserList"
request := make(map[string]interface{})
if v, ok := d.GetOk("keyword"); ok {
request["Keyword"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNum"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewQuickbiClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2020-08-01"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_quick_bi_users", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Result.Data", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Result.Data", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["UserId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNum"] = request["PageNum"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"account_id": object["AccountId"],
"account_name": object["AccountName"],
"admin_user": object["AdminUser"],
"auth_admin_user": object["AuthAdminUser"],
"nick_name": object["NickName"],
"id": fmt.Sprint(object["UserId"]),
"user_id": fmt.Sprint(object["UserId"]),
"user_type": convertQuickBiUserUserTypeResponse(formatInt(object["UserType"])),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["UserId"])
quickbiPublicService := QuickbiPublicService{client}
getResp, err := quickbiPublicService.DescribeQuickBiUser(id)
if err != nil {
return WrapError(err)
}
mapping["email"] = getResp["Email"]
mapping["phone"] = getResp["Phone"]
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("users", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudQuotasQuotaAlarms() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudQuotasQuotaAlarmsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"product_code": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"quota_action_code": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"quota_alarm_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"quota_dimensions": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"value": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
},
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"alarms": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"alarm_id": {
Type: schema.TypeString,
Computed: true,
},
"product_code": {
Type: schema.TypeString,
Computed: true,
},
"quota_action_code": {
Type: schema.TypeString,
Computed: true,
},
"quota_alarm_name": {
Type: schema.TypeString,
Computed: true,
},
"quota_dimensions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Computed: true,
},
"value": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"threshold": {
Type: schema.TypeFloat,
Computed: true,
},
"threshold_percent": {
Type: schema.TypeFloat,
Computed: true,
},
"web_hook": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudQuotasQuotaAlarmsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListQuotaAlarms"
request := make(map[string]interface{})
request["SourceIp"] = client.SourceIp
if v, ok := d.GetOk("product_code"); ok {
request["ProductCode"] = v
}
if v, ok := d.GetOk("quota_action_code"); ok {
request["QuotaActionCode"] = v
}
if v, ok := d.GetOk("quota_alarm_name"); ok {
request["AlarmName"] = v
}
if v, ok := d.GetOk("quota_dimensions"); ok {
quotaDimensionsMaps := make([]map[string]interface{}, 0)
for _, quotaDimensions := range v.([]interface{}) {
quotaDimensionsMap := make(map[string]interface{})
quotaDimensionsArg := quotaDimensions.(map[string]interface{})
quotaDimensionsMap["Key"] = quotaDimensionsArg["key"]
quotaDimensionsMap["Value"] = quotaDimensionsArg["value"]
quotaDimensionsMaps = append(quotaDimensionsMaps, quotaDimensionsMap)
}
request["QuotaDimensions"] = quotaDimensionsMaps
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var quotaAlarmNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
quotaAlarmNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewQuotasClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-05-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_quotas_quota_alarms", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.QuotaAlarms", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.QuotaAlarms", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if quotaAlarmNameRegex != nil {
if !quotaAlarmNameRegex.MatchString(fmt.Sprint(item["AlarmName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["AlarmId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["AlarmId"]),
"alarm_id": fmt.Sprint(object["AlarmId"]),
"product_code": object["ProductCode"],
"quota_action_code": object["QuotaActionCode"],
"quota_alarm_name": object["AlarmName"],
"threshold": object["Threshold"],
"threshold_percent": object["ThresholdPercent"],
"web_hook": object["WebHook"],
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["AlarmId"]))
names = append(names, object["AlarmName"])
s = append(s, mapping)
continue
}
quotasService := QuotasService{client}
id := fmt.Sprint(object["AlarmId"])
getResp, err := quotasService.DescribeQuotasQuotaAlarm(id)
if err != nil {
return WrapError(err)
}
quotaDimensionList := make([]map[string]interface{}, 0)
if quotaDimension, ok := getResp["QuotaDimension"]; ok {
for k, v := range quotaDimension.(map[string]interface{}) {
quotaDimensionMap := make(map[string]interface{})
quotaDimensionMap["key"] = k
quotaDimensionMap["value"] = v
quotaDimensionList = append(quotaDimensionList, quotaDimensionMap)
}
}
mapping["quota_dimensions"] = quotaDimensionList
ids = append(ids, fmt.Sprint(object["AlarmId"]))
names = append(names, object["AlarmName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("alarms", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudQuotasQuotaApplications() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudQuotasQuotaApplicationsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"dimensions": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"value": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
},
},
"key_word": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"product_code": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"quota_action_code": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"quota_category": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"CommonQuota", "FlowControl"}, false),
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Agree", "Disagree", "Process"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"applications": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"application_id": {
Type: schema.TypeString,
Computed: true,
},
"approve_value": {
Type: schema.TypeString,
Computed: true,
},
"audit_reason": {
Type: schema.TypeString,
Computed: true,
},
"desire_value": {
Type: schema.TypeFloat,
Computed: true,
},
"dimensions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Computed: true,
},
"value": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"effective_time": {
Type: schema.TypeString,
Computed: true,
},
"expire_time": {
Type: schema.TypeString,
Computed: true,
},
"notice_type": {
Type: schema.TypeInt,
Computed: true,
},
"product_code": {
Type: schema.TypeString,
Computed: true,
},
"quota_action_code": {
Type: schema.TypeString,
Computed: true,
},
"quota_description": {
Type: schema.TypeString,
Computed: true,
},
"quota_name": {
Type: schema.TypeString,
Computed: true,
},
"quota_unit": {
Type: schema.TypeString,
Computed: true,
},
"reason": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudQuotasQuotaApplicationsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListQuotaApplications"
request := make(map[string]interface{})
request["SourceIp"] = client.SourceIp
if v, ok := d.GetOk("dimensions"); ok {
dimensionsMaps := make([]map[string]interface{}, 0)
for _, dimensions := range v.([]interface{}) {
dimensionsMap := make(map[string]interface{})
dimensionsArg := dimensions.(map[string]interface{})
dimensionsMap["Key"] = dimensionsArg["key"]
dimensionsMap["Value"] = dimensionsArg["value"]
dimensionsMaps = append(dimensionsMaps, dimensionsMap)
}
request["Dimensions"] = dimensionsMaps
}
if v, ok := d.GetOk("key_word"); ok {
request["KeyWord"] = v
}
request["ProductCode"] = d.Get("product_code")
if v, ok := d.GetOk("quota_action_code"); ok {
request["QuotaActionCode"] = v
}
if v, ok := d.GetOk("quota_category"); ok {
request["QuotaCategory"] = v
}
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewQuotasClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-05-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_quotas_quota_applications", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.QuotaApplications", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.QuotaApplications", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ApplicationId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["ApplicationId"]),
"application_id": fmt.Sprint(object["ApplicationId"]),
"approve_value": object["ApproveValue"],
"audit_reason": object["AuditReason"],
"desire_value": object["DesireValue"],
"effective_time": object["EffectiveTime"],
"expire_time": object["ExpireTime"],
"notice_type": formatInt(object["NoticeType"]),
"product_code": object["ProductCode"],
"quota_action_code": object["QuotaActionCode"],
"quota_description": object["QuotaDescription"],
"quota_name": object["QuotaName"],
"quota_unit": object["QuotaUnit"],
"reason": object["Reason"],
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["ApplicationId"]))
s = append(s, mapping)
continue
}
quotasService := QuotasService{client}
id := fmt.Sprint(object["ApplicationId"])
getResp, err := quotasService.DescribeQuotasQuotaApplication(id)
if err != nil {
return WrapError(err)
}
if statusOk && status != "" && status != getResp["Status"].(string) {
continue
}
dimensionList := make([]map[string]interface{}, 0)
if dimension, ok := getResp["Dimension"]; ok {
for k, v := range dimension.(map[string]interface{}) {
dimensionMap := make(map[string]interface{})
dimensionMap["key"] = k
dimensionMap["value"] = v
dimensionList = append(dimensionList, dimensionMap)
}
}
mapping["dimensions"] = dimensionList
mapping["status"] = getResp["Status"]
ids = append(ids, fmt.Sprint(object["ApplicationId"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("applications", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudQuotasQuotas() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudQuotasQuotasRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"dimensions": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"value": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
},
},
"group_code": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"key_word": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"product_code": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"quota_action_code": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"quota_category": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"CommonQuota", "FlowControl"}, false),
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"sort_field": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"TIME", "TOTAL", "RESERVED"}, false),
},
"sort_order": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Ascending", "Descending"}, false),
},
"ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"quotas": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"adjustable": {
Type: schema.TypeBool,
Computed: true,
},
"applicable_range": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"applicable_type": {
Type: schema.TypeString,
Computed: true,
},
"consumable": {
Type: schema.TypeBool,
Computed: true,
},
"quota_action_code": {
Type: schema.TypeString,
Computed: true,
},
"quota_description": {
Type: schema.TypeString,
Computed: true,
},
"quota_name": {
Type: schema.TypeString,
Computed: true,
},
"quota_type": {
Type: schema.TypeString,
Computed: true,
},
"quota_unit": {
Type: schema.TypeString,
Computed: true,
},
"total_quota": {
Type: schema.TypeFloat,
Computed: true,
},
"total_usage": {
Type: schema.TypeFloat,
Computed: true,
},
"unadjustable_detail": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudQuotasQuotasRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListProductQuotas"
request := make(map[string]interface{})
request["SourceIp"] = client.SourceIp
if v, ok := d.GetOk("dimensions"); ok {
dimensionsMaps := make([]map[string]interface{}, 0)
for _, dimensions := range v.([]interface{}) {
dimensionsMap := make(map[string]interface{})
dimensionsArg := dimensions.(map[string]interface{})
dimensionsMap["Key"] = dimensionsArg["key"]
dimensionsMap["Value"] = dimensionsArg["value"]
dimensionsMaps = append(dimensionsMaps, dimensionsMap)
}
request["Dimensions"] = dimensionsMaps
}
if v, ok := d.GetOk("group_code"); ok {
request["GroupCode"] = v
}
if v, ok := d.GetOk("key_word"); ok {
request["KeyWord"] = v
}
request["ProductCode"] = d.Get("product_code")
if v, ok := d.GetOk("quota_action_code"); ok {
request["QuotaActionCode"] = v
}
if v, ok := d.GetOk("quota_category"); ok {
request["QuotaCategory"] = v
}
if v, ok := d.GetOk("sort_field"); ok {
request["SortField"] = v
}
if v, ok := d.GetOk("sort_order"); ok {
request["SortOrder"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var quotaNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
quotaNameRegex = r
}
var response map[string]interface{}
conn, err := client.NewQuotasClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-05-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_quotas_quotas", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Quotas", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Quotas", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if quotaNameRegex != nil {
if !quotaNameRegex.MatchString(fmt.Sprint(item["QuotaName"])) {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["ProductCode"], ":", object["QuotaActionCode"]),
"adjustable": object["Adjustable"],
"applicable_range": object["ApplicableRange"],
"applicable_type": object["ApplicableType"],
"consumable": object["Consumable"],
"quota_action_code": object["QuotaActionCode"],
"quota_description": object["QuotaDescription"],
"quota_name": object["QuotaName"],
"quota_type": object["QuotaType"],
"quota_unit": object["QuotaUnit"],
"total_quota": object["TotalQuota"],
"total_usage": object["TotalUsage"],
"unadjustable_detail": object["UnadjustableDetail"],
}
ids = append(ids, fmt.Sprint(object["ProductCode"], ":", object["QuotaActionCode"]))
names = append(names, object["QuotaName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("quotas", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"github.com/aliyun/alibaba-cloud-sdk-go/services/ram"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudRamAccountAlias() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudRamAccountAliasRead,
Schema: map[string]*schema.Schema{
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"account_alias": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudRamAccountAliasRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ram.CreateGetAccountAliasRequest()
request.RegionId = client.RegionId
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.GetAccountAlias(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ram_account_alias", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ram.GetAccountAliasResponse)
d.SetId(response.AccountAlias)
d.Set("account_alias", response.AccountAlias)
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
s := map[string]interface{}{"account_alias": response.AccountAlias}
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ram"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudRamGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudRamGroupsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"user_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(0, 64),
},
"policy_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(0, 128),
},
"policy_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
// must be ram.System, ram.Custom
ValidateFunc: validation.StringInSlice([]string{"System", "Custom"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
// Computed values
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Computed: true,
},
"comments": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudRamGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
allGroups := []interface{}{}
allGroupsMap := make(map[string]interface{})
userFilterGroupsMap := make(map[string]interface{})
policyFilterGroupsMap := make(map[string]interface{})
dataMap := []map[string]interface{}{}
userName, userNameOk := d.GetOk("user_name")
policyName, policyNameOk := d.GetOk("policy_name")
policyType, policyTypeOk := d.GetOk("policy_type")
nameRegex, nameRegexOk := d.GetOk("name_regex")
if policyTypeOk && !policyNameOk {
return WrapError(Error("You must set 'policy_name' at one time when you set 'policy_type'."))
}
// groups filtered by name_regex
request := ram.CreateListGroupsRequest()
request.RegionId = client.RegionId
request.MaxItems = requests.NewInteger(1000)
for {
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.ListGroups(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ram_groups", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ram.ListGroupsResponse)
for _, v := range response.Groups.Group {
if nameRegexOk {
r, err := regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
if !r.MatchString(v.GroupName) {
continue
}
}
allGroupsMap[v.GroupName] = v
}
if !response.IsTruncated {
break
}
request.Marker = response.Marker
}
// groups for user
if userNameOk {
request := ram.CreateListGroupsForUserRequest()
request.UserName = userName.(string)
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.ListGroupsForUser(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ram_groups", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ram.ListGroupsForUserResponse)
for _, v := range response.Groups.Group {
userFilterGroupsMap[v.GroupName] = v
}
dataMap = append(dataMap, userFilterGroupsMap)
}
// groups which attach with this policy
if policyNameOk {
pType := "System"
if policyTypeOk {
pType = policyType.(string)
}
request := ram.CreateListEntitiesForPolicyRequest()
request.PolicyType = pType
request.PolicyName = policyName.(string)
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.ListEntitiesForPolicy(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ram_groups", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ram.ListEntitiesForPolicyResponse)
for _, v := range response.Groups.Group {
policyFilterGroupsMap[v.GroupName] = v
}
dataMap = append(dataMap, policyFilterGroupsMap)
}
// GetIntersection of each map
allGroups = ramService.GetIntersection(dataMap, allGroupsMap)
return ramGroupsDescriptionAttributes(d, allGroups)
}
func ramGroupsDescriptionAttributes(d *schema.ResourceData, groups []interface{}) error {
var ids []string
var s []map[string]interface{}
for _, v := range groups {
group := v.(ram.GroupInListGroups)
mapping := map[string]interface{}{
"name": group.GroupName,
"comments": group.Comments,
}
ids = append(ids, v.(ram.GroupInListGroups).GroupName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if err := d.Set("names", ids); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudRamPolicies() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudRamPoliciesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"System", "Custom"}, false),
},
"group_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"user_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(0, 64),
},
"role_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(0, 64),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"policies": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"attachment_count": {
Type: schema.TypeInt,
Computed: true,
},
"default_version": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"policy_document": {
Type: schema.TypeString,
Computed: true,
},
"document": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"policy_name": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"update_date": {
Type: schema.TypeString,
Computed: true,
},
"version_id": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"create_date": {
Type: schema.TypeString,
Computed: true,
},
"user_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
},
}
}
func dataSourceAlicloudRamPoliciesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListPolicies"
request := make(map[string]interface{})
request["MaxItems"] = PageSizeLarge
var objects []map[string]interface{}
userFilterPoliciesMap := make(map[string]interface{})
groupFilterPoliciesMap := make(map[string]interface{})
roleFilterPoliciesMap := make(map[string]interface{})
dataMap := []map[string]interface{}{}
userName, userNameOk := d.GetOk("user_name")
groupName, groupNameOk := d.GetOk("group_name")
roleName, roleNameOk := d.GetOk("role_name")
policyType, policyTypeOk := d.GetOk("type")
var policyNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
policyNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewRamClient()
if err != nil {
return WrapError(err)
}
// policies for user
if userNameOk {
userAction := "ListPoliciesForUser"
userRequest := map[string]interface{}{
"UserName": userName,
}
response, err = conn.DoRequest(StringPointer(userAction), nil, StringPointer("POST"), StringPointer("2015-05-01"), StringPointer("AK"), nil, userRequest, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ram_policies")
}
userResp, err := jsonpath.Get("$.Policies.Policy", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Policies.Policy", response)
}
for _, v := range userResp.([]interface{}) {
userFilterPoliciesMap[v.(map[string]interface{})["PolicyType"].(string)+v.(map[string]interface{})["PolicyName"].(string)] = v
}
dataMap = append(dataMap, userFilterPoliciesMap)
}
// policies for group
if groupNameOk {
groupAction := "ListPoliciesForGroup"
groupRequest := map[string]interface{}{
"GroupName": groupName,
}
response, err = conn.DoRequest(StringPointer(groupAction), nil, StringPointer("POST"), StringPointer("2015-05-01"), StringPointer("AK"), nil, groupRequest, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ram_policies")
}
groupResp, err := jsonpath.Get("$.Policies.Policy", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Policies.Policy", response)
}
for _, v := range groupResp.([]interface{}) {
groupFilterPoliciesMap[v.(map[string]interface{})["PolicyType"].(string)+v.(map[string]interface{})["PolicyName"].(string)] = v
}
dataMap = append(dataMap, groupFilterPoliciesMap)
}
// policies for role
if roleNameOk {
roleAction := "ListPoliciesForRole"
roleRequest := map[string]interface{}{
"RoleName": roleName,
}
response, err = conn.DoRequest(StringPointer(roleAction), nil, StringPointer("POST"), StringPointer("2015-05-01"), StringPointer("AK"), nil, roleRequest, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ram_policies")
}
roleResp, err := jsonpath.Get("$.Policies.Policy", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Policies.Policy", response)
}
for _, v := range roleResp.([]interface{}) {
roleFilterPoliciesMap[v.(map[string]interface{})["PolicyType"].(string)+v.(map[string]interface{})["PolicyName"].(string)] = v
}
dataMap = append(dataMap, roleFilterPoliciesMap)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-05-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ram_policies", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Policies.Policy", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Policies.Policy", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if policyNameRegex != nil {
if !policyNameRegex.MatchString(fmt.Sprint(item["PolicyName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["PolicyName"])]; !ok {
continue
}
}
if policyTypeOk && policyType.(string) != item["PolicyType"] {
continue
}
if len(dataMap) > 0 {
res := false
for _, v := range dataMap {
if _, ok := v[item["PolicyType"].(string)+item["PolicyName"].(string)]; ok {
res = true
break
}
}
if !res {
continue
}
}
objects = append(objects, item)
}
if marker, ok := response["Marker"].(string); ok && marker != "" {
request["Marker"] = marker
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"attachment_count": formatInt(object["AttachmentCount"]),
"default_version": object["DefaultVersion"],
"description": object["Description"],
"id": fmt.Sprint(object["PolicyName"]),
"policy_name": fmt.Sprint(object["PolicyName"]),
"name": object["PolicyName"],
"update_date": object["UpdateDate"],
"type": object["PolicyType"],
"create_date": object["CreateDate"],
"user_name": object["UserName"],
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["PolicyName"]))
names = append(names, object["PolicyName"])
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["PolicyName"])
action := "GetPolicy"
request := map[string]interface{}{
"PolicyName": id,
"PolicyType": object["PolicyType"],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-05-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapError(err)
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
getResp := v.(map[string]interface{})
mapping["policy_document"] = getResp["DefaultPolicyVersion"].(map[string]interface{})["PolicyDocument"]
mapping["document"] = getResp["DefaultPolicyVersion"].(map[string]interface{})["PolicyDocument"]
mapping["version_id"] = getResp["DefaultPolicyVersion"].(map[string]interface{})["VersionId"]
ids = append(ids, fmt.Sprint(object["PolicyName"]))
names = append(names, object["PolicyName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("policies", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ram"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudRamRoles() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudRamRolesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"policy_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(0, 128),
},
"policy_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"System", "Custom"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
// Computed values
"roles": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"arn": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"assume_role_policy_document": {
Type: schema.TypeString,
Computed: true,
},
"document": {
Type: schema.TypeString,
Computed: true,
},
"create_date": {
Type: schema.TypeString,
Computed: true,
},
"update_date": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudRamRolesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
allRoles := []interface{}{}
allRolesMap := make(map[string]interface{})
dataMap := []interface{}{}
policyName, policyNameOk := d.GetOk("policy_name")
policyType, policyTypeOk := d.GetOk("policy_type")
nameRegex, nameRegexOk := d.GetOk("name_regex")
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
// all roles
request := ram.CreateListRolesRequest()
request.RegionId = client.RegionId
request.MaxItems = requests.NewInteger(1000)
for {
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.ListRoles(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ram_roles", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ram.ListRolesResponse)
for _, v := range response.Roles.Role {
if nameRegexOk {
r, err := regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
if !r.MatchString(v.RoleName) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[v.RoleId]; !ok {
continue
}
}
allRolesMap[v.RoleName] = v
allRoles = append(allRoles, v)
}
if !response.IsTruncated {
break
}
request.Marker = response.Marker
}
// roles which attach with this policy
if policyNameOk {
pType := "System"
if policyTypeOk {
pType = policyType.(string)
}
request := ram.CreateListEntitiesForPolicyRequest()
request.PolicyType = pType
request.PolicyName = policyName.(string)
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.ListEntitiesForPolicy(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ram_roles", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ram.ListEntitiesForPolicyResponse)
for _, v := range response.Roles.Role {
role, ok := allRolesMap[v.RoleName]
if ok {
dataMap = append(dataMap, role)
}
}
allRoles = dataMap
}
return ramRolesDescriptionAttributes(d, meta, allRoles)
}
func ramRolesDescriptionAttributes(d *schema.ResourceData, meta interface{}, roles []interface{}) error {
client := meta.(*connectivity.AliyunClient)
var ids []string
var names []string
var s []map[string]interface{}
for _, v := range roles {
role := v.(ram.RoleInListRoles)
request := ram.CreateGetRoleRequest()
request.RoleName = role.RoleName
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.GetRole(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist"}) {
continue
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ram_roles", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ram.GetRoleResponse)
mapping := map[string]interface{}{
"id": role.RoleId,
"name": role.RoleName,
"arn": role.Arn,
"description": response.Role.Description,
"create_date": role.CreateDate,
"update_date": role.UpdateDate,
"assume_role_policy_document": response.Role.AssumeRolePolicyDocument,
"document": response.Role.AssumeRolePolicyDocument,
}
ids = append(ids, role.RoleId)
names = append(names, role.RoleName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("roles", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudRamSamlProviders() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudRamSamlProvidersRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"providers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"arn": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"encodedsaml_metadata_document": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"saml_provider_name": {
Type: schema.TypeString,
Computed: true,
},
"update_date": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudRamSamlProvidersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListSAMLProviders"
request := make(map[string]interface{})
request["MaxItems"] = PageSizeLarge
var objects []map[string]interface{}
var sAMLProviderNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
sAMLProviderNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewImsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ram_saml_providers", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.SAMLProviders.SAMLProvider", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.SAMLProviders.SAMLProvider", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if sAMLProviderNameRegex != nil {
if !sAMLProviderNameRegex.MatchString(fmt.Sprint(item["SAMLProviderName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["SAMLProviderName"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if marker, ok := response["Marker"].(string); ok && marker != "" {
request["Marker"] = marker
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"arn": object["Arn"],
"description": object["Description"],
"id": fmt.Sprint(object["SAMLProviderName"]),
"saml_provider_name": fmt.Sprint(object["SAMLProviderName"]),
"update_date": object["UpdateDate"],
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["SAMLProviderName"]))
names = append(names, object["SAMLProviderName"])
s = append(s, mapping)
continue
}
imsService := ImsService{client}
id := fmt.Sprint(object["SAMLProviderName"])
getResp, err := imsService.DescribeRamSamlProvider(id)
if err != nil {
return WrapError(err)
}
mapping["encodedsaml_metadata_document"] = getResp["EncodedSAMLMetadataDocument"]
ids = append(ids, fmt.Sprint(object["SAMLProviderName"]))
names = append(names, object["SAMLProviderName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("providers", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"log"
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ram"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudRamUsers() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudRamUsersRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"group_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"policy_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(0, 128),
},
"policy_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"System", "Custom"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
// Computed values
"users": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"create_date": {
Type: schema.TypeString,
Computed: true,
},
"last_login_date": {
Removed: "Field 'last_login_date' has been removed from provider version 1.79.0.",
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudRamUsersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
var allUsers []interface{}
allUsersMap := make(map[string]interface{})
groupFilterUsersMap := make(map[string]interface{})
policyFilterUsersMap := make(map[string]interface{})
var dataMap []map[string]interface{}
groupName, groupNameOk := d.GetOk("group_name")
policyName, policyNameOk := d.GetOk("policy_name")
policyType, policyTypeOk := d.GetOk("policy_type")
nameRegex, nameRegexOk := d.GetOk("name_regex")
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
if policyTypeOk && !policyNameOk {
return WrapError(Error("You must set 'policy_name' at one time when you set 'policy_type'."))
}
// all users
request := ram.CreateListUsersRequest()
request.RegionId = client.RegionId
request.MaxItems = requests.NewInteger(1000)
for {
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.ListUsers(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ram_users", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ram.ListUsersResponse)
for _, v := range response.Users.User {
if nameRegexOk {
r, err := regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
if !r.MatchString(v.UserName) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[v.UserId]; !ok {
continue
}
}
allUsersMap[v.UserName] = v
}
if !response.IsTruncated {
break
}
request.Marker = response.Marker
}
// users for group
if groupNameOk {
request := ram.CreateListUsersForGroupRequest()
request.GroupName = groupName.(string)
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.ListUsersForGroup(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ram_users", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ram.ListUsersForGroupResponse)
for _, v := range response.Users.User {
groupFilterUsersMap[v.UserName] = v
}
dataMap = append(dataMap, groupFilterUsersMap)
}
// users which attach with this policy
if policyNameOk {
pType := "System"
if policyTypeOk {
pType = policyType.(string)
}
request := ram.CreateListEntitiesForPolicyRequest()
request.PolicyName = policyName.(string)
request.PolicyType = pType
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.ListEntitiesForPolicy(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ram_users", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ram.ListEntitiesForPolicyResponse)
for _, v := range response.Users.User {
policyFilterUsersMap[v.UserName] = v
}
dataMap = append(dataMap, policyFilterUsersMap)
}
// GetIntersection of each map
allUsers = ramService.GetIntersection(dataMap, allUsersMap)
return ramUsersDescriptionAttributes(d, allUsers)
}
func ramUsersDescriptionAttributes(d *schema.ResourceData, users []interface{}) error {
var ids []string
var names []string
var s []map[string]interface{}
for _, v := range users {
user, ok := v.(ram.UserInListUsers)
if !ok {
return WrapError(Error("wrong interface convince"))
}
mapping := map[string]interface{}{
"id": user.UserId,
"name": user.UserName,
"create_date": user.CreateDate,
}
log.Printf("[DEBUG] alicloud_ram_users - adding user: %v", mapping)
ids = append(ids, user.UserId)
names = append(names, user.UserName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("users", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudRdcOrganizations() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudRdcOrganizationsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"real_pk": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"organizations": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"organization_id": {
Type: schema.TypeString,
Computed: true,
},
"organization_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudRdcOrganizationsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListUserOrganization"
request := make(map[string]interface{})
if v, ok := d.GetOk("real_pk"); ok {
request["RealPk"] = v
}
var objects []map[string]interface{}
var organizationNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
organizationNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewDevopsrdcClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-03"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_rdc_organizations", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Object", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Object", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if organizationNameRegex != nil && !organizationNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Id"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["Id"]),
"organization_id": fmt.Sprint(object["Id"]),
"organization_name": object["Name"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("organizations", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudRdsAccounts() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudRdsAccountsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"db_instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "Unavailable"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"accounts": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"account_name": {
Type: schema.TypeString,
Computed: true,
},
"account_type": {
Type: schema.TypeString,
Computed: true,
},
"database_privileges": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_privilege": {
Type: schema.TypeString,
Computed: true,
},
"account_privilege_detail": {
Type: schema.TypeString,
Computed: true,
},
"db_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"priv_exceeded": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudRdsAccountsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeAccounts"
request := make(map[string]interface{})
request["SourceIp"] = client.SourceIp
request["DBInstanceId"] = d.Get("db_instance_id")
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var accountNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
accountNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_rds_accounts", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Accounts.DBInstanceAccount", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Accounts.DBInstanceAccount", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if accountNameRegex != nil {
if !accountNameRegex.MatchString(fmt.Sprint(item["AccountName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["AccountName"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["AccountStatus"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"account_description": object["AccountDescription"],
"id": fmt.Sprint(object["AccountName"]),
"account_name": fmt.Sprint(object["AccountName"]),
"account_type": object["AccountType"],
"priv_exceeded": object["PrivExceeded"],
"status": object["AccountStatus"],
}
databasePrivilege := make([]map[string]interface{}, 0)
if databasePrivilegeList, ok := object["DatabasePrivileges"].(map[string]interface{})["DatabasePrivilege"].([]interface{}); ok {
for _, v := range databasePrivilegeList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"account_privilege": m1["AccountPrivilege"],
"account_privilege_detail": m1["AccountPrivilegeDetail"],
"db_name": m1["DBName"],
}
databasePrivilege = append(databasePrivilege, temp1)
}
}
}
mapping["database_privileges"] = databasePrivilege
ids = append(ids, fmt.Sprint(object["AccountName"]))
names = append(names, object["AccountName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("accounts", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudRdsBackups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudRdsBackupsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"backup_mode": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Automated", "Manual"}, false),
},
"db_instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"end_time": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"start_time": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"backup_status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Success", "Failed"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"backups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"backup_download_url": {
Type: schema.TypeString,
Computed: true,
},
"backup_end_time": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"backup_id": {
Type: schema.TypeString,
Computed: true,
},
"backup_initiator": {
Type: schema.TypeString,
Computed: true,
},
"backup_intranet_download_url": {
Type: schema.TypeString,
Computed: true,
},
"backup_method": {
Type: schema.TypeString,
Computed: true,
},
"backup_mode": {
Type: schema.TypeString,
Computed: true,
},
"backup_size": {
Type: schema.TypeString,
Computed: true,
},
"backup_start_time": {
Type: schema.TypeString,
Computed: true,
},
"backup_type": {
Type: schema.TypeString,
Computed: true,
},
"consistent_time": {
Type: schema.TypeString,
Computed: true,
},
"copy_only_backup": {
Type: schema.TypeString,
Computed: true,
},
"db_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"encryption": {
Type: schema.TypeString,
Computed: true,
},
"host_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"is_avail": {
Type: schema.TypeInt,
Computed: true,
},
"meta_status": {
Type: schema.TypeString,
Computed: true,
},
"backup_status": {
Type: schema.TypeString,
Computed: true,
},
"storage_class": {
Type: schema.TypeString,
Computed: true,
},
"store_status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudRdsBackupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeBackups"
request := make(map[string]interface{})
request["SourceIp"] = client.SourceIp
if v, ok := d.GetOk("backup_mode"); ok {
request["BackupMode"] = v
}
request["DBInstanceId"] = d.Get("db_instance_id")
if v, ok := d.GetOk("end_time"); ok {
request["EndTime"] = v
}
if v, ok := d.GetOk("start_time"); ok {
request["StartTime"] = v
}
if v, ok := d.GetOk("backup_status"); ok {
request["BackupStatus"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_rds_backups", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Items.Backup", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Items.Backup", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DBInstanceId"], ":", item["BackupId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"backup_download_url": object["BackupDownloadURL"],
"backup_end_time": object["BackupEndTime"],
"id": fmt.Sprint(object["DBInstanceId"], ":", object["BackupId"]),
"backup_id": fmt.Sprint(object["BackupId"]),
"backup_initiator": object["BackupInitiator"],
"backup_intranet_download_url": object["BackupIntranetDownloadURL"],
"backup_method": object["BackupMethod"],
"backup_mode": object["BackupMode"],
"backup_size": fmt.Sprint(object["BackupSize"]),
"backup_start_time": object["BackupStartTime"],
"backup_type": object["BackupType"],
"consistent_time": fmt.Sprint(object["ConsistentTime"]),
"copy_only_backup": object["CopyOnlyBackup"],
"db_instance_id": object["DBInstanceId"],
"encryption": object["Encryption"],
"host_instance_id": object["HostInstanceID"],
"is_avail": formatInt(object["IsAvail"]),
"meta_status": object["MetaStatus"],
"backup_status": object["BackupStatus"],
"storage_class": object["StorageClass"],
"store_status": object["StoreStatus"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("backups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudRdsParameterGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudRdsParameterGroupsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"engine": {
Type: schema.TypeString,
Computed: true,
},
"engine_version": {
Type: schema.TypeString,
Computed: true,
},
"force_restart": {
Type: schema.TypeInt,
Computed: true,
},
"param_counts": {
Type: schema.TypeInt,
Computed: true,
},
"param_detail": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"param_name": {
Type: schema.TypeString,
Computed: true,
},
"param_value": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"parameter_group_desc": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"parameter_group_id": {
Type: schema.TypeString,
Computed: true,
},
"parameter_group_name": {
Type: schema.TypeString,
Computed: true,
},
"parameter_group_type": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudRdsParameterGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeParameterGroups"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
var objects []map[string]interface{}
var parameterGroupNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
parameterGroupNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_rds_parameter_groups", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.ParameterGroups.ParameterGroup", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.ParameterGroups.ParameterGroup", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if parameterGroupNameRegex != nil {
if !parameterGroupNameRegex.MatchString(fmt.Sprint(item["ParameterGroupName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ParameterGroupId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"engine": object["Engine"],
"engine_version": object["EngineVersion"],
"force_restart": formatInt(object["ForceRestart"]),
"param_counts": formatInt(object["ParamCounts"]),
"parameter_group_desc": object["ParameterGroupDesc"],
"id": fmt.Sprint(object["ParameterGroupId"]),
"parameter_group_id": fmt.Sprint(object["ParameterGroupId"]),
"parameter_group_name": object["ParameterGroupName"],
"parameter_group_type": formatInt(object["ParameterGroupType"]),
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["ParameterGroupId"]))
names = append(names, object["ParameterGroupName"])
s = append(s, mapping)
continue
}
rdsService := RdsService{client}
id := fmt.Sprint(object["ParameterGroupId"])
getResp, err := rdsService.DescribeRdsParameterGroup(id)
if err != nil {
return WrapError(err)
}
if v, ok := getResp["ParamDetail"].(map[string]interface{})["ParameterDetail"].([]interface{}); ok {
parameterDetail := make([]map[string]interface{}, 0)
for _, val := range v {
item := val.(map[string]interface{})
parameterDetail = append(parameterDetail, map[string]interface{}{
"param_name": item["ParamName"],
"param_value": item["ParamValue"],
})
}
mapping["param_detail"] = parameterDetail
}
ids = append(ids, fmt.Sprint(object["ParameterGroupId"]))
names = append(names, object["ParameterGroupName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudRegions() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudRegionsRead,
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"current": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
//Computed value
"regions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"local_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudRegionsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ecs.CreateDescribeRegionsRequest()
request.RegionId = client.RegionId
currentRegion := client.RegionId
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeRegions(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_regions", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
resp, _ := raw.(*ecs.DescribeRegionsResponse)
if resp == nil || len(resp.Regions.Region) == 0 {
return fmt.Errorf("no matching regions found")
}
name, nameOk := d.GetOk("name")
current := false
if v, exist := d.GetOk("current"); exist {
current = v.(bool)
}
var filterRegions []ecs.Region
for _, region := range resp.Regions.Region {
if current {
if nameOk && name.(string) != currentRegion {
return fmt.Errorf("name doesn't match current region: %#v, please input again.", currentRegion)
}
if region.RegionId == currentRegion {
filterRegions = append(filterRegions, region)
break
}
continue
}
if nameOk {
if name.(string) == region.RegionId {
filterRegions = append(filterRegions, region)
break
}
continue
}
filterRegions = append(filterRegions, region)
}
if len(filterRegions) < 1 {
return fmt.Errorf("Your query region returned no results. Please change your search criteria and try again.")
}
return regionsDescriptionAttributes(d, filterRegions)
}
func regionsDescriptionAttributes(d *schema.ResourceData, regions []ecs.Region) error {
var ids []string
var s []map[string]interface{}
for _, region := range regions {
mapping := map[string]interface{}{
"id": region.RegionId,
"region_id": region.RegionId,
"local_name": region.LocalName,
}
log.Printf("[DEBUG] alicloud_regions - adding region mapping: %v", mapping)
ids = append(ids, string(region.RegionId))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("regions", s); err != nil {
return err
}
if err := d.Set("ids", ids); err != nil {
return err
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudResourceManagerAccounts() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudResourceManagerAccountsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"CreateCancelled", "CreateExpired", "CreateFailed", "CreateSuccess", "CreateVerifying", "InviteSuccess", "PromoteCancelled", "PromoteExpired", "PromoteFailed", "PromoteSuccess", "PromoteVerifying"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"accounts": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"account_id": {
Type: schema.TypeString,
Computed: true,
},
"account_name": {
Type: schema.TypeString,
Computed: true,
},
"display_name": {
Type: schema.TypeString,
Computed: true,
},
"folder_id": {
Type: schema.TypeString,
Computed: true,
},
"join_method": {
Type: schema.TypeString,
Computed: true,
},
"join_time": {
Type: schema.TypeString,
Computed: true,
},
"modify_time": {
Type: schema.TypeString,
Computed: true,
},
"payer_account_id": {
Type: schema.TypeString,
Computed: true,
},
"resource_directory_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudResourceManagerAccountsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListAccounts"
request := make(map[string]interface{})
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_resource_manager_accounts", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Accounts.Account", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Accounts.Account", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["AccountId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["AccountId"]),
"account_id": fmt.Sprint(object["AccountId"]),
"display_name": object["DisplayName"],
"folder_id": object["FolderId"],
"join_method": object["JoinMethod"],
"join_time": object["JoinTime"],
"modify_time": object["ModifyTime"],
"resource_directory_id": object["ResourceDirectoryId"],
"status": object["Status"],
"type": object["Type"],
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["AccountId"]))
s = append(s, mapping)
continue
}
resourcemanagerService := ResourcemanagerService{client}
id := fmt.Sprint(object["AccountId"])
getResp, err := resourcemanagerService.DescribeResourceManagerAccount(id)
if err != nil {
return WrapError(err)
}
mapping["account_name"] = getResp["AccountName"]
getResp1, err := resourcemanagerService.GetPayerForAccount(id)
if err != nil {
return WrapError(err)
}
mapping["payer_account_id"] = getResp1["PayerAccountId"]
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("accounts", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudResourceManagerControlPolicies() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudResourceManagerControlPoliciesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"language": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"policy_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"System", "Custom"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"policies": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"attachment_count": {
Type: schema.TypeInt,
Computed: true,
},
"control_policy_name": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"effect_scope": {
Type: schema.TypeString,
Computed: true,
},
"policy_document": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"policy_id": {
Type: schema.TypeString,
Computed: true,
},
"policy_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudResourceManagerControlPoliciesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListControlPolicies"
request := make(map[string]interface{})
if v, ok := d.GetOk("language"); ok {
request["Language"] = v
}
if v, ok := d.GetOk("policy_type"); ok {
request["PolicyType"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var controlPolicyNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
controlPolicyNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_resource_manager_control_policies", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.ControlPolicies.ControlPolicy", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.ControlPolicies.ControlPolicy", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if controlPolicyNameRegex != nil {
if !controlPolicyNameRegex.MatchString(fmt.Sprint(item["PolicyName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["PolicyId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"attachment_count": formatInt(object["AttachmentCount"]),
"control_policy_name": object["PolicyName"],
"description": object["Description"],
"effect_scope": object["EffectScope"],
"id": fmt.Sprint(object["PolicyId"]),
"policy_id": fmt.Sprint(object["PolicyId"]),
"policy_type": object["PolicyType"],
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["PolicyId"]))
names = append(names, object["PolicyName"])
s = append(s, mapping)
continue
}
resourcemanagerService := ResourcemanagerService{client}
id := fmt.Sprint(object["PolicyId"])
getResp, err := resourcemanagerService.DescribeResourceManagerControlPolicy(id)
if err != nil {
return WrapError(err)
}
mapping["policy_document"] = getResp["PolicyDocument"]
ids = append(ids, fmt.Sprint(object["PolicyId"]))
names = append(names, object["PolicyName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("policies", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudResourceManagerControlPolicyAttachments() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudResourceManagerControlPolicyAttachmentsRead,
Schema: map[string]*schema.Schema{
"policy_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"language": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"target_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"attachments": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"attach_date": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"policy_id": {
Type: schema.TypeString,
Computed: true,
},
"policy_name": {
Type: schema.TypeString,
Computed: true,
},
"policy_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudResourceManagerControlPolicyAttachmentsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListControlPolicyAttachmentsForTarget"
request := make(map[string]interface{})
if v, ok := d.GetOk("language"); ok {
request["Language"] = v
}
request["TargetId"] = d.Get("target_id")
var objects []map[string]interface{}
var response map[string]interface{}
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_resource_manager_control_policy_attachments", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.ControlPolicyAttachments.ControlPolicyAttachment", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.ControlPolicyAttachments.ControlPolicyAttachment", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if policyType, ok := d.GetOk("policy_type"); ok && policyType.(string) != fmt.Sprint(item["PolicyType"]) {
continue
}
objects = append(objects, item)
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["PolicyId"], ":", request["TargetId"]),
"attach_date": object["AttachDate"],
"description": object["Description"],
"policy_id": object["PolicyId"],
"policy_name": object["PolicyName"],
"policy_type": object["PolicyType"],
}
ids = append(ids, fmt.Sprint(object["PolicyId"], ":", request["TargetId"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("attachments", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudResourceManagerFolders() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudResourceManagerFoldersRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"parent_folder_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"query_keyword": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"folders": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"folder_id": {
Type: schema.TypeString,
Computed: true,
},
"folder_name": {
Type: schema.TypeString,
Computed: true,
},
"parent_folder_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudResourceManagerFoldersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListFoldersForParent"
request := make(map[string]interface{})
if v, ok := d.GetOk("parent_folder_id"); ok {
request["ParentFolderId"] = v
}
if v, ok := d.GetOk("query_keyword"); ok {
request["QueryKeyword"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var folderNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
folderNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_resource_manager_folders", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Folders.Folder", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Folders.Folder", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if folderNameRegex != nil {
if !folderNameRegex.MatchString(fmt.Sprint(item["FolderName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["FolderId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["FolderId"]),
"folder_id": fmt.Sprint(object["FolderId"]),
"folder_name": object["FolderName"],
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["FolderId"]))
names = append(names, object["FolderName"])
s = append(s, mapping)
continue
}
resourcemanagerService := ResourcemanagerService{client}
id := fmt.Sprint(object["FolderId"])
getResp, err := resourcemanagerService.DescribeResourceManagerFolder(id)
if err != nil {
return WrapError(err)
}
mapping["parent_folder_id"] = getResp["ParentFolderId"]
ids = append(ids, fmt.Sprint(object["FolderId"]))
names = append(names, object["FolderName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("folders", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudResourceManagerHandshakes() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudResourceManagerHandshakesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Accepted", "Cancelled", "Declined", "Deleted", "Expired", "Pending"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"handshakes": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"expire_time": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"handshake_id": {
Type: schema.TypeString,
Computed: true,
},
"invited_account_real_name": {
Type: schema.TypeString,
Computed: true,
},
"master_account_id": {
Type: schema.TypeString,
Computed: true,
},
"master_account_name": {
Type: schema.TypeString,
Computed: true,
},
"master_account_real_name": {
Type: schema.TypeString,
Computed: true,
},
"modify_time": {
Type: schema.TypeString,
Computed: true,
},
"note": {
Type: schema.TypeString,
Computed: true,
},
"resource_directory_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"target_entity": {
Type: schema.TypeString,
Computed: true,
},
"target_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudResourceManagerHandshakesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListHandshakesForResourceDirectory"
request := make(map[string]interface{})
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_resource_manager_handshakes", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Handshakes.Handshake", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Handshakes.Handshake", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["HandshakeId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"expire_time": object["ExpireTime"],
"id": fmt.Sprint(object["HandshakeId"]),
"handshake_id": fmt.Sprint(object["HandshakeId"]),
"master_account_id": object["MasterAccountId"],
"master_account_name": object["MasterAccountName"],
"modify_time": object["ModifyTime"],
"note": object["Note"],
"resource_directory_id": object["ResourceDirectoryId"],
"status": object["Status"],
"target_entity": object["TargetEntity"],
"target_type": object["TargetType"],
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["HandshakeId"]))
s = append(s, mapping)
continue
}
resourcemanagerService := ResourcemanagerService{client}
id := fmt.Sprint(object["HandshakeId"])
getResp, err := resourcemanagerService.DescribeResourceManagerHandshake(id)
if err != nil {
return WrapError(err)
}
mapping["invited_account_real_name"] = getResp["InvitedAccountRealName"]
mapping["master_account_real_name"] = getResp["MasterAccountRealName"]
ids = append(ids, fmt.Sprint(object["HandshakeId"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("handshakes", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudResourceManagerPolicies() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudResourceManagerPoliciesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"policy_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Custom", "System"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"policies": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"attachment_count": {
Type: schema.TypeInt,
Computed: true,
},
"default_version": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"policy_name": {
Type: schema.TypeString,
Computed: true,
},
"policy_type": {
Type: schema.TypeString,
Computed: true,
},
"update_date": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudResourceManagerPoliciesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListPolicies"
request := make(map[string]interface{})
if v, ok := d.GetOk("policy_type"); ok {
request["PolicyType"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var policyNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
policyNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_resource_manager_policies", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Policies.Policy", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Policies.Policy", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if policyNameRegex != nil {
if !policyNameRegex.MatchString(fmt.Sprint(item["PolicyName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["PolicyName"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"attachment_count": formatInt(object["AttachmentCount"]),
"default_version": object["DefaultVersion"],
"description": object["Description"],
"id": fmt.Sprint(object["PolicyName"]),
"policy_name": fmt.Sprint(object["PolicyName"]),
"policy_type": object["PolicyType"],
"update_date": object["UpdateDate"],
}
ids = append(ids, fmt.Sprint(object["PolicyName"]))
names = append(names, object["PolicyName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("policies", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudResourceManagerPolicyAttachments() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudResourceManagerPolicyAttachmentsRead,
Schema: map[string]*schema.Schema{
"language": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"policy_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"policy_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Custom", "System"}, false),
},
"principal_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"principal_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"IMSGroup", "IMSUser", "ServiceRole"}, false),
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"attachments": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"attach_date": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"policy_name": {
Type: schema.TypeString,
Computed: true,
},
"policy_type": {
Type: schema.TypeString,
Computed: true,
},
"principal_name": {
Type: schema.TypeString,
Computed: true,
},
"principal_type": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudResourceManagerPolicyAttachmentsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListPolicyAttachments"
request := make(map[string]interface{})
if v, ok := d.GetOk("language"); ok {
request["Language"] = v
}
if v, ok := d.GetOk("policy_name"); ok {
request["PolicyName"] = v
}
if v, ok := d.GetOk("policy_type"); ok {
request["PolicyType"] = v
}
if v, ok := d.GetOk("principal_name"); ok {
request["PrincipalName"] = v
}
if v, ok := d.GetOk("principal_type"); ok {
request["PrincipalType"] = v
}
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var response map[string]interface{}
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_resource_manager_policy_attachments", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.PolicyAttachments.PolicyAttachment", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.PolicyAttachments.PolicyAttachment", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["PolicyName"], ":", object["PolicyType"], ":", object["PrincipalName"], ":", object["PrincipalType"], ":", object["ResourceGroupId"]),
"attach_date": object["AttachDate"],
"description": object["Description"],
"policy_name": object["PolicyName"],
"policy_type": object["PolicyType"],
"principal_name": object["PrincipalName"],
"principal_type": object["PrincipalType"],
"resource_group_id": object["ResourceGroupId"],
}
ids = append(ids, fmt.Sprint(object["PolicyName"], ":", object["PolicyType"], ":", object["PrincipalName"], ":", object["PrincipalType"], ":", object["ResourceGroupId"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("attachments", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudResourceManagerPolicyVersions() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudResourceManagerPolicyVersionsRead,
Schema: map[string]*schema.Schema{
"policy_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"policy_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Custom", "System"}, false),
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"versions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"is_default_version": {
Type: schema.TypeBool,
Computed: true,
},
"policy_document": {
Type: schema.TypeString,
Computed: true,
},
"version_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudResourceManagerPolicyVersionsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListPolicyVersions"
request := make(map[string]interface{})
request["PolicyName"] = d.Get("policy_name")
request["PolicyType"] = d.Get("policy_type")
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var objects []map[string]interface{}
var response map[string]interface{}
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_resource_manager_policy_versions", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.PolicyVersions.PolicyVersion", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.PolicyVersions.PolicyVersion", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(request["PolicyName"], ":", item["VersionId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(request["PolicyName"], ":", object["VersionId"]),
"is_default_version": object["IsDefaultVersion"],
"version_id": object["VersionId"],
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(request["PolicyName"], ":", object["VersionId"]))
s = append(s, mapping)
continue
}
resourcemanagerService := ResourcemanagerService{client}
id := fmt.Sprint(request["PolicyName"], ":", object["VersionId"])
getResp, err := resourcemanagerService.DescribeResourceManagerPolicyVersion(id)
if err != nil {
return WrapError(err)
}
mapping["policy_document"] = getResp["PolicyDocument"]
ids = append(ids, fmt.Sprint(request["PolicyName"], ":", object["VersionId"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("versions", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudResourceManagerResourceDirectories() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudResourceManagerResourceDirectoriesRead,
Schema: map[string]*schema.Schema{
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"directories": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"master_account_id": {
Type: schema.TypeString,
Computed: true,
},
"master_account_name": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"resource_directory_id": {
Type: schema.TypeString,
Computed: true,
},
"root_folder_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudResourceManagerResourceDirectoriesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "GetResourceDirectory"
request := make(map[string]interface{})
var response map[string]interface{}
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_resource_manager_resource_directories", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
s := make([]map[string]interface{}, 0)
mapping := map[string]interface{}{
"master_account_id": response["ResourceDirectory"].(map[string]interface{})["MasterAccountId"],
"master_account_name": response["ResourceDirectory"].(map[string]interface{})["MasterAccountName"],
"id": fmt.Sprint(response["ResourceDirectory"].(map[string]interface{})["ResourceDirectoryId"]),
"resource_directory_id": fmt.Sprint(response["ResourceDirectory"].(map[string]interface{})["ResourceDirectoryId"]),
"root_folder_id": response["ResourceDirectory"].(map[string]interface{})["RootFolderId"],
"status": response["ResourceDirectory"].(map[string]interface{})["ScpStatus"],
}
s = append(s, mapping)
d.SetId(fmt.Sprint(response["ResourceDirectory"].(map[string]interface{})["ResourceDirectoryId"]))
if err := d.Set("directories", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudResourceManagerResourceGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudResourceManagerResourceGroupsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Creating", "Deleted", "Deleting", "OK", "PendingDelete"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_id": {
Type: schema.TypeString,
Computed: true,
},
"display_name": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"region_statuses": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"resource_group_name": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudResourceManagerResourceGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListResourceGroups"
request := make(map[string]interface{})
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var resourceGroupNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
resourceGroupNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_resource_manager_resource_groups", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.ResourceGroups.ResourceGroup", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.ResourceGroups.ResourceGroup", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if resourceGroupNameRegex != nil {
if !resourceGroupNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Id"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"account_id": object["AccountId"],
"display_name": object["DisplayName"],
"id": fmt.Sprint(object["Id"]),
"resource_group_name": object["Name"],
"name": object["Name"],
"status": object["Status"],
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["Id"]))
names = append(names, object["Name"])
s = append(s, mapping)
continue
}
resourcemanagerService := ResourcemanagerService{client}
id := fmt.Sprint(object["Id"])
getResp, err := resourcemanagerService.DescribeResourceManagerResourceGroup(id)
if err != nil {
return WrapError(err)
}
regionStatus := make([]map[string]interface{}, 0)
if regionStatusList, ok := getResp["RegionStatuses"].(map[string]interface{})["RegionStatus"].([]interface{}); ok {
for _, v := range regionStatusList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"region_id": m1["RegionId"],
"status": m1["Status"],
}
regionStatus = append(regionStatus, temp1)
}
}
}
mapping["region_statuses"] = regionStatus
ids = append(ids, fmt.Sprint(object["Id"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudResourceManagerResourceShares() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudResourceManagerResourceSharesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"resource_share_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"resource_share_owner": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Self", "OtherAccounts"}, false),
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Deleted", "Deleting"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"shares": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"resource_share_id": {
Type: schema.TypeString,
Computed: true,
},
"resource_share_name": {
Type: schema.TypeString,
Computed: true,
},
"resource_share_owner": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudResourceManagerResourceSharesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListResourceShares"
request := make(map[string]interface{})
if v, ok := d.GetOk("resource_share_name"); ok {
request["ResourceShareName"] = v
}
request["ResourceOwner"] = d.Get("resource_share_owner")
request["MaxResults"] = PageSizeMedium
var objects []map[string]interface{}
var resourceShareNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
resourceShareNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewRessharingClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_resource_manager_resource_shares", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.ResourceShares", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.ResourceShares", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if resourceShareNameRegex != nil {
if !resourceShareNameRegex.MatchString(fmt.Sprint(item["ResourceShareName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ResourceShareId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["ResourceShareStatus"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["ResourceShareId"]),
"resource_share_id": fmt.Sprint(object["ResourceShareId"]),
"resource_share_name": object["ResourceShareName"],
"resource_share_owner": object["ResourceShareOwner"],
"status": object["ResourceShareStatus"],
}
ids = append(ids, fmt.Sprint(object["ResourceShareId"]))
names = append(names, object["ResourceShareName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("shares", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudResourceManagerRoles() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudResourceManagerRolesRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"roles": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"arn": {
Type: schema.TypeString,
Computed: true,
},
"assume_role_policy_document": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"max_session_duration": {
Type: schema.TypeInt,
Computed: true,
},
"role_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"role_name": {
Type: schema.TypeString,
Computed: true,
},
"update_date": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudResourceManagerRolesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListRoles"
request := make(map[string]interface{})
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var roleNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
roleNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_resource_manager_roles", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Roles.Role", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Roles.Role", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if roleNameRegex != nil {
if !roleNameRegex.MatchString(fmt.Sprint(item["RoleName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["RoleName"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"arn": object["Arn"],
"description": object["Description"],
"max_session_duration": object["MaxSessionDuration"],
"role_id": object["RoleId"],
"id": fmt.Sprint(object["RoleName"]),
"role_name": fmt.Sprint(object["RoleName"]),
"update_date": object["UpdateDate"],
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["RoleName"]))
names = append(names, object["RoleName"])
s = append(s, mapping)
continue
}
resourcemanagerService := ResourcemanagerService{client}
id := fmt.Sprint(object["RoleName"])
getResp, err := resourcemanagerService.DescribeResourceManagerRole(id)
if err != nil {
return WrapError(err)
}
mapping["assume_role_policy_document"] = getResp["AssumeRolePolicyDocument"]
ids = append(ids, fmt.Sprint(object["RoleName"]))
names = append(names, object["RoleName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("roles", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudResourceManagerSharedResources() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudResourceManagerSharedResourcesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"resource_share_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Associated", "Associating", "Disassociated", "Disassociating", "Failed"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"resources": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"resource_id": {
Type: schema.TypeString,
Computed: true,
},
"resource_share_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"resource_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudResourceManagerSharedResourcesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListResourceShareAssociations"
request := make(map[string]interface{})
request["AssociationType"] = "Resource"
if v, ok := d.GetOk("resource_share_id"); ok {
request["ResourceShareIds"] = []string{v.(string)}
}
request["MaxResults"] = PageSizeMedium
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewRessharingClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_resource_manager_shared_resources", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.ResourceShareAssociations", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.ResourceShareAssociations", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["EntityId"], ":", item["EntityType"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["AssociationStatus"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"resource_id": object["EntityId"],
"resource_share_id": object["ResourceShareId"],
"id": fmt.Sprint(object["EntityId"], ":", object["EntityType"]),
"resource_type": fmt.Sprint(object["EntityType"]),
"status": object["AssociationStatus"],
}
ids = append(ids, fmt.Sprint(object["EntityId"], ":", object["EntityType"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("resources", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudResourceManagerSharedTargets() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudResourceManagerSharedTargetsRead,
Schema: map[string]*schema.Schema{
"resource_share_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Associated", "Associating", "Disassociated", "Disassociating", "Failed"}, false),
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"targets": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"resource_share_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"target_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudResourceManagerSharedTargetsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListResourceShareAssociations"
request := make(map[string]interface{})
request["AssociationType"] = "Target"
if v, ok := d.GetOk("resource_share_id"); ok {
request["ResourceShareIds"] = []string{v.(string)}
}
request["MaxResults"] = PageSizeMedium
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewRessharingClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_resource_manager_shared_targets", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.ResourceShareAssociations", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.ResourceShareAssociations", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["EntityId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["AssociationStatus"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"resource_share_id": object["ResourceShareId"],
"status": object["AssociationStatus"],
"id": fmt.Sprint(object["EntityId"]),
"target_id": fmt.Sprint(object["EntityId"]),
}
ids = append(ids, fmt.Sprint(object["EntityId"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("targets", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudRosChangeSets() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudRosChangeSetsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"change_set_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"stack_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"CREATE_COMPLETE", "CREATE_FAILED", "CREATE_IN_PROGRESS", "CREATE_PENDING", "DELETE_COMPLETE", "DELETE_FAILED"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"sets": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"change_set_id": {
Type: schema.TypeString,
Computed: true,
},
"change_set_name": {
Type: schema.TypeString,
Computed: true,
},
"change_set_type": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"disable_rollback": {
Type: schema.TypeBool,
Computed: true,
},
"execution_status": {
Type: schema.TypeString,
Computed: true,
},
"parameters": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"parameter_key": {
Type: schema.TypeString,
Computed: true,
},
"parameter_value": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"stack_id": {
Type: schema.TypeString,
Computed: true,
},
"stack_name": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"template_body": {
Type: schema.TypeString,
Computed: true,
},
"timeout_in_minutes": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudRosChangeSetsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListChangeSets"
request := make(map[string]interface{})
if v, ok := d.GetOk("change_set_name"); ok {
request["ChangeSetName"] = v
}
request["RegionId"] = client.RegionId
request["StackId"] = d.Get("stack_id")
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var changeSetNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
changeSetNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewRosClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ros_change_sets", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.ChangeSets", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.ChangeSets", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if changeSetNameRegex != nil {
if !changeSetNameRegex.MatchString(item["ChangeSetName"].(string)) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ChangeSetId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["ChangeSetId"]),
"change_set_id": object["ChangeSetId"],
"change_set_name": object["ChangeSetName"],
"change_set_type": object["ChangeSetType"],
"description": object["Description"],
"stack_id": object["StackId"],
"stack_name": object["StackName"],
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["ChangeSetId"]))
names = append(names, object["ChangeSetName"].(string))
s = append(s, mapping)
continue
}
rosService := RosService{client}
id := fmt.Sprint(object["ChangeSetId"])
getResp, err := rosService.DescribeRosChangeSet(id)
if err != nil {
return WrapError(err)
}
if statusOk && status != "" && status != getResp["Status"].(string) {
continue
}
mapping["disable_rollback"] = getResp["DisableRollback"]
mapping["execution_status"] = getResp["ExecutionStatus"]
Parameters := getResp["Parameters"].([]interface{})
parameters := make([]map[string]interface{}, len(Parameters))
for i, v := range Parameters {
mapping1 := map[string]interface{}{
"parameter_key": v.(map[string]interface{})["Parameters"],
"parameter_value": v.(map[string]interface{})["Parameters"],
}
parameters[i] = mapping1
}
mapping["parameters"] = getResp["parameters"]
mapping["status"] = getResp["Status"]
mapping["template_body"] = getResp["TemplateBody"]
mapping["timeout_in_minutes"] = getResp["TimeoutInMinutes"]
ids = append(ids, fmt.Sprint(object["ChangeSetId"]))
names = append(names, object["ChangeSetName"].(string))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("sets", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"strconv"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudRosRegions() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudRosRegionsRead,
Schema: map[string]*schema.Schema{
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"regions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"region_endpoint": {
Type: schema.TypeString,
Computed: true,
},
"local_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudRosRegionsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeRegions"
request := make(map[string]interface{})
request["AcceptLanguage"] = "en-US"
var objects []map[string]interface{}
var response map[string]interface{}
conn, err := client.NewRosClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ros_regions", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Regions", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Regions", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
objects = append(objects, item)
}
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"region_id": fmt.Sprint(object["RegionId"]),
"region_endpoint": object["RegionEndpoint"],
"local_name": object["LocalName"],
}
s = append(s, mapping)
}
d.SetId(strconv.FormatInt(time.Now().Unix(), 16))
if err := d.Set("regions", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"encoding/json"
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudRosStackGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudRosStackGroupsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ACTIVE", "DELETED"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"administration_role_name": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"execution_role_name": {
Type: schema.TypeString,
Computed: true,
},
"parameters": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"parameter_key": {
Type: schema.TypeString,
Computed: true,
},
"parameter_value": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"stack_group_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"stack_group_name": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"template_body": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudRosStackGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListStackGroups"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var stackGroupNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
stackGroupNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewRosClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ros_stack_groups", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.StackGroups", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.StackGroups", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if stackGroupNameRegex != nil {
if !stackGroupNameRegex.MatchString(item["StackGroupName"].(string)) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["StackGroupName"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"description": object["Description"],
"stack_group_id": object["StackGroupId"],
"id": fmt.Sprint(object["StackGroupName"]),
"stack_group_name": fmt.Sprint(object["StackGroupName"]),
"status": object["Status"],
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["StackGroupName"]))
names = append(names, object["StackGroupName"].(string))
s = append(s, mapping)
continue
}
rosService := RosService{client}
id := fmt.Sprint(object["StackGroupName"])
getResp, err := rosService.DescribeRosStackGroup(id)
if err != nil {
return WrapError(err)
}
mapping["administration_role_name"] = getResp["AdministrationRoleName"]
mapping["execution_role_name"] = getResp["ExecutionRoleName"]
parameters := make([]map[string]interface{}, 0)
if parametersList, ok := getResp["Parameters"].([]interface{}); ok {
for _, v := range parametersList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"parameter_key": m1["ParameterKey"],
"parameter_value": m1["ParameterValue"],
}
parameters = append(parameters, temp1)
}
}
}
mapping["parameters"] = parameters
b, err := json.Marshal(getResp["TemplateBody"])
if err != nil {
return WrapError(err)
}
mapping["template_body"] = string(b)
ids = append(ids, fmt.Sprint(object["StackGroupName"]))
names = append(names, object["StackGroupName"].(string))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudRosStackInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudRosStackInstancesRead,
Schema: map[string]*schema.Schema{
"stack_group_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-zA-Z][-_a-zA-Z0-9]{1,254}$`), "The name can be up to 255 characters in length and can contain digits, letters, hyphens (-), and underscores (_). It must start with a digit or letter."),
},
"stack_instance_account_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^\d+$`), "It can only be made of numbers."),
},
"stack_instance_region_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"CURRENT", "OUTDATED"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"parameter_overrides": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"parameter_key": {
Type: schema.TypeString,
Computed: true,
},
"parameter_value": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"stack_group_id": {
Type: schema.TypeString,
Computed: true,
},
"stack_group_name": {
Type: schema.TypeString,
Computed: true,
},
"stack_id": {
Type: schema.TypeString,
Computed: true,
},
"stack_instance_account_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"stack_instance_region_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"status_reason": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudRosStackInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListStackInstances"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
request["StackGroupName"] = d.Get("stack_group_name")
if v, ok := d.GetOk("stack_instance_account_id"); ok {
request["StackInstanceAccountId"] = v
}
if v, ok := d.GetOk("stack_instance_region_id"); ok {
request["StackInstanceRegionId"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewRosClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ros_stack_instances", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.StackInstances", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.StackInstances", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(request["StackGroupName"], ":", item["AccountId"], ":", item["RegionId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"stack_group_id": object["StackGroupId"],
"stack_group_name": object["StackGroupName"],
"stack_id": object["StackId"],
"stack_instance_account_id": fmt.Sprint(object["AccountId"]),
"id": fmt.Sprint(object["StackGroupName"], ":", object["AccountId"], ":", object["RegionId"]),
"stack_instance_region_id": fmt.Sprint(object["RegionId"]),
"status": object["Status"],
"status_reason": object["StatusReason"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
rosService := RosService{client}
getResp, err := rosService.DescribeRosStackInstance(mapping["id"].(string))
if err != nil {
return WrapError(err)
}
parameterOverrides := make([]map[string]interface{}, 0)
if parameterOverridesList, ok := getResp["ParameterOverrides"].([]interface{}); ok {
for _, v := range parameterOverridesList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"parameter_key": m1["ParameterKey"],
"parameter_value": m1["ParameterValue"],
}
parameterOverrides = append(parameterOverrides, temp1)
}
}
}
mapping["parameter_overrides"] = parameterOverrides
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"encoding/json"
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudRosStacks() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudRosStacksRead,
Schema: map[string]*schema.Schema{
"parent_stack_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"show_nested_stack": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"stack_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"CREATE_COMPLETE", "CREATE_FAILED", "CREATE_IN_PROGRESS", "DELETE_COMPLETE", "DELETE_FAILED", "DELETE_IN_PROGRESS", "ROLLBACK_COMPLETE", "ROLLBACK_FAILED", "ROLLBACK_IN_PROGRESS"}, false),
},
"tags": tagsSchema(),
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"stacks": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"deletion_protection": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"disable_rollback": {
Type: schema.TypeBool,
Computed: true,
},
"drift_detection_time": {
Type: schema.TypeString,
Computed: true,
},
"parameters": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"parameter_key": {
Type: schema.TypeString,
Computed: true,
},
"parameter_value": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"parent_stack_id": {
Type: schema.TypeString,
Computed: true,
},
"ram_role_name": {
Type: schema.TypeString,
Computed: true,
},
"root_stack_id": {
Type: schema.TypeString,
Computed: true,
},
"stack_drift_status": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"stack_id": {
Type: schema.TypeString,
Computed: true,
},
"stack_name": {
Type: schema.TypeString,
Computed: true,
},
"stack_policy_body": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"status_reason": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"template_description": {
Type: schema.TypeString,
Computed: true,
},
"timeout_in_minutes": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudRosStacksRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListStacks"
request := make(map[string]interface{})
if v, ok := d.GetOk("parent_stack_id"); ok {
request["ParentStackId"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOkExists("show_nested_stack"); ok {
request["ShowNestedStack"] = v
}
if v, ok := d.GetOk("stack_name"); ok {
request["StackName"] = v
}
if v, ok := d.GetOk("tags"); ok {
tags := make([]map[string]interface{}, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, map[string]interface{}{
"Key": key,
"Value": value.(string),
})
}
request["Tag"] = tags
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var stackNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
stackNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewRosClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ros_stacks", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Stacks", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Stacks", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if stackNameRegex != nil {
if !stackNameRegex.MatchString(item["StackName"].(string)) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["StackId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"disable_rollback": object["DisableRollback"],
"drift_detection_time": object["DriftDetectionTime"],
"parent_stack_id": object["ParentStackId"],
"stack_drift_status": object["StackDriftStatus"],
"id": fmt.Sprint(object["StackId"]),
"stack_id": fmt.Sprint(object["StackId"]),
"stack_name": object["StackName"],
"status_reason": object["StatusReason"],
"timeout_in_minutes": formatInt(object["TimeoutInMinutes"]),
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["StackId"]))
names = append(names, object["StackName"].(string))
s = append(s, mapping)
continue
}
rosService := RosService{client}
id := fmt.Sprint(object["StackId"])
getResp, err := rosService.DescribeRosStack(id)
if err != nil {
return WrapError(err)
}
if statusOk && status != "" && status != getResp["Status"].(string) {
continue
}
mapping["deletion_protection"] = getResp["DeletionProtection"]
mapping["description"] = getResp["Description"]
parameters := make([]map[string]interface{}, 0)
if parametersList, ok := getResp["Parameters"].([]interface{}); ok {
for _, v := range parametersList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"parameter_key": m1["ParameterKey"],
"parameter_value": m1["ParameterValue"],
}
parameters = append(parameters, temp1)
}
}
}
mapping["parameters"] = parameters
mapping["ram_role_name"] = getResp["RamRoleName"]
mapping["root_stack_id"] = getResp["RootStackId"]
mapping["status"] = getResp["Status"]
mapping["template_description"] = getResp["TemplateDescription"]
getResp1, err := rosService.GetStackPolicy(id)
if err != nil {
return WrapError(err)
}
b, err := json.Marshal(getResp1["StackPolicyBody"])
mapping["stack_policy_body"] = string(b)
getResp2, err := rosService.ListTagResources(id, "stack")
if err != nil {
return WrapError(err)
}
mapping["tags"] = tagsToMap(getResp2)
ids = append(ids, fmt.Sprint(object["StackId"]))
names = append(names, object["StackName"].(string))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("stacks", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudRosTemplateScratches() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudRosTemplateScratchesRead,
Schema: map[string]*schema.Schema{
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"GENERATE_COMPLETE", "GENERATE_FAILED", "GENERATE_IN_PROGRESS"}, false),
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"template_scratch_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ResourceImport", "ArchitectureReplication"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"scratches": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"logical_id_strategy": {
Type: schema.TypeString,
Computed: true,
},
"preference_parameters": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"parameter_key": {
Type: schema.TypeString,
Computed: true,
},
"parameter_value": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"source_tag": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"resource_tags": {
Type: schema.TypeMap,
Computed: true,
},
"resource_type_filter": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"source_resource_group": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"resource_type_filter": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"source_resources": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"resource_id": {
Type: schema.TypeString,
Computed: true,
},
"resource_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"stacks": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"stack_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"template_scratch_id": {
Type: schema.TypeString,
Computed: true,
},
"template_scratch_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudRosTemplateScratchesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListTemplateScratches"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("status"); ok {
request["Status"] = convertListToJsonString([]interface{}{v})
}
if v, ok := d.GetOk("template_scratch_type"); ok {
request["TemplateScratchType"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewRosClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ros_template_scratches", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.TemplateScratches", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.TemplateScratches", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["TemplateScratchId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": object["CreateTime"],
"description": object["Description"],
"logical_id_strategy": object["LogicalIdStrategy"],
"status": object["Status"],
"id": fmt.Sprint(object["TemplateScratchId"]),
"template_scratch_id": fmt.Sprint(object["TemplateScratchId"]),
"template_scratch_type": object["TemplateScratchType"],
}
preferenceParameters := make([]map[string]interface{}, 0)
if preferenceParametersList, ok := object["PreferenceParameters"].([]interface{}); ok {
for _, v := range preferenceParametersList {
if m1, ok := v.(map[string]interface{}); ok {
if v, ok := m1["ParameterValue"]; ok && fmt.Sprint(v) != "" {
temp1 := map[string]interface{}{
"parameter_key": m1["ParameterKey"],
"parameter_value": v,
}
preferenceParameters = append(preferenceParameters, temp1)
}
}
}
}
mapping["preference_parameters"] = preferenceParameters
sourceResourceGroupSli := make([]map[string]interface{}, 0)
if v, ok := object["SourceResourceGroup"]; ok {
if sourceResourceGroup, ok := v.(map[string]interface{}); ok && len(sourceResourceGroup) > 0 {
sourceResourceGroupMap := make(map[string]interface{})
sourceResourceGroupMap["resource_group_id"] = sourceResourceGroup["ResourceGroupId"]
resourceTypeFilter := make([]interface{}, 0)
if v, ok := sourceResourceGroup["ResourceTypeFilter"]; ok {
if vv, ok := v.([]interface{}); ok && len(vv) > 0 {
resourceTypeFilter = append(resourceTypeFilter, vv...)
}
}
sourceResourceGroupMap["resource_type_filter"] = resourceTypeFilter
sourceResourceGroupSli = append(sourceResourceGroupSli, sourceResourceGroupMap)
}
}
mapping["source_resource_group"] = sourceResourceGroupSli
sourceResources := make([]map[string]interface{}, 0)
if sourceResourcesList, ok := object["SourceResources"].([]interface{}); ok {
for _, v := range sourceResourcesList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"resource_id": m1["ResourceId"],
"resource_type": m1["ResourceType"],
}
sourceResources = append(sourceResources, temp1)
}
}
}
mapping["source_resources"] = sourceResources
sourceTagSli := make([]map[string]interface{}, 0)
if v, ok := object["SourceTag"]; ok {
if sourceTag, ok := v.(map[string]interface{}); ok && len(sourceTag) > 0 {
sourceTagMap := make(map[string]interface{})
sourceTagMap["resource_tags"] = sourceTag["ResourceTags"]
resourceTypeFilter := make([]interface{}, 0)
if v, ok := sourceTag["ResourceTypeFilter"]; ok {
if vv, ok := v.([]interface{}); ok && len(vv) > 0 {
resourceTypeFilter = append(resourceTypeFilter, vv...)
}
}
sourceTagMap["resource_type_filter"] = resourceTypeFilter
sourceTagSli = append(sourceTagSli, sourceTagMap)
}
}
mapping["source_tag"] = sourceTagSli
ids = append(ids, fmt.Sprint(mapping["id"]))
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["TemplateScratchId"])
rosService := RosService{client}
getResp, err := rosService.DescribeRosTemplateScratch(id)
if err != nil {
return WrapError(err)
}
stacks := make([]map[string]interface{}, 0)
if stacksList, ok := getResp["Stacks"].([]interface{}); ok {
for _, v := range stacksList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"stack_id": m1["StackId"],
}
stacks = append(stacks, temp1)
}
}
}
mapping["stacks"] = stacks
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("scratches", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"encoding/json"
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudRosTemplates() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudRosTemplatesRead,
Schema: map[string]*schema.Schema{
"share_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Private", "Shared"}, false),
},
"tags": tagsSchema(),
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"template_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"templates": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"change_set_id": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"share_type": {
Type: schema.TypeString,
Computed: true,
},
"stack_group_name": {
Type: schema.TypeString,
Computed: true,
},
"stack_id": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"template_body": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"template_id": {
Type: schema.TypeString,
Computed: true,
},
"template_name": {
Type: schema.TypeString,
Computed: true,
},
"template_version": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudRosTemplatesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListTemplates"
request := make(map[string]interface{})
if v, ok := d.GetOk("share_type"); ok {
request["ShareType"] = v
}
if v, ok := d.GetOk("tags"); ok {
tags := make([]map[string]interface{}, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, map[string]interface{}{
"Key": key,
"Value": value.(string),
})
}
request["Tag"] = tags
}
if v, ok := d.GetOk("template_name"); ok {
request["TemplateName"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var templateNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
templateNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewRosClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ros_templates", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Templates", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Templates", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if templateNameRegex != nil {
if !templateNameRegex.MatchString(item["TemplateName"].(string)) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["TemplateId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"description": object["Description"],
"share_type": object["ShareType"],
"id": fmt.Sprint(object["TemplateId"]),
"template_id": fmt.Sprint(object["TemplateId"]),
"template_name": object["TemplateName"],
"template_version": object["TemplateVersion"],
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["TemplateId"]))
names = append(names, object["TemplateName"].(string))
s = append(s, mapping)
continue
}
rosService := RosService{client}
id := fmt.Sprint(object["TemplateId"])
getResp, err := rosService.DescribeRosTemplate(id)
if err != nil {
return WrapError(err)
}
mapping["change_set_id"] = getResp["ChangeSetId"]
mapping["stack_group_name"] = getResp["StackGroupName"]
mapping["stack_id"] = getResp["StackId"]
b, err := json.Marshal(getResp["TemplateBody"])
if err != nil {
return WrapError(err)
}
mapping["template_body"] = string(b)
getResp1, err := rosService.ListTagResources(id, "template")
if err != nil {
return WrapError(err)
}
mapping["tags"] = tagsToMap(getResp1)
ids = append(ids, fmt.Sprint(object["TemplateId"]))
names = append(names, object["TemplateName"].(string))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("templates", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudRouteEntries() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudRouteEntriesRead,
Schema: map[string]*schema.Schema{
"route_table_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"instance_id": {
Type: schema.TypeString,
Optional: true,
},
"type": {
Type: schema.TypeString,
Optional: true,
},
"cidr_block": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"entries": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"type": {
Type: schema.TypeString,
Computed: true,
},
"next_hop_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"route_table_id": {
Type: schema.TypeString,
Computed: true,
},
"cidr_block": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudRouteEntriesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := vpc.CreateDescribeRouteTablesRequest()
request.RegionId = string(client.Region)
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
request.RouteTableId = d.Get("route_table_id").(string)
var allRouteEntries []vpc.RouteEntry
invoker := NewInvoker()
for {
var raw interface{}
if err := invoker.Run(func() error {
response, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeRouteTables(request)
})
raw = response
return err
}); err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_route_entries", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*vpc.DescribeRouteTablesResponse)
if len(response.RouteTables.RouteTable) < 1 {
break
}
for _, entries := range response.RouteTables.RouteTable[0].RouteEntrys.RouteEntry {
if instance_id, ok := d.GetOk("instance_id"); ok && entries.InstanceId != instance_id.(string) {
continue
}
if route_entry_type, ok := d.GetOk("type"); ok && entries.Type != route_entry_type.(string) {
continue
}
if cidr_block, ok := d.GetOk("cidr_block"); ok && entries.DestinationCidrBlock != cidr_block.(string) {
continue
}
allRouteEntries = append(allRouteEntries, entries)
}
if len(response.RouteTables.RouteTable) < PageSizeLarge {
break
}
if page, err := getNextpageNumber(request.PageNumber); err != nil {
return WrapError(err)
} else {
request.PageNumber = page
}
}
return RouteEntriesDecriptionAttributes(d, allRouteEntries, meta)
}
func RouteEntriesDecriptionAttributes(d *schema.ResourceData, entries []vpc.RouteEntry, meta interface{}) error {
var ids []string
var s []map[string]interface{}
for _, entry := range entries {
mapping := map[string]interface{}{
"route_table_id": entry.RouteTableId,
"instance_id": entry.InstanceId,
"status": entry.Status,
"next_hop_type": entry.NextHopType,
"type": entry.Type,
"cidr_block": entry.DestinationCidrBlock,
}
ids = append(ids, entry.RouteTableId)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("entries", s); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudRouteTables() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudRouteTablesRead,
Schema: map[string]*schema.Schema{
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"route_table_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"router_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"router_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"VRouter", "VBR"}, false),
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "Pending"}, false),
},
"tags": tagsSchema(),
"vpc_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"page_number": {
Type: schema.TypeInt,
Optional: true,
},
"page_size": {
Type: schema.TypeInt,
Optional: true,
Default: 50,
},
"tables": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"route_table_id": {
Type: schema.TypeString,
Computed: true,
},
"route_table_name": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"route_table_type": {
Type: schema.TypeString,
Computed: true,
},
"router_id": {
Type: schema.TypeString,
Computed: true,
},
"router_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"vswitch_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"total_count": {
Type: schema.TypeInt,
Computed: true,
},
},
}
}
func dataSourceAlicloudRouteTablesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeRouteTableList"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("route_table_name"); ok {
request["RouteTableName"] = v
}
if v, ok := d.GetOk("router_id"); ok {
request["RouterId"] = v
}
if v, ok := d.GetOk("router_type"); ok {
request["RouterType"] = v
}
if v, ok := d.GetOk("tags"); ok {
tags := make([]map[string]interface{}, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, map[string]interface{}{
"Key": key,
"Value": value.(string),
})
}
request["Tag"] = tags
}
if v, ok := d.GetOk("vpc_id"); ok {
request["VpcId"] = v
}
if v, ok := d.GetOk("page_number"); ok && v.(int) > 0 {
request["PageNumber"] = v.(int)
} else {
request["PageNumber"] = 1
}
if v, ok := d.GetOk("page_size"); ok && v.(int) > 0 {
request["PageSize"] = v.(int)
} else {
request["PageSize"] = PageSizeLarge
}
var objects []interface{}
var routeTableNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
routeTableNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_route_tables", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.RouterTableList.RouterTableListType", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.RouterTableList.RouterTableListType", response)
}
result, _ := resp.([]interface{})
if isPagingRequest(d) {
objects = result
break
}
for _, v := range result {
item := v.(map[string]interface{})
if routeTableNameRegex != nil {
if !routeTableNameRegex.MatchString(fmt.Sprint(item["RouteTableName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["RouteTableId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, v := range objects {
object := v.(map[string]interface{})
mapping := map[string]interface{}{
"description": object["Description"],
"resource_group_id": object["ResourceGroupId"],
"id": fmt.Sprint(object["RouteTableId"]),
"route_table_id": fmt.Sprint(object["RouteTableId"]),
"route_table_name": object["RouteTableName"],
"name": object["RouteTableName"],
"route_table_type": object["RouteTableType"],
"router_id": object["RouterId"],
"router_type": object["RouterType"],
"status": object["Status"],
"vswitch_ids": object["VSwitchIds"].(map[string]interface{})["VSwitchId"],
"vpc_id": object["VpcId"],
}
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags.Tag", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["Key"].(string)
value := t.(map[string]interface{})["Value"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
ids = append(ids, fmt.Sprint(object["RouteTableId"]))
names = append(names, object["RouteTableName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("tables", s); err != nil {
return WrapError(err)
}
if err := d.Set("total_count", formatInt(response["TotalCount"])); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudRouterInterfaces() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudRouterInterfacesRead,
Schema: map[string]*schema.Schema{
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Inactive", "Idle"}, false),
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"specification": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"router_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"router_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
string(VRouter), string(VBR)}, false),
},
"role": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"opposite_interface_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"opposite_interface_owner_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"interfaces": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"role": {
Type: schema.TypeString,
Computed: true,
},
"specification": {
Type: schema.TypeString,
Computed: true,
},
"router_id": {
Type: schema.TypeString,
Computed: true,
},
"router_type": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"access_point_id": {
Type: schema.TypeString,
Computed: true,
},
"creation_time": {
Type: schema.TypeString,
Computed: true,
},
"opposite_region_id": {
Type: schema.TypeString,
Computed: true,
},
"opposite_interface_id": {
Type: schema.TypeString,
Computed: true,
},
"opposite_router_id": {
Type: schema.TypeString,
Computed: true,
},
"opposite_router_type": {
Type: schema.TypeString,
Computed: true,
},
"opposite_interface_owner_id": {
Type: schema.TypeString,
Computed: true,
},
"health_check_source_ip": {
Type: schema.TypeString,
Computed: true,
},
"health_check_target_ip": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudRouterInterfacesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := vpc.CreateDescribeRouterInterfacesRequest()
request.RegionId = string(client.Region)
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var filters []vpc.DescribeRouterInterfacesFilter
for _, key := range []string{"status", "router_id", "router_type", "opposite_interface_id", "opposite_interface_owner_id"} {
if v, ok := d.GetOk(key); ok && v.(string) != "" {
value := []string{v.(string)}
filters = append(filters, vpc.DescribeRouterInterfacesFilter{
Key: terraformToAPI(key),
Value: &value,
})
}
}
request.Filter = &filters
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[Trim(vv.(string))] = Trim(vv.(string))
}
}
var allRouterInterfaces []vpc.RouterInterfaceType
invoker := NewInvoker()
for {
var response *vpc.DescribeRouterInterfacesResponse
err := invoker.Run(func() error {
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeRouterInterfaces(request)
})
if err != nil {
return err
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*vpc.DescribeRouterInterfacesResponse)
return nil
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_router_interfaces", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
if len(response.RouterInterfaceSet.RouterInterfaceType) < 1 {
break
}
allRouterInterfaces = append(allRouterInterfaces, response.RouterInterfaceSet.RouterInterfaceType...)
if len(response.RouterInterfaceSet.RouterInterfaceType) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
var filteredRouterInterfaces []vpc.RouterInterfaceType
var rounterInterfaceNameRegex *regexp.Regexp
if nameRegex, ok := d.GetOk("name_regex"); ok && nameRegex.(string) != "" {
r, err := regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
rounterInterfaceNameRegex = r
}
for _, v := range allRouterInterfaces {
if len(idsMap) > 0 {
if _, ok := idsMap[v.RouterInterfaceId]; !ok {
continue
}
}
if rounterInterfaceNameRegex != nil && !rounterInterfaceNameRegex.MatchString(v.Name) {
continue
}
if role := d.Get("role").(string); role != "" && role != v.Role {
continue
}
if spec := d.Get("specification").(string); spec != "" && spec != v.Spec {
continue
}
filteredRouterInterfaces = append(filteredRouterInterfaces, v)
}
return riDecriptionAttributes(d, filteredRouterInterfaces, meta)
}
func riDecriptionAttributes(d *schema.ResourceData, riSetTypes []vpc.RouterInterfaceType, meta interface{}) error {
var ids []string
var names []string
var s []map[string]interface{}
for _, ri := range riSetTypes {
mapping := map[string]interface{}{
"id": ri.RouterInterfaceId,
"status": ri.Status,
"name": ri.Name,
"description": ri.Description,
"role": ri.Role,
"specification": ri.Spec,
"router_id": ri.RouterId,
"router_type": ri.RouterType,
"vpc_id": ri.VpcInstanceId,
"access_point_id": ri.AccessPointId,
"creation_time": ri.CreationTime,
"opposite_region_id": ri.OppositeRegionId,
"opposite_interface_id": ri.OppositeInterfaceId,
"opposite_router_id": ri.OppositeRouterId,
"opposite_router_type": ri.OppositeRouterType,
"opposite_interface_owner_id": ri.OppositeInterfaceOwnerId,
"health_check_source_ip": ri.HealthCheckSourceIp,
"health_check_target_ip": ri.HealthCheckTargetIp,
}
ids = append(ids, ri.RouterInterfaceId)
names = append(names, ri.Name)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("interfaces", s); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"strconv"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSaeApplications() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSaeApplicationsRead,
Schema: map[string]*schema.Schema{
"app_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"field_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"appName", "appIds", "slbIps", "instanceIps"}, false),
},
"field_value": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"namespace_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"order_by": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"running", "instances"}, false),
},
"reverse": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"RUNNING", "STOPPED", "UNKNOWN"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"applications": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"app_description": {
Type: schema.TypeString,
Computed: true,
},
"app_name": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"application_id": {
Type: schema.TypeString,
Computed: true,
},
"command": {
Type: schema.TypeString,
Computed: true,
},
"command_args": {
Type: schema.TypeString,
Computed: true,
},
"config_map_mount_desc": {
Type: schema.TypeString,
Computed: true,
},
"cpu": {
Type: schema.TypeInt,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"repo_name": {
Type: schema.TypeString,
Computed: true,
},
"repo_namespace": {
Type: schema.TypeString,
Computed: true,
},
"repo_origin_type": {
Type: schema.TypeString,
Computed: true,
},
"custom_host_alias": {
Type: schema.TypeString,
Computed: true,
},
"edas_container_version": {
Type: schema.TypeString,
Computed: true,
},
"envs": {
Type: schema.TypeString,
Computed: true,
},
"image_url": {
Type: schema.TypeString,
Computed: true,
},
"jar_start_args": {
Type: schema.TypeString,
Computed: true,
},
"jar_start_options": {
Type: schema.TypeString,
Computed: true,
},
"jdk": {
Type: schema.TypeString,
Computed: true,
},
"liveness": {
Type: schema.TypeString,
Computed: true,
},
"memory": {
Type: schema.TypeInt,
Computed: true,
},
"min_ready_instances": {
Type: schema.TypeInt,
Computed: true,
},
"mount_desc": {
Type: schema.TypeString,
Computed: true,
},
"mount_host": {
Type: schema.TypeString,
Computed: true,
},
"namespace_id": {
Type: schema.TypeString,
Computed: true,
},
"nas_id": {
Type: schema.TypeString,
Computed: true,
},
"oss_ak_id": {
Type: schema.TypeString,
Computed: true,
},
"oss_ak_secret": {
Type: schema.TypeString,
Computed: true,
},
"oss_mount_descs": {
Type: schema.TypeString,
Computed: true,
},
"package_type": {
Type: schema.TypeString,
Computed: true,
},
"package_url": {
Type: schema.TypeString,
Computed: true,
},
"package_version": {
Type: schema.TypeString,
Computed: true,
},
"php_arms_config_location": {
Type: schema.TypeString,
Computed: true,
},
"php_config": {
Type: schema.TypeString,
Computed: true,
},
"php_config_location": {
Type: schema.TypeString,
Computed: true,
},
"post_start": {
Type: schema.TypeString,
Computed: true,
},
"pre_stop": {
Type: schema.TypeString,
Computed: true,
},
"readiness": {
Type: schema.TypeString,
Computed: true,
},
"replicas": {
Type: schema.TypeInt,
Computed: true,
},
"security_group_id": {
Type: schema.TypeString,
Computed: true,
},
"sls_configs": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"termination_grace_period_seconds": {
Type: schema.TypeInt,
Computed: true,
},
"acr_assume_role_arn": {
Type: schema.TypeString,
Computed: true,
},
"timezone": {
Type: schema.TypeString,
Computed: true,
},
"tomcat_config": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"war_start_options": {
Type: schema.TypeString,
Computed: true,
},
"web_container": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudSaeApplicationsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "/pop/v1/sam/app/listApplications"
request := make(map[string]*string)
if v, ok := d.GetOk("app_name"); ok {
request["AppName"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("field_type"); ok {
request["FieldType"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("field_value"); ok {
request["FieldValue"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("namespace_id"); ok {
request["NamespaceId"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("order_by"); ok {
request["OrderBy"] = StringPointer(v.(string))
}
if v, ok := d.GetOkExists("reverse"); ok {
request["Reverse"] = StringPointer(v.(string))
}
request["PageSize"] = StringPointer(strconv.Itoa(PageSizeLarge))
request["CurrentPage"] = StringPointer("1")
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewServerlessClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("GET"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_sae_applications", "GET "+action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", "GET "+action, response))
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return WrapError(fmt.Errorf("%s failed, response: %v", "GET "+action, response))
}
resp, err := jsonpath.Get("$.Data.Applications", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Data.Applications", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["AppId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
currentPage, err := strconv.Atoi(*request["CurrentPage"])
if err != nil {
return WrapError(err)
}
request["CurrentPage"] = StringPointer(strconv.Itoa(currentPage + 1))
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"app_description": object["AppDescription"],
"app_name": object["AppName"],
"id": fmt.Sprint(object["AppId"]),
"application_id": fmt.Sprint(object["AppId"]),
"namespace_id": object["NamespaceId"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["AppId"])
saeService := SaeService{client}
getResp, err := saeService.DescribeSaeApplication(id)
if err != nil {
return WrapError(err)
}
mapping["acr_assume_role_arn"] = getResp["AcrAssumeRoleArn"]
mapping["command"] = getResp["Command"]
mapping["command_args"] = getResp["CommandArgs"]
config_map_mount_desc, _ := convertArrayObjectToJsonString(getResp["ConfigMapMountDesc"])
mapping["config_map_mount_desc"] = config_map_mount_desc
if v, ok := getResp["Cpu"]; ok && fmt.Sprint(v) != "0" {
mapping["cpu"] = formatInt(v)
}
mapping["custom_host_alias"] = getResp["CustomHostAlias"]
mapping["edas_container_version"] = getResp["EdasContainerVersion"]
mapping["envs"] = getResp["Envs"]
mapping["image_url"] = getResp["ImageUrl"]
mapping["jar_start_args"] = getResp["JarStartArgs"]
mapping["jar_start_options"] = getResp["JarStartOptions"]
mapping["jdk"] = getResp["Jdk"]
mapping["liveness"] = getResp["Liveness"]
if v, ok := getResp["Memory"]; ok && fmt.Sprint(v) != "0" {
mapping["memory"] = formatInt(v)
}
if v, ok := getResp["MinReadyInstances"]; ok && fmt.Sprint(v) != "0" {
mapping["min_ready_instances"] = formatInt(v)
}
mapping["mount_desc"] = getResp["MountDesc"]
mapping["mount_host"] = getResp["MountHost"]
mapping["nas_id"] = getResp["NasId"]
mapping["oss_ak_id"] = getResp["OssAkId"]
mapping["oss_ak_secret"] = getResp["OssAkSecret"]
mapping["oss_mount_descs"] = getResp["OssMountDescs"]
mapping["package_type"] = getResp["PackageType"]
mapping["package_url"] = getResp["PackageUrl"]
mapping["package_version"] = getResp["PackageVersion"]
mapping["php_arms_config_location"] = getResp["PhpArmsConfigLocation"]
mapping["php_config"] = getResp["PhpConfig"]
mapping["php_config_location"] = getResp["PhpConfigLocation"]
mapping["post_start"] = getResp["PostStart"]
mapping["pre_stop"] = getResp["PreStop"]
mapping["readiness"] = getResp["Readiness"]
if v, ok := getResp["Replicas"]; ok && fmt.Sprint(v) != "0" {
mapping["replicas"] = formatInt(v)
}
mapping["security_group_id"] = getResp["SecurityGroupId"]
mapping["sls_configs"] = getResp["SlsConfigs"]
if v, ok := getResp["TerminationGracePeriodSeconds"]; ok && fmt.Sprint(v) != "0" {
mapping["termination_grace_period_seconds"] = formatInt(v)
}
mapping["timezone"] = getResp["Timezone"]
mapping["tomcat_config"] = getResp["TomcatConfig"]
mapping["vswitch_id"] = getResp["VSwitchId"]
mapping["vpc_id"] = getResp["VpcId"]
mapping["war_start_options"] = getResp["WarStartOptions"]
mapping["web_container"] = getResp["WebContainer"]
saeService = SaeService{client}
if imageUrl, exist := getResp["ImageUrl"]; exist {
applicationImageResp, err := saeService.DescribeApplicationImage(id, imageUrl.(string))
if err != nil {
return WrapError(err)
}
mapping["region_id"] = applicationImageResp["RegionId"]
mapping["repo_name"] = applicationImageResp["RepoName"]
mapping["repo_namespace"] = applicationImageResp["RepoNamespace"]
mapping["repo_origin_type"] = applicationImageResp["RepoOriginType"]
}
getRespStatus, err := saeService.DescribeApplicationStatus(id)
if err != nil {
return WrapError(err)
}
if statusOk && status != "" && status != getRespStatus["CurrentStatus"].(string) {
continue
}
mapping["create_time"] = getRespStatus["CreateTime"]
mapping["status"] = getRespStatus["CurrentStatus"]
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("applications", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
//
import (
"encoding/json"
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSaeConfigMaps() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSaeConfigMapsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"namespace_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"maps": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"config_map_id": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"data": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"namespace_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudSaeConfigMapsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "/pop/v1/sam/configmap/listNamespacedConfigMaps"
request := make(map[string]*string)
request["NamespaceId"] = StringPointer(d.Get("namespace_id").(string))
var objects []map[string]interface{}
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
nameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewServerlessClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("GET"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_sae_config_maps", action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return WrapError(fmt.Errorf("%s failed, response: %v", "POST "+action, response))
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.Data.ConfigMaps", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Data.ConfigMaps", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if nameRegex != nil && !nameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ConfigMapId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["ConfigMapId"]),
"config_map_id": fmt.Sprint(object["ConfigMapId"]),
"create_time": fmt.Sprint(object["CreateTime"]),
"description": object["Description"],
"name": object["Name"],
"namespace_id": object["NamespaceId"],
}
serialized, err := json.Marshal(object["Data"])
if err != nil {
return WrapError(err)
}
mapping["data"] = string(serialized)
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("maps", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudSaeIngresses() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSaeIngressesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"namespace_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ingresses": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cert_id": {
Type: schema.TypeString,
Computed: true,
},
"default_rule": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"ingress_id": {
Type: schema.TypeString,
Computed: true,
},
"listener_port": {
Type: schema.TypeInt,
Computed: true,
},
"namespace_id": {
Type: schema.TypeString,
Computed: true,
},
"slb_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudSaeIngressesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "/pop/v1/sam/ingress/IngressList"
request := make(map[string]*string)
request["NamespaceId"] = StringPointer(d.Get("namespace_id").(string))
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewServerlessClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("GET"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_sae_ingresses", action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return WrapError(fmt.Errorf("%s failed, response: %v", "AlicloudSaeIngressesRead", response))
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", "GET "+action, response))
}
resp, err := jsonpath.Get("$.Data.IngressList", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Data.IngressList", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Id"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"cert_id": object["CertId"],
"description": object["Description"],
"id": fmt.Sprint(object["Id"]),
"ingress_id": fmt.Sprint(object["Id"]),
"listener_port": formatInt(object["ListenerPort"]),
"namespace_id": object["NamespaceId"],
"slb_id": object["SlbId"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["Id"])
saeService := SaeService{client}
getResp, err := saeService.DescribeSaeIngress(id)
if err != nil {
return WrapError(err)
}
mapping["default_rule"] = getResp["DefaultRule"]
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("ingresses", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudSaeInstanceSpecifications() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSaeInstanceSpecificationsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"specifications": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cpu": {
Type: schema.TypeInt,
Computed: true,
},
"enable": {
Type: schema.TypeBool,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"instance_specification_id": {
Type: schema.TypeString,
Computed: true,
},
"memory": {
Type: schema.TypeInt,
Computed: true,
},
"spec_info": {
Type: schema.TypeString,
Computed: true,
},
"version": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudSaeInstanceSpecificationsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "/pop/v1/paas/quota/instanceSpecifications"
request := make(map[string]*string)
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewServerlessClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("GET"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_sae_instance_specifications", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.body.Data", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.body.Data", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Id"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"cpu": formatInt(object["Cpu"]),
"enable": object["Enable"],
"id": fmt.Sprint(object["Id"]),
"instance_specification_id": fmt.Sprint(object["Id"]),
"memory": formatInt(object["Memory"]),
"spec_info": object["SpecInfo"],
"version": formatInt(object["Version"]),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("specifications", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"strconv"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSaeNamespaces() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSaeNamespacesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"namespaces": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"namespace_description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"namespace_id": {
Type: schema.TypeString,
Computed: true,
},
"namespace_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudSaeNamespacesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "/pop/v1/paas/namespaces"
request := make(map[string]*string)
request["PageSize"] = StringPointer(strconv.Itoa(PageSizeLarge))
request["CurrentPage"] = StringPointer("1")
var objects []map[string]interface{}
var namespaceNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
namespaceNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewServerlessClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("GET"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_sae_namespaces", action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return WrapError(fmt.Errorf("%s failed, response: %v", "AlicloudSaeNamespacesRead", response))
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
resp, err := jsonpath.Get("$.Data.Namespaces", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Data.Namespaces", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if namespaceNameRegex != nil && !namespaceNameRegex.MatchString(fmt.Sprint(item["NamespaceName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["NamespaceId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
currntPage, err := strconv.Atoi(*request["CurrentPage"])
if err != nil {
return WrapError(err)
}
request["CurrentPage"] = StringPointer(strconv.Itoa(currntPage + 1))
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"namespace_description": object["NamespaceDescription"],
"id": fmt.Sprint(object["NamespaceId"]),
"namespace_id": fmt.Sprint(object["NamespaceId"]),
"namespace_name": object["NamespaceName"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["NamespaceName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("namespaces", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSaeService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSaeServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudSaeServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("SaeServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
action := "OpenSaeService"
request := map[string]*string{}
conn, err := meta.(*connectivity.AliyunClient).NewTeaRoaCommonClient(connectivity.OpenSaeService)
if err != nil {
return WrapError(err)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequestWithAction(StringPointer(action), StringPointer("2019-05-06"), nil, StringPointer("POST"), StringPointer("AK"), String("/service/open"), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"QPS Limit Exceeded"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
addDebug(action, response, nil)
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ORDER.OPEND", "SYSTEM.SALE_VALIDATE_NO_SPECIFIC_CODE_FAILED"}) {
d.SetId("SaeServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_sae_service", action, AlibabaCloudSdkGoERROR)
}
d.SetId("SaeServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/smartag"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSagAcls() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSagAclsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.ValidateRegexp,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"acls": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudSagAclsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := smartag.CreateDescribeACLsRequest()
var allAcls []smartag.Acl
request.RegionId = client.RegionId
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
for {
raw, err := client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.DescribeACLs(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_sag_acls", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*smartag.DescribeACLsResponse)
acls := response.Acls.Acl
for _, acl := range acls {
allAcls = append(allAcls, acl)
}
if len(acls) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
var filteredSagAclsTemp []smartag.Acl
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
for _, acl := range allAcls {
if v, ok := d.GetOk("id"); ok && v.(string) != "" && acl.AclId != v.(string) {
continue
}
if v, ok := d.GetOk("name_regex"); ok && v.(string) != "" {
r := regexp.MustCompile(v.(string))
if !r.MatchString(acl.Name) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[acl.AclId]; !ok {
continue
}
}
filteredSagAclsTemp = append(filteredSagAclsTemp, acl)
}
return sagAclsDescriptionAttributes(d, filteredSagAclsTemp, meta)
}
func sagAclsDescriptionAttributes(d *schema.ResourceData, acls []smartag.Acl, meta interface{}) error {
var ids []string
var names []string
var s []map[string]interface{}
for _, acl := range acls {
mapping := map[string]interface{}{
"id": acl.AclId,
"name": acl.Name,
}
names = append(names, acl.Name)
ids = append(ids, acl.AclId)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("acls", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudScdnDomains() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudScdnDomainsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"check_failed", "checking", "configure_failed", "configuring", "offline", "online"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"domains": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cert_infos": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cert_name": {
Type: schema.TypeString,
Computed: true,
},
"cert_type": {
Type: schema.TypeString,
Computed: true,
},
"ssl_protocol": {
Type: schema.TypeString,
Computed: true,
},
"ssl_pub": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"cname": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"domain_name": {
Type: schema.TypeString,
Computed: true,
},
"gmt_modified": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"sources": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"content": {
Type: schema.TypeString,
Computed: true,
},
"enabled": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeInt,
Computed: true,
},
"priority": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudScdnDomainsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeScdnUserDomains"
request := make(map[string]interface{})
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("status"); ok {
request["DomainStatus"] = v
}
request["PageSize"] = PageSizeXLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var domainNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
domainNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewScdnClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-11-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_scdn_domains", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Domains.PageData", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Domains.PageData", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if domainNameRegex != nil && !domainNameRegex.MatchString(fmt.Sprint(item["DomainName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DomainName"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"cname": object["Cname"],
"create_time": object["GmtCreated"],
"description": object["Description"],
"id": fmt.Sprint(object["DomainName"]),
"domain_name": fmt.Sprint(object["DomainName"]),
"gmt_modified": object["GmtModified"],
"resource_group_id": object["ResourceGroupId"],
"status": object["DomainStatus"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["DomainName"])
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["DomainName"])
scdnService := ScdnService{client}
getResp1, err := scdnService.DescribeScdnDomainCertificateInfo(id)
if err != nil {
return WrapError(err)
}
if certInfosMap, ok := getResp1["CertInfos"].(map[string]interface{}); ok && certInfosMap != nil {
if certInfoList, ok := certInfosMap["CertInfo"]; ok && certInfoList != nil {
certInfosMaps := make([]map[string]interface{}, 0)
for _, certInfoListItem := range certInfoList.([]interface{}) {
if certInfoListItemMap, ok := certInfoListItem.(map[string]interface{}); ok {
certInfoListItemMap["cert_name"] = certInfoListItemMap["CertName"]
certInfoListItemMap["cert_type"] = certInfoListItemMap["CertType"]
certInfoListItemMap["ssl_protocol"] = certInfoListItemMap["SslProtocol"]
certInfoListItemMap["ssl_pub"] = certInfoListItemMap["SslPub"]
certInfosMaps = append(certInfosMaps, certInfoListItemMap)
}
}
mapping["cert_infos"] = certInfosMaps
}
}
getResp4, err := scdnService.DescribeScdnDomain(id)
if err != nil {
return WrapError(err)
}
if v, ok := getResp4["Sources"].(map[string]interface{})["Source"].([]interface{}); ok {
source := make([]map[string]interface{}, 0)
for _, val := range v {
item := val.(map[string]interface{})
temp := map[string]interface{}{
"content": item["Content"],
"enabled": item["Enabled"],
"port": item["Port"],
"priority": item["Priority"],
"type": item["Type"],
}
source = append(source, temp)
}
mapping["sources"] = source
}
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("domains", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudSddpConfigs() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSddpConfigsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"lang": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"zh", "en"}, false),
Default: "zh",
Optional: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"configs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"code": {
Type: schema.TypeString,
Computed: true,
},
"config_id": {
Type: schema.TypeString,
Computed: true,
},
"default_value": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"value": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudSddpConfigsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeConfigs"
request := make(map[string]interface{})
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewSddpClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-03"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_sddp_configs", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$", response)
}
var configlistMap map[string]interface{}
if _, ok := resp.(map[string]interface{}); ok {
configlistMap = resp.(map[string]interface{})
}
result, _ := configlistMap["ConfigList"].([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Code"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := make(map[string]interface{}, 0)
mapping["code"] = object["Code"]
mapping["config_id"] = object["Id"]
mapping["default_value"] = object["DefaultValue"]
mapping["description"] = object["Description"]
mapping["value"] = object["Value"]
ids = append(ids, fmt.Sprint(mapping["code"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("configs", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"strconv"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudSddpInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSddpInstancesRead,
Schema: map[string]*schema.Schema{
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"authed": {
Type: schema.TypeBool,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_num": {
Type: schema.TypeString,
Computed: true,
},
"odps_set": {
Type: schema.TypeBool,
Computed: true,
},
"oss_bucket_set": {
Type: schema.TypeBool,
Computed: true,
},
"oss_size": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"rds_set": {
Type: schema.TypeBool,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudSddpInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeUserStatus"
request := make(map[string]interface{})
var response map[string]interface{}
conn, err := client.NewSddpClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-03"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_sddp_instances", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.UserStatus", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.UserStatus", response)
}
userstatus := resp.(map[string]interface{})
s := make([]map[string]interface{}, 0)
mapping := map[string]interface{}{
"authed": userstatus["Authed"],
"id": fmt.Sprint(userstatus["InstanceId"]),
"instance_id": fmt.Sprint(userstatus["InstanceId"]),
"instance_num": fmt.Sprint(userstatus["InstanceNum"]),
"odps_set": userstatus["OdpsSet"],
"oss_bucket_set": userstatus["OssBucketSet"],
"oss_size": fmt.Sprint(userstatus["OssSize"]),
"payment_type": convertSddpInstancePaymentTypeToStandard(userstatus["ChargeType"]),
"rds_set": userstatus["RdsSet"],
"status": fmt.Sprint(userstatus["InstanceStatus"]),
}
s = append(s, mapping)
d.SetId(strconv.FormatInt(time.Now().Unix(), 16))
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSddpRules() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSddpRulesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"risk_level_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"custom_type": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"product_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"1", "2", "5"}, false),
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"0", "1"}, false),
},
"rule_type": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3}),
},
"category": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IntInSlice([]int{0, 2}),
},
"warn_level": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3}),
},
"content_category": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"category": {
Type: schema.TypeInt,
Computed: true,
},
"category_name": {
Type: schema.TypeString,
Computed: true,
},
"content": {
Type: schema.TypeString,
Computed: true,
},
"content_category": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"custom_type": {
Type: schema.TypeInt,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"display_name": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"gmt_modified": {
Type: schema.TypeString,
Computed: true,
},
"login_name": {
Type: schema.TypeString,
Computed: true,
},
"major_key": {
Type: schema.TypeString,
Computed: true,
},
"product_code": {
Type: schema.TypeString,
Computed: true,
},
"product_id": {
Type: schema.TypeString,
Computed: true,
},
"risk_level_id": {
Type: schema.TypeString,
Computed: true,
},
"risk_level_name": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"rule_id": {
Type: schema.TypeString,
Computed: true,
},
"stat_express": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeInt,
Computed: true,
},
"target": {
Type: schema.TypeString,
Computed: true,
},
"user_id": {
Type: schema.TypeString,
Computed: true,
},
"warn_level": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudSddpRulesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeRules"
request := make(map[string]interface{})
if v, ok := d.GetOk("category"); ok {
request["Category"] = v
}
if v, ok := d.GetOk("content_category"); ok {
request["ContentCategory"] = v
}
if v, ok := d.GetOk("custom_type"); ok {
request["CustomType"] = v
}
if v, ok := d.GetOk("name"); ok {
request["Name"] = v
}
if v, ok := d.GetOk("product_id"); ok {
request["ProductId"] = v
}
if v, ok := d.GetOk("risk_level_id"); ok {
request["RiskLevelId"] = v
}
if v, ok := d.GetOk("rule_type"); ok {
request["RuleType"] = v
}
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
if v, ok := d.GetOk("warn_level"); ok {
request["WarnLevel"] = v
}
request["PageSize"] = PageSizeLarge
request["CurrentPage"] = 1
var objects []map[string]interface{}
var ruleNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
ruleNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewSddpClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-03"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_sddp_rules", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Items", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Items", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if ruleNameRegex != nil && !ruleNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Id"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["CurrentPage"] = request["CurrentPage"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"category": formatInt(object["Category"]),
"category_name": object["CategoryName"],
"content": object["Content"],
"content_category": object["ContentCategory"],
"custom_type": formatInt(object["CustomType"]),
"description": object["Description"],
"display_name": object["DisplayName"],
"gmt_modified": fmt.Sprint(object["GmtModified"]),
"name": object["Name"],
"login_name": object["LoginName"],
"major_key": object["MajorKey"],
"product_code": object["ProductCode"],
"product_id": fmt.Sprint(object["ProductId"]),
"risk_level_id": fmt.Sprint(object["RiskLevelId"]),
"risk_level_name": object["RiskLevelName"],
"id": fmt.Sprint(object["Id"]),
"rule_id": fmt.Sprint(object["Id"]),
"stat_express": object["StatExpress"],
"status": formatInt(object["Status"]),
"target": object["Target"],
"user_id": fmt.Sprint(object["UserId"]),
"warn_level": formatInt(object["WarnLevel"]),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
names = append(names, object["name"])
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("rules", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSecurityCenterGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSecurityCenterGroupsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"group_flag": {
Type: schema.TypeInt,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"group_id": {
Type: schema.TypeString,
Computed: true,
},
"group_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudSecurityCenterGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeAllGroups"
request := make(map[string]interface{})
var objects []map[string]interface{}
var groupNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
groupNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewSasClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-03"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_security_center_groups", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Groups", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Groups", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if groupNameRegex != nil && !groupNameRegex.MatchString(fmt.Sprint(item["GroupName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["GroupId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"group_flag": formatInt(object["GroupFlag"]),
"id": fmt.Sprint(object["GroupId"]),
"group_id": fmt.Sprint(object["GroupId"]),
"group_name": object["GroupName"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["GroupName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"strconv"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSecurityGroupRules() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSecurityGroupRulesRead,
Schema: map[string]*schema.Schema{
"group_id": {
Type: schema.TypeString,
Required: true,
},
"nic_type": {
Type: schema.TypeString,
Optional: true,
// must be one of GroupRuleInternet, GroupRuleIntranet
ValidateFunc: validation.StringInSlice([]string{"internet", "intranet"}, false),
},
"direction": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"ingress", "egress"}, false),
},
"ip_protocol": {
Type: schema.TypeString,
Optional: true,
// must be one of Tcp, Udp, Icmp, Gre, All
ValidateFunc: validation.StringInSlice([]string{
string(Tcp),
string(Udp),
string(Icmp),
string(Gre),
string(All),
}, false),
},
"policy": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"accept", "drop"}, false),
},
"rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ip_protocol": {
Type: schema.TypeString,
Computed: true,
},
"port_range": {
Type: schema.TypeString,
Computed: true,
},
"source_cidr_ip": {
Type: schema.TypeString,
Computed: true,
},
"source_group_id": {
Type: schema.TypeString,
Computed: true,
},
"source_group_owner_account": {
Type: schema.TypeString,
Computed: true,
},
"dest_cidr_ip": {
Type: schema.TypeString,
Computed: true,
},
"dest_group_id": {
Type: schema.TypeString,
Computed: true,
},
"dest_group_owner_account": {
Type: schema.TypeString,
Computed: true,
},
"policy": {
Type: schema.TypeString,
Computed: true,
},
"nic_type": {
Type: schema.TypeString,
Computed: true,
},
"priority": {
Type: schema.TypeInt,
Computed: true,
},
"direction": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"group_name": {
Type: schema.TypeString,
Computed: true,
},
"group_desc": {
Type: schema.TypeString,
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func dataSourceAlicloudSecurityGroupRulesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
req := ecs.CreateDescribeSecurityGroupAttributeRequest()
req.RegionId = client.RegionId
req.SecurityGroupId = d.Get("group_id").(string)
req.NicType = d.Get("nic_type").(string)
req.Direction = d.Get("direction").(string)
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeSecurityGroupAttribute(req)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "security_group_rules", req.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(req.GetActionName(), raw, req.RpcRequest, req)
attr, _ := raw.(*ecs.DescribeSecurityGroupAttributeResponse)
var rules []map[string]interface{}
if attr != nil {
for _, item := range attr.Permissions.Permission {
if v, ok := d.GetOk("ip_protocol"); ok && strings.ToLower(string(item.IpProtocol)) != v.(string) {
continue
}
if v, ok := d.GetOk("policy"); ok && strings.ToLower(string(item.Policy)) != v.(string) {
continue
}
mapping := map[string]interface{}{
"ip_protocol": strings.ToLower(string(item.IpProtocol)),
"port_range": item.PortRange,
"source_cidr_ip": item.SourceCidrIp,
"source_group_id": item.SourceGroupId,
"source_group_owner_account": item.SourceGroupOwnerAccount,
"dest_cidr_ip": item.DestCidrIp,
"dest_group_id": item.DestGroupId,
"dest_group_owner_account": item.DestGroupOwnerAccount,
"policy": strings.ToLower(string(item.Policy)),
"nic_type": item.NicType,
"direction": item.Direction,
"description": item.Description,
}
pri, err := strconv.Atoi(item.Priority)
if err != nil {
return WrapError(err)
}
mapping["priority"] = pri
rules = append(rules, mapping)
}
if err := d.Set("group_name", attr.SecurityGroupName); err != nil {
return WrapError(err)
}
if err := d.Set("group_desc", attr.Description); err != nil {
return WrapError(err)
}
}
d.SetId(d.Get("group_id").(string))
if err := d.Set("rules", rules); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), rules)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudSecurityGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSecurityGroupsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"page_number": {
Type: schema.TypeInt,
Optional: true,
},
"page_size": {
Type: schema.TypeInt,
Optional: true,
Default: 50,
},
"tags": tagsSchema(),
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
// Computed values
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"security_group_type": {
Type: schema.TypeString,
Computed: true,
},
"inner_access": {
Type: schema.TypeBool,
Computed: true,
},
"creation_time": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"total_count": {
Type: schema.TypeInt,
Computed: true,
},
},
}
}
func dataSourceAlicloudSecurityGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeSecurityGroups"
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
request := make(map[string]interface{})
if v, ok := d.GetOk("page_number"); ok && v.(int) > 0 {
request["PageNumber"] = v.(int)
} else {
request["PageNumber"] = 1
}
if v, ok := d.GetOk("page_size"); ok && v.(int) > 0 {
request["PageSize"] = v.(int)
} else {
request["PageSize"] = PageSizeLarge
}
var objects []interface{}
var securityGroupNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
securityGroupNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
if v, ok := d.GetOk("tags"); ok {
tags := make([]map[string]interface{}, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, map[string]interface{}{
"Key": key,
"Value": value.(string),
})
}
request["Tag"] = tags
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("vpc_id"); ok {
request["VpcId"] = v
}
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("security_group_name"); ok {
request["SecurityGroupName"] = v
}
var response map[string]interface{}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
resp, err := jsonpath.Get("$.SecurityGroups.SecurityGroup", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.SecurityGroups.SecurityGroup", response)
}
result, _ := resp.([]interface{})
if isPagingRequest(d) {
objects = result
break
}
for _, v := range result {
item := v.(map[string]interface{})
if securityGroupNameRegex != nil {
if !securityGroupNameRegex.MatchString(fmt.Sprint(item["SecurityGroupName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["SecurityGroupId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, v := range objects {
object := v.(map[string]interface{})
mapping := map[string]interface{}{
"id": object["SecurityGroupId"],
"name": object["SecurityGroupName"],
"description": object["Description"],
"vpc_id": object["VpcId"],
"resource_group_id": object["ResourceGroupId"],
"security_group_type": object["SecurityGroupType"],
"creation_time": object["CreationTime"],
}
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags.Tag", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["TagKey"].(string)
value := t.(map[string]interface{})["TagValue"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
if d.Get("enable_details").(bool) {
ecsService := EcsService{client}
id := fmt.Sprint(object["SecurityGroupId"])
getResp, err := ecsService.DescribeSecurityGroupAttribute(id)
if err != nil {
return WrapError(err)
}
mapping["inner_access"] = getResp["InnerAccessPolicy"] == string(GroupInnerAccept)
}
ids = append(ids, fmt.Sprint(object["SecurityGroupId"]))
names = append(names, object["SecurityGroupName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if err := d.Set("total_count", formatInt(response["TotalCount"])); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudServiceMeshServiceMeshes() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudServiceMeshServiceMeshesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"running", "initial"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"meshes": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"clusters": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"endpoints": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"intranet_api_server_endpoint": {
Type: schema.TypeString,
Computed: true,
},
"intranet_pilot_endpoint": {
Type: schema.TypeString,
Computed: true,
},
"public_api_server_endpoint": {
Type: schema.TypeString,
Computed: true,
},
"public_pilot_endpoint": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"error_message": {
Type: schema.TypeString,
Computed: true,
},
"load_balancer": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"api_server_loadbalancer_id": {
Type: schema.TypeString,
Computed: true,
},
"api_server_public_eip": {
Type: schema.TypeBool,
Computed: true,
},
"pilot_public_eip": {
Type: schema.TypeBool,
Computed: true,
},
"pilot_public_loadbalancer_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"edition": {
Type: schema.TypeString,
Computed: true,
},
"mesh_config": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"access_log": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enabled": {
Type: schema.TypeBool,
Computed: true,
},
},
},
},
"audit": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enabled": {
Type: schema.TypeBool,
Computed: true,
},
"project": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"customized_zipkin": {
Type: schema.TypeBool,
Computed: true,
},
"enable_locality_lb": {
Type: schema.TypeBool,
Computed: true,
},
"include_ip_ranges": {
Type: schema.TypeString,
Computed: true,
},
"kiali": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enabled": {
Type: schema.TypeBool,
Computed: true,
},
"url": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"opa": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enabled": {
Type: schema.TypeBool,
Computed: true,
},
"limit_cpu": {
Type: schema.TypeString,
Computed: true,
},
"limit_memory": {
Type: schema.TypeString,
Computed: true,
},
"log_level": {
Type: schema.TypeString,
Computed: true,
},
"request_cpu": {
Type: schema.TypeString,
Computed: true,
},
"request_memory": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"outbound_traffic_policy": {
Type: schema.TypeString,
Computed: true,
},
"pilot": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"http10_enabled": {
Type: schema.TypeBool,
Computed: true,
},
"trace_sampling": {
Type: schema.TypeFloat,
Computed: true,
},
},
},
},
"prometheus": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"external_url": {
Type: schema.TypeString,
Computed: true,
},
"use_external": {
Type: schema.TypeBool,
Computed: true,
},
},
},
},
"proxy": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cluster_domain": {
Type: schema.TypeString,
Computed: true,
},
"limit_cpu": {
Type: schema.TypeString,
Computed: true,
},
"limit_memory": {
Type: schema.TypeString,
Computed: true,
},
"request_cpu": {
Type: schema.TypeString,
Computed: true,
},
"request_memory": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"sidecar_injector": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"auto_injection_policy_enabled": {
Type: schema.TypeBool,
Computed: true,
},
"enable_namespaces_by_default": {
Type: schema.TypeBool,
Computed: true,
},
"init_cni_configuration": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enabled": {
Type: schema.TypeBool,
Computed: true,
},
"exclude_namespaces": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"limit_cpu": {
Type: schema.TypeString,
Computed: true,
},
"limit_memory": {
Type: schema.TypeString,
Computed: true,
},
"request_cpu": {
Type: schema.TypeString,
Computed: true,
},
"request_memory": {
Type: schema.TypeString,
Computed: true,
},
"sidecar_injector_webhook_as_yaml": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"telemetry": {
Type: schema.TypeBool,
Computed: true,
},
"tracing": {
Type: schema.TypeBool,
Computed: true,
},
},
},
},
"network": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"security_group_id": {
Type: schema.TypeString,
Computed: true,
},
"vswitche_list": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"service_mesh_id": {
Type: schema.TypeString,
Computed: true,
},
"service_mesh_name": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"version": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudServiceMeshServiceMeshesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeServiceMeshes"
request := make(map[string]interface{})
var objects []map[string]interface{}
var serviceMeshNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
serviceMeshNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewServicemeshClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2020-01-11"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_service_mesh_service_meshes", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.ServiceMeshes", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.ServiceMeshes", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if serviceMeshNameRegex != nil && !serviceMeshNameRegex.MatchString(fmt.Sprint(item["ServiceMeshInfo"].(map[string]interface{})["Name"])) {
continue
}
if len(idsMap) > 0 {
id := item["ServiceMeshInfo"].(map[string]interface{})["ServiceMeshId"]
if _, ok := idsMap[fmt.Sprint(id)]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["ServiceMeshInfo"].(map[string]interface{})["State"].(string) {
continue
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"clusters": object["Clusters"],
}
if objectArg, ok := object["ServiceMeshInfo"].(map[string]interface{}); ok {
mapping["create_time"] = objectArg["CreationTime"]
mapping["error_message"] = objectArg["ErrorMessage"]
mapping["id"] = fmt.Sprint(objectArg["ServiceMeshId"])
mapping["service_mesh_id"] = fmt.Sprint(objectArg["ServiceMeshId"])
mapping["service_mesh_name"] = objectArg["Name"]
mapping["status"] = objectArg["State"]
mapping["version"] = objectArg["Version"]
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["ServiceMeshInfo"].(map[string]interface{})["Name"])
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
s = append(s, mapping)
continue
}
id := fmt.Sprint(object["ServiceMeshInfo"].(map[string]interface{})["ServiceMeshId"])
servicemeshService := ServicemeshService{client}
getResp, err := servicemeshService.DescribeServiceMeshServiceMesh(id)
if err != nil {
return WrapError(err)
}
endpointsSli := make([]map[string]interface{}, 0)
if endpoints, ok := getResp["Endpoints"]; ok {
endpointsMap := make(map[string]interface{})
if endpointsArg, ok := endpoints.(map[string]interface{}); ok && len(endpointsArg) > 0 {
endpointsMap["intranet_pilot_endpoint"] = endpointsArg["IntranetPilotEndpoint"]
endpointsMap["public_pilot_endpoint"] = endpointsArg["PublicPilotEndpoint"]
endpointsMap["intranet_api_server_endpoint"] = endpointsArg["IntranetApiServerEndpoint"]
endpointsMap["public_api_server_endpoint"] = endpointsArg["PublicApiServerEndpoint"]
endpointsSli = append(endpointsSli, endpointsMap)
mapping["endpoints"] = endpointsSli
}
}
if spec, ok := getResp["Spec"]; ok {
if specArg, ok := spec.(map[string]interface{}); ok && len(specArg) > 0 {
meshConfigSli := make([]map[string]interface{}, 0)
if meshConfig, ok := specArg["MeshConfig"]; ok {
meshConfigMap := make(map[string]interface{})
if meshConfigArg, ok := meshConfig.(map[string]interface{}); ok && len(meshConfigArg) > 0 {
accessLogSli := make([]map[string]interface{}, 0)
if accessLog, ok := meshConfigArg["AccessLog"]; ok {
if accessLogArg, ok := accessLog.(map[string]interface{}); ok && len(accessLogArg) > 0 {
accessLogMap := make(map[string]interface{})
accessLogMap["enabled"] = accessLogArg["Enabled"]
accessLogSli = append(accessLogSli, accessLogMap)
}
}
meshConfigMap["access_log"] = accessLogSli
auditSli := make([]map[string]interface{}, 0)
if audit, ok := meshConfigArg["Audit"]; ok {
auditMap := make(map[string]interface{})
if auditArg, ok := audit.(map[string]interface{}); ok && len(auditArg) > 0 {
auditMap["enabled"] = auditArg["Enabled"]
auditMap["project"] = auditArg["Project"]
auditSli = append(auditSli, auditMap)
meshConfigMap["audit"] = auditSli
}
}
mapping["edition"] = meshConfigArg["Profile"]
meshConfigMap["customized_zipkin"] = meshConfigArg["CustomizedZipkin"]
meshConfigMap["enable_locality_lb"] = meshConfigArg["EnableLocalityLB"]
meshConfigMap["include_ip_ranges"] = meshConfigArg["IncludeIPRanges"]
kialiSli := make([]map[string]interface{}, 0)
if kiali, ok := meshConfigArg["Kiali"]; ok {
if kialiArg, ok := kiali.(map[string]interface{}); ok && len(kialiArg) > 0 {
kialiMap := make(map[string]interface{})
kialiMap["enabled"] = kialiArg["Enabled"]
if v, ok := kialiArg["Url"]; ok {
kialiMap["url"] = v
}
kialiSli = append(kialiSli, kialiMap)
}
}
meshConfigMap["kiali"] = kialiSli
opaSli := make([]map[string]interface{}, 0)
if opa, ok := meshConfigArg["OPA"]; ok {
opaMap := make(map[string]interface{})
if opaArg, ok := opa.(map[string]interface{}); ok && len(opaArg) > 0 {
opaMap["enabled"] = opaArg["Enabled"]
opaMap["limit_cpu"] = opaArg["LimitCPU"]
opaMap["limit_memory"] = opaArg["LimitMemory"]
opaMap["log_level"] = opaArg["LogLevel"]
opaMap["request_cpu"] = opaArg["RequestCPU"]
opaMap["request_memory"] = opaArg["RequestMemory"]
}
opaSli = append(opaSli, opaMap)
}
meshConfigMap["opa"] = opaSli
meshConfigMap["outbound_traffic_policy"] = meshConfigArg["OutboundTrafficPolicy"]
pilotSli := make([]map[string]interface{}, 0)
if pilot := meshConfigArg["Pilot"]; ok {
if pilotArg, ok := pilot.(map[string]interface{}); ok && len(pilotArg) > 0 {
pilotMap := make(map[string]interface{})
pilotMap["http10_enabled"] = pilotArg["Http10Enabled"]
pilotMap["trace_sampling"] = pilotArg["TraceSampling"]
pilotSli = append(pilotSli, pilotMap)
}
}
meshConfigMap["pilot"] = pilotSli
prometheusSli := make([]map[string]interface{}, 0)
if prometheus, ok := meshConfigArg["Prometheus"]; ok {
if prometheusArg, ok := prometheus.(map[string]interface{}); ok && len(prometheusArg) > 0 {
prometheusMap := make(map[string]interface{})
prometheusMap["external_url"] = prometheusArg["ExternalUrl"]
prometheusMap["use_external"] = prometheusArg["UseExternal"]
prometheusSli = append(prometheusSli, prometheusMap)
}
}
meshConfigMap["prometheus"] = prometheusSli
proxySli := make([]map[string]interface{}, 0)
if proxy, ok := meshConfigArg["Proxy"]; ok {
if proxyArg, ok := proxy.(map[string]interface{}); ok && len(proxyArg) > 0 {
proxyMap := make(map[string]interface{})
proxyMap["cluster_domain"] = proxyArg["ClusterDomain"]
proxyMap["limit_cpu"] = proxyArg["LimitCPU"]
proxyMap["limit_memory"] = proxyArg["LimitMemory"]
proxyMap["request_cpu"] = proxyArg["RequestCPU"]
proxyMap["request_memory"] = proxyArg["RequestMemory"]
proxySli = append(proxySli, proxyMap)
}
}
meshConfigMap["proxy"] = proxySli
sidecarInjectorSli := make([]map[string]interface{}, 0)
if sidecarInjector, ok := meshConfigArg["SidecarInjector"]; ok {
if sidecarInjectorArg, ok := sidecarInjector.(map[string]interface{}); ok && len(sidecarInjectorArg) > 0 {
sidecarInjectorMap := make(map[string]interface{})
sidecarInjectorMap["auto_injection_policy_enabled"] = sidecarInjectorArg["AutoInjectionPolicyEnabled"]
sidecarInjectorMap["enable_namespaces_by_default"] = sidecarInjectorArg["EnableNamespacesByDefault"]
initCNIConfigurationSli := make([]map[string]interface{}, 0)
if initCNIConfiguration, ok := sidecarInjectorArg["InitCNIConfiguration"]; ok {
if initCNIConfigurationArg, ok := initCNIConfiguration.(map[string]interface{}); ok && len(initCNIConfigurationArg) > 0 {
initCNIConfigurationMap := make(map[string]interface{})
initCNIConfigurationMap["enabled"] = initCNIConfigurationArg["Enabled"]
initCNIConfigurationMap["exclude_namespaces"] = initCNIConfigurationArg["ExcludeNamespaces"]
initCNIConfigurationSli = append(initCNIConfigurationSli, initCNIConfigurationMap)
}
}
sidecarInjectorMap["init_cni_configuration"] = initCNIConfigurationSli
sidecarInjectorMap["limit_cpu"] = sidecarInjectorArg["LimitCPU"]
sidecarInjectorMap["limit_memory"] = sidecarInjectorArg["LimitMemory"]
sidecarInjectorMap["request_cpu"] = sidecarInjectorArg["RequestCPU"]
sidecarInjectorMap["request_memory"] = sidecarInjectorArg["RequestMemory"]
if v, ok := sidecarInjectorArg["SidecarInjectorWebhookAsYaml"]; ok {
sidecarInjectorMap["sidecar_injector_webhook_as_yaml"] = v
}
sidecarInjectorSli = append(sidecarInjectorSli, sidecarInjectorMap)
}
}
meshConfigMap["sidecar_injector"] = sidecarInjectorSli
meshConfigMap["telemetry"] = meshConfigArg["Telemetry"]
meshConfigMap["tracing"] = meshConfigArg["Tracing"]
meshConfigSli = append(meshConfigSli, meshConfigMap)
}
}
mapping["mesh_config"] = meshConfigSli
loadBalancerSli := make([]map[string]interface{}, 0)
if loadBalancer, ok := specArg["LoadBalancer"]; ok {
if loadBalancerArg, ok := loadBalancer.(map[string]interface{}); ok && len(loadBalancerArg) > 0 {
loadBalancerMap := make(map[string]interface{})
loadBalancerMap["pilot_public_eip"] = loadBalancerArg["PilotPublicEip"]
loadBalancerMap["pilot_public_loadbalancer_id"] = loadBalancerArg["PilotPublicLoadbalancerId"]
loadBalancerMap["api_server_loadbalancer_id"] = loadBalancerArg["ApiServerLoadbalancerId"]
loadBalancerMap["api_server_public_eip"] = loadBalancerArg["ApiServerPublicEip"]
loadBalancerSli = append(loadBalancerSli, loadBalancerMap)
}
}
mapping["load_balancer"] = loadBalancerSli
networkSli := make([]map[string]interface{}, 0)
if network, ok := specArg["Network"]; ok {
if networkArg, ok := network.(map[string]interface{}); ok && len(networkArg) > 0 {
networkMap := make(map[string]interface{})
networkMap["vswitche_list"] = networkArg["VSwitches"]
networkMap["vpc_id"] = networkArg["VpcId"]
networkMap["security_group_id"] = networkArg["SecurityGroupId"]
networkSli = append(networkSli, networkMap)
}
}
mapping["network"] = networkSli
}
}
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("meshes", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSimpleApplicationServerCustomImages() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSimpleApplicationServerCustomImagesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"images": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"custom_image_id": {
Type: schema.TypeString,
Computed: true,
},
"custom_image_name": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"platform": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudSimpleApplicationServerCustomImagesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListImages"
request := make(map[string]interface{})
request["ImageType"] = "custom"
request["RegionId"] = client.RegionId
var objects []map[string]interface{}
var customImageNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
customImageNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewSwasClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_simple_application_server_custom_images", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Images", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Images", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if customImageNameRegex != nil && !customImageNameRegex.MatchString(fmt.Sprint(item["ImageName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ImageId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["ImageId"]),
"custom_image_id": fmt.Sprint(object["ImageId"]),
"custom_image_name": object["ImageName"],
"description": object["Description"],
"platform": object["Platform"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["ImageName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("images", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSimpleApplicationServerDisks() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSimpleApplicationServerDisksRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"disk_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"System", "Data"}, false),
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Attaching", "Available", "Creating", "Detaching", "In_use", "ReIniting"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"disks": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"category": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"device": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"disk_id": {
Type: schema.TypeString,
Computed: true,
},
"disk_name": {
Type: schema.TypeString,
Computed: true,
},
"disk_type": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"size": {
Type: schema.TypeInt,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudSimpleApplicationServerDisksRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListDisks"
request := make(map[string]interface{})
if v, ok := d.GetOk("instance_id"); ok {
request["InstanceId"] = v
}
diskType, diskTypeOk := d.GetOk("disk_type")
request["RegionId"] = client.RegionId
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var diskNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
diskNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewSwasClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidInstanceId.NotFound"}) {
break
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_simple_application_server_disks", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Disks", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Disks", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if diskNameRegex != nil && !diskNameRegex.MatchString(fmt.Sprint(item["DiskName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DiskId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
if diskTypeOk && diskType.(string) != "" && diskType.(string) != item["DiskType"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"category": object["Category"],
"create_time": object["CreationTime"],
"device": object["Device"],
"id": fmt.Sprint(object["DiskId"]),
"disk_id": fmt.Sprint(object["DiskId"]),
"disk_name": object["DiskName"],
"disk_type": object["DiskType"],
"instance_id": object["InstanceId"],
"payment_type": convertSimpleApplicationServerDiskPaymentTypeResponse(object["DiskChargeType"].(string)),
"size": formatInt(object["Size"]),
"status": object["Status"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["DiskName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("disks", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
func convertSimpleApplicationServerDiskPaymentTypeResponse(source interface{}) interface{} {
switch source {
case "PostPaid":
return "PayAsYouGo"
case "PrePaid":
return "Subscription"
}
return source
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudSimpleApplicationServerFirewallRules() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSimpleApplicationServerFirewallRulesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"firewall_rule_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeString,
Computed: true,
},
"remark": {
Type: schema.TypeString,
Computed: true,
},
"rule_protocol": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudSimpleApplicationServerFirewallRulesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListFirewallRules"
request := make(map[string]interface{})
request["InstanceId"] = d.Get("instance_id")
request["RegionId"] = client.RegionId
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewSwasClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_simple_application_server_firewall_rules", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.FirewallRules", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.FirewallRules", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(request["InstanceId"], ":", item["RuleId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(request["InstanceId"], ":", object["FirewallId"]),
"firewall_rule_id": fmt.Sprint(object["RuleId"]),
"instance_id": request["InstanceId"],
"port": object["Port"],
"remark": object["Remark"],
"rule_protocol": convertSimpleApplicationServerFirewallRuleRuleProtocolResponse(object["RuleProtocol"].(string)),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("rules", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSimpleApplicationServerImages() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSimpleApplicationServerImagesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"image_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"app", "custom", "system"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"images": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"image_id": {
Type: schema.TypeString,
Computed: true,
},
"image_name": {
Type: schema.TypeString,
Computed: true,
},
"image_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudSimpleApplicationServerImagesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListImages"
request := make(map[string]interface{})
if v, ok := d.GetOk("image_type"); ok {
request["ImageType"] = v
}
var objects []map[string]interface{}
var instanceImageNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
instanceImageNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewSwasClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_simple_application_server_images", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Images", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Images", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if instanceImageNameRegex != nil && !instanceImageNameRegex.MatchString(fmt.Sprint(item["ImageName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["ImageId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"description": object["Description"],
"id": fmt.Sprint(object["ImageId"]),
"image_id": fmt.Sprint(object["ImageId"]),
"image_name": object["ImageName"],
"image_type": object["ImageType"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["ImageName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("images", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSimpleApplicationServerInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSimpleApplicationServerInstancesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "Subscription",
ValidateFunc: validation.StringInSlice([]string{"Subscription"}, false),
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Disabled", "Pending", "Resetting", "Running", "Starting", "Stopped", "Stopping", "Upgrading"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"business_status": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"ddos_status": {
Type: schema.TypeString,
Computed: true,
},
"expired_time": {
Type: schema.TypeString,
Computed: true,
},
"image_id": {
Type: schema.TypeString,
Computed: true,
},
"inner_ip_address": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_name": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"plan_id": {
Type: schema.TypeString,
Computed: true,
},
"public_ip_address": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudSimpleApplicationServerInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListInstances"
request := make(map[string]interface{})
if v, ok := d.GetOk("payment_type"); ok {
request["ChargeType"] = convertSimpleApplicationServerInstancePaymentTypeRequest(v)
}
request["RegionId"] = client.RegionId
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var instanceNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
instanceNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewSwasClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_simple_application_server_instances", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Instances", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Instances", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if instanceNameRegex != nil && !instanceNameRegex.MatchString(fmt.Sprint(item["InstanceName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["InstanceId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"business_status": object["BusinessStatus"],
"create_time": object["CreationTime"],
"ddos_status": object["DdosStatus"],
"expired_time": object["ExpiredTime"],
"image_id": object["ImageId"],
"inner_ip_address": object["InnerIpAddress"],
"id": fmt.Sprint(object["InstanceId"]),
"instance_id": fmt.Sprint(object["InstanceId"]),
"instance_name": object["InstanceName"],
"payment_type": convertSimpleApplicationServerInstancePaymentTypeResponse(object["ChargeType"]),
"plan_id": object["PlanId"],
"public_ip_address": object["PublicIpAddress"],
"status": object["Status"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["InstanceName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudSimpleApplicationServerPlans() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSimpleApplicationServerPlansRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"bandwidth": {
Type: schema.TypeInt,
Optional: true,
},
"core": {
Type: schema.TypeInt,
Optional: true,
},
"disk_size": {
Type: schema.TypeInt,
Optional: true,
},
"flow": {
Type: schema.TypeInt,
Optional: true,
},
"memory": {
Type: schema.TypeInt,
Optional: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"plans": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"bandwidth": {
Type: schema.TypeInt,
Computed: true,
},
"core": {
Type: schema.TypeInt,
Computed: true,
},
"disk_size": {
Type: schema.TypeInt,
Computed: true,
},
"flow": {
Type: schema.TypeInt,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"plan_id": {
Type: schema.TypeString,
Computed: true,
},
"memory": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudSimpleApplicationServerPlansRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListPlans"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
bandwidth, bandwidthOk := d.GetOk("bandwidth")
core, coreOk := d.GetOk("core")
diskSize, diskSizeOk := d.GetOk("disk_size")
memory, memoryOk := d.GetOk("memory")
flow, flowOk := d.GetOk("flow")
var response map[string]interface{}
conn, err := client.NewSwasClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_simple_application_server_plans", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Plans", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Plans", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["PlanId"])]; !ok {
continue
}
}
if bandwidthOk && bandwidth.(int) != 0 && bandwidth.(int) != formatInt(item["Bandwidth"]) {
continue
}
if coreOk && core.(int) != 0 && core.(int) != formatInt(item["Core"]) {
continue
}
if diskSizeOk && diskSize.(int) != 0 && diskSize.(int) != formatInt(item["DiskSize"]) {
continue
}
if memoryOk && memory.(int) != 0 && memory.(int) != formatInt(item["Memory"]) {
continue
}
if flowOk && flow.(int) != 0 && flow.(int) != formatInt(item["Flow"]) {
continue
}
objects = append(objects, item)
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"bandwidth": formatInt(object["Bandwidth"]),
"core": formatInt(object["Core"]),
"disk_size": formatInt(object["DiskSize"]),
"flow": formatInt(object["Flow"]),
"id": fmt.Sprint(object["PlanId"]),
"plan_id": fmt.Sprint(object["PlanId"]),
"memory": formatInt(object["Memory"]),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("plans", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSimpleApplicationServerSnapshots() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSimpleApplicationServerSnapshotsRead,
Schema: map[string]*schema.Schema{
"disk_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Accomplished", "Failed", "Progressing"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"snapshots": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"disk_id": {
Type: schema.TypeString,
Computed: true,
},
"progress": {
Type: schema.TypeString,
Computed: true,
},
"remark": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"snapshot_id": {
Type: schema.TypeString,
Computed: true,
},
"snapshot_name": {
Type: schema.TypeString,
Computed: true,
},
"source_disk_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudSimpleApplicationServerSnapshotsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListSnapshots"
request := make(map[string]interface{})
if v, ok := d.GetOk("disk_id"); ok {
request["DiskId"] = v
}
if v, ok := d.GetOk("instance_id"); ok {
request["InstanceId"] = v
}
request["RegionId"] = client.RegionId
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var snapshotNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
snapshotNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewSwasClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_simple_application_server_snapshots", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Snapshots", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Snapshots", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if snapshotNameRegex != nil && !snapshotNameRegex.MatchString(fmt.Sprint(item["SnapshotName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["SnapshotId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": object["CreationTime"],
"disk_id": object["SourceDiskId"],
"progress": object["Progress"],
"remark": object["Remark"],
"id": fmt.Sprint(object["SnapshotId"]),
"snapshot_id": fmt.Sprint(object["SnapshotId"]),
"snapshot_name": object["SnapshotName"],
"source_disk_type": object["SourceDiskType"],
"status": object["Status"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["SnapshotName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("snapshots", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/services/slb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSlbAcls() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSlbAclsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
MinItems: 1,
},
"tags": tagsSchema(),
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"acls": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"ip_version": {
Type: schema.TypeString,
Computed: true,
},
"entry_list": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"entry": {
Type: schema.TypeString,
Computed: true,
},
"comment": {
Type: schema.TypeString,
Computed: true,
},
},
},
MinItems: 0,
},
"related_listeners": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"load_balancer_id": {
Type: schema.TypeString,
Computed: true,
},
"frontend_port": {
Type: schema.TypeInt,
Computed: true,
},
"protocol": {
Type: schema.TypeString,
Computed: true,
},
"acl_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
MinItems: 0,
},
"tags": tagsSchema(),
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudSlbAclsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := slb.CreateDescribeAccessControlListsRequest()
request.RegionId = client.RegionId
request.ResourceGroupId = d.Get("resource_group_id").(string)
tags := d.Get("tags").(map[string]interface{})
if tags != nil && len(tags) > 0 {
KeyPairsTags := make([]slb.DescribeAccessControlListsTag, 0, len(tags))
for k, v := range tags {
keyPairsTag := slb.DescribeAccessControlListsTag{
Key: k,
Value: v.(string),
}
KeyPairsTags = append(KeyPairsTags, keyPairsTag)
}
request.Tag = &KeyPairsTags
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[Trim(vv.(string))] = Trim(vv.(string))
}
}
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeAccessControlLists(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_slb_acls", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*slb.DescribeAccessControlListsResponse)
var filteredAclsTemp []slb.Acl
nameRegex, ok := d.GetOk("name_regex")
if (ok && nameRegex.(string) != "") || (len(idsMap) > 0) {
var r *regexp.Regexp
if nameRegex != "" {
r, err = regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
}
for _, acl := range response.Acls.Acl {
if r != nil && !r.MatchString(acl.AclName) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[acl.AclId]; !ok {
continue
}
}
filteredAclsTemp = append(filteredAclsTemp, acl)
}
} else {
filteredAclsTemp = response.Acls.Acl
}
return slbAclsDescriptionAttributes(d, filteredAclsTemp, client, meta)
}
func aclTagsMappings(d *schema.ResourceData, aclId string, meta interface{}) map[string]string {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
tags, err := slbService.DescribeTags(aclId, nil, TagResourceAcl)
if err != nil {
return nil
}
return slbTagsToMap(tags)
}
func slbAclsDescriptionAttributes(d *schema.ResourceData, acls []slb.Acl, client *connectivity.AliyunClient, meta interface{}) error {
var ids []string
var names []string
var s []map[string]interface{}
slbService := SlbService{client}
request := slb.CreateDescribeAccessControlListAttributeRequest()
for _, item := range acls {
request.AclId = item.AclId
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeAccessControlListAttribute(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_slb_acls", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*slb.DescribeAccessControlListAttributeResponse)
mapping := map[string]interface{}{
"id": response.AclId,
"name": response.AclName,
"ip_version": response.AddressIPVersion,
"entry_list": slbService.FlattenSlbAclEntryMappings(response.AclEntrys.AclEntry),
"related_listeners": slbService.flattenSlbRelatedListenerMappings(response.RelatedListeners.RelatedListener),
"tags": aclTagsMappings(d, response.AclId, meta),
"resource_group_id": response.ResourceGroupId,
}
ids = append(ids, response.AclId)
names = append(names, response.AclName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("acls", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"github.com/aliyun/alibaba-cloud-sdk-go/services/slb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudSlbAttachments() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSlbAttachmentsRead,
Schema: map[string]*schema.Schema{
"load_balancer_id": {
Type: schema.TypeString,
Required: true,
},
"instance_ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
ForceNew: true,
MinItems: 1,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"slb_attachments": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"weight": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudSlbAttachmentsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := slb.CreateDescribeLoadBalancerAttributeRequest()
request.RegionId = client.RegionId
request.LoadBalancerId = d.Get("load_balancer_id").(string)
instanceIdsMap := make(map[string]string)
if v, ok := d.GetOk("instance_ids"); ok {
for _, vv := range v.([]interface{}) {
instanceIdsMap[Trim(vv.(string))] = Trim(vv.(string))
}
}
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeLoadBalancerAttribute(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_slb_attachments", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*slb.DescribeLoadBalancerAttributeResponse)
var filteredBackendServersTemp []slb.BackendServerInDescribeLoadBalancerAttribute
if len(instanceIdsMap) > 0 {
for _, backendServer := range response.BackendServers.BackendServer {
if len(instanceIdsMap) > 0 {
if _, ok := instanceIdsMap[backendServer.ServerId]; !ok {
continue
}
}
filteredBackendServersTemp = append(filteredBackendServersTemp, backendServer)
}
} else {
filteredBackendServersTemp = response.BackendServers.BackendServer
}
return slbAttachmentsDescriptionAttributes(d, filteredBackendServersTemp)
}
func slbAttachmentsDescriptionAttributes(d *schema.ResourceData, backendServers []slb.BackendServerInDescribeLoadBalancerAttribute) error {
var ids []string
var s []map[string]interface{}
for _, backendServer := range backendServers {
mapping := map[string]interface{}{
"instance_id": backendServer.ServerId,
"weight": backendServer.Weight,
}
ids = append(ids, backendServer.ServerId)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("slb_attachments", s); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"github.com/aliyun/alibaba-cloud-sdk-go/services/slb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudSlbBackendServers() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSlbBackendServersRead,
Schema: map[string]*schema.Schema{
"load_balancer_id": {
Type: schema.TypeString,
Required: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
MinItems: 1,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"backend_servers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"weight": {
Type: schema.TypeInt,
Computed: true,
},
"server_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudSlbBackendServersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := slb.CreateDescribeLoadBalancerAttributeRequest()
request.RegionId = client.RegionId
request.LoadBalancerId = d.Get("load_balancer_id").(string)
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[Trim(vv.(string))] = Trim(vv.(string))
}
}
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeLoadBalancerAttribute(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_slb_backend_servers", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*slb.DescribeLoadBalancerAttributeResponse)
var filteredBackendServersTemp []slb.BackendServerInDescribeLoadBalancerAttribute
if len(idsMap) > 0 {
for _, backendServer := range response.BackendServers.BackendServer {
if len(idsMap) > 0 {
if _, ok := idsMap[backendServer.ServerId]; !ok {
continue
}
}
filteredBackendServersTemp = append(filteredBackendServersTemp, backendServer)
}
} else {
filteredBackendServersTemp = response.BackendServers.BackendServer
}
return slbBackendServersDescriptionAttributes(d, filteredBackendServersTemp)
}
func slbBackendServersDescriptionAttributes(d *schema.ResourceData, backendServers []slb.BackendServerInDescribeLoadBalancerAttribute) error {
var ids []string
var s []map[string]interface{}
for _, backendServer := range backendServers {
mapping := map[string]interface{}{
"id": backendServer.ServerId,
"weight": backendServer.Weight,
"server_type": backendServer.Type,
}
ids = append(ids, backendServer.ServerId)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("backend_servers", s); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSlbCaCertificates() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSlbCaCertificatesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"tags": tagsSchema(),
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"certificates": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"ca_certificate_id": {
Type: schema.TypeString,
Computed: true,
},
"ca_certificate_name": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"common_name": {
Type: schema.TypeString,
Computed: true,
},
"created_timestamp": {
Type: schema.TypeInt,
Computed: true,
},
"expired_time": {
Type: schema.TypeString,
Computed: true,
},
"expired_timestamp": {
Type: schema.TypeInt,
Computed: true,
},
"fingerprint": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudSlbCaCertificatesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeCACertificates"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("tags"); ok {
tags := make([]map[string]interface{}, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, map[string]interface{}{
"Key": key,
"Value": value.(string),
})
}
request["Tag"] = tags
}
var objects []map[string]interface{}
var cACertificateNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
cACertificateNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewSlbClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_slb_ca_certificates", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.CACertificates.CACertificate", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.CACertificates.CACertificate", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if cACertificateNameRegex != nil {
if !cACertificateNameRegex.MatchString(fmt.Sprint(item["CACertificateName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["CACertificateId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["CACertificateId"]),
"ca_certificate_id": fmt.Sprint(object["CACertificateId"]),
"ca_certificate_name": object["CACertificateName"],
"name": object["CACertificateName"],
"common_name": object["CommonName"],
"created_timestamp": formatInt(object["CreateTimeStamp"]),
"expired_time": object["ExpireTime"],
"expired_timestamp": formatInt(object["ExpireTimeStamp"]),
"fingerprint": object["Fingerprint"],
"resource_group_id": object["ResourceGroupId"],
}
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags.Tag", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["TagKey"].(string)
value := t.(map[string]interface{})["TagValue"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
ids = append(ids, fmt.Sprint(object["CACertificateId"]))
names = append(names, object["CACertificateName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("certificates", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/slb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudSlbDomainExtensions() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSlbDomainExtensionsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
MinItems: 1,
},
"load_balancer_id": {
Type: schema.TypeString,
Required: true,
},
"frontend_port": {
Type: schema.TypeInt,
Required: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"extensions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"domain": {
Type: schema.TypeString,
Computed: true,
},
"server_certificate_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudSlbDomainExtensionsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := slb.CreateDescribeDomainExtensionsRequest()
request.LoadBalancerId = d.Get("load_balancer_id").(string)
request.ListenerPort = requests.NewInteger(d.Get("frontend_port").(int))
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[Trim(vv.(string))] = Trim(vv.(string))
}
}
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeDomainExtensions(request)
})
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_slb_domain_extensions", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*slb.DescribeDomainExtensionsResponse)
var filteredDomainExtensionsTemp []slb.DomainExtension
if len(idsMap) > 0 {
for _, domainExtension := range response.DomainExtensions.DomainExtension {
if len(idsMap) > 0 {
if _, ok := idsMap[domainExtension.DomainExtensionId]; !ok {
continue
}
}
filteredDomainExtensionsTemp = append(filteredDomainExtensionsTemp, domainExtension)
}
} else {
filteredDomainExtensionsTemp = response.DomainExtensions.DomainExtension
}
return slbDomainExtensionDescriptionAttributes(d, filteredDomainExtensionsTemp)
}
func slbDomainExtensionDescriptionAttributes(d *schema.ResourceData, domainExtensions []slb.DomainExtension) error {
var ids []string
var s []map[string]interface{}
for _, domainExtension := range domainExtensions {
mapping := map[string]interface{}{
"id": domainExtension.DomainExtensionId,
"domain": domainExtension.Domain,
"server_certificate_id": domainExtension.ServerCertificateId,
}
ids = append(ids, domainExtension.DomainExtensionId)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("extensions", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"strconv"
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/slb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSlbListeners() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSlbListenersRead,
Schema: map[string]*schema.Schema{
"load_balancer_id": {
Type: schema.TypeString,
Required: true,
},
"frontend_port": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"protocol": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"description_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"slb_listeners": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"frontend_port": {
Type: schema.TypeInt,
Computed: true,
},
"backend_port": {
Type: schema.TypeInt,
Computed: true,
},
"protocol": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"security_status": {
Type: schema.TypeString,
Computed: true,
},
"bandwidth": {
Type: schema.TypeInt,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"scheduler": {
Type: schema.TypeString,
Computed: true,
},
"server_group_id": {
Type: schema.TypeString,
Computed: true,
},
"master_slave_server_group_id": {
Type: schema.TypeString,
Computed: true,
},
"persistence_timeout": {
Type: schema.TypeInt,
Computed: true,
},
"established_timeout": {
Type: schema.TypeInt,
Computed: true,
},
"sticky_session": {
Type: schema.TypeString,
Computed: true,
},
"sticky_session_type": {
Type: schema.TypeString,
Computed: true,
},
"cookie_timeout": {
Type: schema.TypeInt,
Computed: true,
},
"cookie": {
Type: schema.TypeString,
Computed: true,
},
"health_check": {
Type: schema.TypeString,
Computed: true,
},
"health_check_type": {
Type: schema.TypeString,
Computed: true,
},
"health_check_domain": {
Type: schema.TypeString,
Computed: true,
},
"health_check_uri": {
Type: schema.TypeString,
Computed: true,
},
"health_check_connect_port": {
Type: schema.TypeInt,
Computed: true,
},
"health_check_connect_timeout": {
Type: schema.TypeInt,
Computed: true,
},
"healthy_threshold": {
Type: schema.TypeInt,
Computed: true,
},
"unhealthy_threshold": {
Type: schema.TypeInt,
Computed: true,
},
"health_check_timeout": {
Type: schema.TypeInt,
Computed: true,
},
"health_check_interval": {
Type: schema.TypeInt,
Computed: true,
},
"health_check_http_code": {
Type: schema.TypeString,
Computed: true,
},
"gzip": {
Type: schema.TypeString,
Computed: true,
},
"ssl_certificate_id": {
Type: schema.TypeString,
Computed: true,
},
"server_certificate_id": {
Type: schema.TypeString,
Computed: true,
},
"ca_certificate_id": {
Type: schema.TypeString,
Computed: true,
},
"x_forwarded_for": {
Type: schema.TypeString,
Computed: true,
},
"x_forwarded_for_slb_ip": {
Type: schema.TypeString,
Computed: true,
},
"x_forwarded_for_slb_id": {
Type: schema.TypeString,
Computed: true,
},
"x_forwarded_for_slb_proto": {
Type: schema.TypeString,
Computed: true,
},
// http https
"idle_timeout": {
Type: schema.TypeInt,
Computed: true,
},
// http https
"request_timeout": {
Type: schema.TypeInt,
Computed: true,
},
// https
"enable_http2": {
Type: schema.TypeString,
Computed: true,
},
// https
"tls_cipher_policy": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudSlbListenersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := slb.CreateDescribeLoadBalancerAttributeRequest()
request.RegionId = client.RegionId
request.LoadBalancerId = d.Get("load_balancer_id").(string)
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeLoadBalancerAttribute(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_slb_listeners", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*slb.DescribeLoadBalancerAttributeResponse)
var filteredListenersTemp []slb.ListenerPortAndProtocol
port := -1
if v, ok := d.GetOk("frontend_port"); ok && v.(int) != 0 {
port = v.(int)
}
protocol := ""
if v, ok := d.GetOk("protocol"); ok && v.(string) != "" {
protocol = v.(string)
}
var r *regexp.Regexp
if despRegex, ok := d.GetOk("description_regex"); ok && despRegex.(string) != "" {
r = regexp.MustCompile(despRegex.(string))
}
if port != -1 || protocol != "" || r != nil {
for _, listener := range response.ListenerPortsAndProtocol.ListenerPortAndProtocol {
if port != -1 && listener.ListenerPort != port {
continue
}
if protocol != "" && listener.ListenerProtocol != protocol {
continue
}
if r != nil && !r.MatchString(listener.Description) {
continue
}
filteredListenersTemp = append(filteredListenersTemp, listener)
}
} else {
filteredListenersTemp = response.ListenerPortsAndProtocol.ListenerPortAndProtocol
}
return slbListenersDescriptionAttributes(d, filteredListenersTemp, meta)
}
func slbListenersDescriptionAttributes(d *schema.ResourceData, listeners []slb.ListenerPortAndProtocol, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var ids []string
var s []map[string]interface{}
for _, listener := range listeners {
mapping := map[string]interface{}{
"frontend_port": listener.ListenerPort,
"protocol": listener.ListenerProtocol,
"description": listener.Description,
}
loadBalancerId := d.Get("load_balancer_id").(string)
switch Protocol(listener.ListenerProtocol) {
case Http:
request := slb.CreateDescribeLoadBalancerHTTPListenerAttributeRequest()
request.LoadBalancerId = loadBalancerId
request.ListenerPort = requests.NewInteger(listener.ListenerPort)
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeLoadBalancerHTTPListenerAttribute(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_slb_listeners", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*slb.DescribeLoadBalancerHTTPListenerAttributeResponse)
mapping["backend_port"] = response.BackendServerPort
mapping["status"] = response.Status
mapping["bandwidth"] = response.Bandwidth
mapping["scheduler"] = response.Scheduler
mapping["server_group_id"] = response.VServerGroupId
mapping["sticky_session"] = response.StickySession
mapping["sticky_session_type"] = response.StickySessionType
mapping["cookie_timeout"] = response.CookieTimeout
mapping["cookie"] = response.Cookie
mapping["health_check"] = response.HealthCheck
mapping["health_check_domain"] = response.HealthCheckDomain
mapping["health_check_uri"] = response.HealthCheckURI
mapping["health_check_connect_port"] = response.HealthCheckConnectPort
mapping["healthy_threshold"] = response.HealthyThreshold
mapping["unhealthy_threshold"] = response.UnhealthyThreshold
mapping["health_check_timeout"] = response.HealthCheckTimeout
mapping["health_check_interval"] = response.HealthCheckInterval
mapping["health_check_http_code"] = response.HealthCheckHttpCode
mapping["gzip"] = response.Gzip
mapping["x_forwarded_for"] = response.XForwardedFor
mapping["x_forwarded_for_slb_ip"] = response.XForwardedForSLBIP
mapping["x_forwarded_for_slb_id"] = response.XForwardedForSLBID
mapping["x_forwarded_for_slb_proto"] = response.XForwardedForProto
mapping["idle_timeout"] = response.IdleTimeout
mapping["request_timeout"] = response.RequestTimeout
case Https:
request := slb.CreateDescribeLoadBalancerHTTPSListenerAttributeRequest()
request.LoadBalancerId = loadBalancerId
request.ListenerPort = requests.NewInteger(listener.ListenerPort)
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeLoadBalancerHTTPSListenerAttribute(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_slb_listeners", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*slb.DescribeLoadBalancerHTTPSListenerAttributeResponse)
mapping["backend_port"] = response.BackendServerPort
mapping["status"] = response.Status
mapping["security_status"] = response.SecurityStatus
mapping["bandwidth"] = response.Bandwidth
mapping["scheduler"] = response.Scheduler
mapping["server_group_id"] = response.VServerGroupId
mapping["sticky_session"] = response.StickySession
mapping["sticky_session_type"] = response.StickySessionType
mapping["cookie_timeout"] = response.CookieTimeout
mapping["cookie"] = response.Cookie
mapping["health_check"] = response.HealthCheck
mapping["health_check_domain"] = response.HealthCheckDomain
mapping["health_check_uri"] = response.HealthCheckURI
mapping["health_check_connect_port"] = response.HealthCheckConnectPort
mapping["healthy_threshold"] = response.HealthyThreshold
mapping["unhealthy_threshold"] = response.UnhealthyThreshold
mapping["health_check_timeout"] = response.HealthCheckTimeout
mapping["health_check_interval"] = response.HealthCheckInterval
mapping["health_check_http_code"] = response.HealthCheckHttpCode
mapping["gzip"] = response.Gzip
mapping["ssl_certificate_id"] = response.ServerCertificateId
mapping["server_certificate_id"] = response.ServerCertificateId
mapping["ca_certificate_id"] = response.CACertificateId
mapping["x_forwarded_for"] = response.XForwardedFor
mapping["x_forwarded_for_slb_ip"] = response.XForwardedForSLBIP
mapping["x_forwarded_for_slb_id"] = response.XForwardedForSLBID
mapping["x_forwarded_for_slb_proto"] = response.XForwardedForProto
mapping["idle_timeout"] = response.IdleTimeout
mapping["request_timeout"] = response.RequestTimeout
mapping["enable_http2"] = response.EnableHttp2
mapping["tls_cipher_policy"] = response.TLSCipherPolicy
case Tcp:
request := slb.CreateDescribeLoadBalancerTCPListenerAttributeRequest()
request.LoadBalancerId = loadBalancerId
request.ListenerPort = requests.NewInteger(listener.ListenerPort)
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeLoadBalancerTCPListenerAttribute(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_slb_listeners", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*slb.DescribeLoadBalancerTCPListenerAttributeResponse)
mapping["backend_port"] = response.BackendServerPort
mapping["status"] = response.Status
mapping["bandwidth"] = response.Bandwidth
mapping["scheduler"] = response.Scheduler
mapping["server_group_id"] = response.VServerGroupId
mapping["master_slave_server_group_id"] = response.MasterSlaveServerGroupId
mapping["persistence_timeout"] = response.PersistenceTimeout
mapping["established_timeout"] = response.EstablishedTimeout
mapping["health_check"] = response.HealthCheck
mapping["health_check_type"] = response.HealthCheckType
mapping["health_check_domain"] = response.HealthCheckDomain
mapping["health_check_uri"] = response.HealthCheckURI
mapping["health_check_connect_port"] = response.HealthCheckConnectPort
mapping["health_check_connect_timeout"] = response.HealthCheckConnectTimeout
mapping["healthy_threshold"] = response.HealthyThreshold
mapping["unhealthy_threshold"] = response.UnhealthyThreshold
mapping["health_check_interval"] = response.HealthCheckInterval
mapping["health_check_http_code"] = response.HealthCheckHttpCode
case Udp:
request := slb.CreateDescribeLoadBalancerUDPListenerAttributeRequest()
request.LoadBalancerId = loadBalancerId
request.ListenerPort = requests.NewInteger(listener.ListenerPort)
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeLoadBalancerUDPListenerAttribute(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_slb_listeners", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*slb.DescribeLoadBalancerUDPListenerAttributeResponse)
mapping["backend_port"] = response.BackendServerPort
mapping["status"] = response.Status
mapping["bandwidth"] = response.Bandwidth
mapping["scheduler"] = response.Scheduler
mapping["server_group_id"] = response.VServerGroupId
mapping["master_slave_server_group_id"] = response.MasterSlaveServerGroupId
mapping["persistence_timeout"] = response.PersistenceTimeout
mapping["health_check"] = response.HealthCheck
mapping["health_check_connect_port"] = response.HealthCheckConnectPort
mapping["health_check_connect_timeout"] = response.HealthCheckConnectTimeout
mapping["healthy_threshold"] = response.HealthyThreshold
mapping["unhealthy_threshold"] = response.UnhealthyThreshold
mapping["health_check_interval"] = response.HealthCheckInterval
}
ids = append(ids, strconv.Itoa(listener.ListenerPort))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("slb_listeners", s); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"strings"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSlbLoadBalancers() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSlbLoadBalancersRead,
Schema: map[string]*schema.Schema{
"master_availability_zone": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Removed: "Field 'master_availability_zone' has removed from v1.123.1 and replace by 'master_zone_id'.",
},
"slave_availability_zone": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Removed: "Field 'slave_availability_zone' has removed from v1.123.1 and replace by 'slave_zone_id'.",
},
"address": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"address_ip_version": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ipv4", "ipv6"}, false),
},
"address_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"internet", "intranet"}, false),
},
"internet_charge_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PayByBandwidth", "PayByTraffic"}, true),
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"load_balancer_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"master_zone_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"network_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"vpc", "classic"}, false),
},
"payment_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo", "Subscription"}, false),
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"server_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"server_intranet_address": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"slave_zone_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"active", "inactive", "locked"}, false),
},
"tags": tagsSchema(),
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"page_number": {
Type: schema.TypeInt,
Optional: true,
},
"page_size": {
Type: schema.TypeInt,
Optional: true,
Default: 100,
},
"balancers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"address": {
Type: schema.TypeString,
Computed: true,
},
"address_ip_version": {
Type: schema.TypeString,
Computed: true,
},
"address_type": {
Type: schema.TypeString,
Computed: true,
},
"auto_release_time": {
Type: schema.TypeInt,
Computed: true,
},
"backend_servers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Computed: true,
},
"server_id": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"weight": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"bandwidth": {
Type: schema.TypeInt,
Computed: true,
},
"create_time_stamp": {
Type: schema.TypeInt,
Computed: true,
},
"delete_protection": {
Type: schema.TypeString,
Computed: true,
},
"end_time": {
Type: schema.TypeString,
Computed: true,
},
"end_time_stamp": {
Type: schema.TypeInt,
Computed: true,
},
"internet_charge_type": {
Type: schema.TypeString,
Computed: true,
},
"listener_ports_and_protocal": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"listener_port": {
Type: schema.TypeInt,
Computed: true,
},
"listener_protocal": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"listener_ports_and_protocol": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Computed: true,
},
"forward_port": {
Type: schema.TypeInt,
Computed: true,
},
"listener_forward": {
Type: schema.TypeString,
Computed: true,
},
"listener_port": {
Type: schema.TypeInt,
Computed: true,
},
"listener_protocol": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"load_balancer_id": {
Type: schema.TypeString,
Computed: true,
},
"load_balancer_name": {
Type: schema.TypeString,
Computed: true,
},
"load_balancer_spec": {
Type: schema.TypeString,
Computed: true,
},
"master_zone_id": {
Type: schema.TypeString,
Computed: true,
},
"modification_protection_reason": {
Type: schema.TypeString,
Computed: true,
},
"modification_protection_status": {
Type: schema.TypeString,
Computed: true,
},
"network_type": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"region_id_alias": {
Type: schema.TypeString,
Computed: true,
},
"renewal_cyc_unit": {
Type: schema.TypeString,
Computed: true,
},
"renewal_duration": {
Type: schema.TypeInt,
Computed: true,
},
"renewal_status": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"slave_zone_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"slbs": {
Type: schema.TypeList,
Computed: true,
Deprecated: "Field 'slbs' has deprecated from v1.123.1 and replace by 'balancers'.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"master_availability_zone": {
Type: schema.TypeString,
Computed: true,
},
"slave_availability_zone": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"network_type": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"address": {
Type: schema.TypeString,
Computed: true,
},
"internet": {
Type: schema.TypeBool,
Computed: true,
},
"creation_time": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"total_count": {
Type: schema.TypeInt,
Computed: true,
},
},
}
}
func dataSourceAlicloudSlbLoadBalancersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeLoadBalancers"
request := make(map[string]interface{})
if v, ok := d.GetOk("address"); ok {
request["Address"] = v
}
if v, ok := d.GetOk("address_ip_version"); ok {
request["AddressIPVersion"] = v
}
if v, ok := d.GetOk("address_type"); ok {
request["AddressType"] = v
}
if v, ok := d.GetOk("internet_charge_type"); ok {
request["InternetChargeType"] = convertSlbLoadBalancerInternetChargeTypeRequest(v)
}
if v, ok := d.GetOk("load_balancer_name"); ok {
request["LoadBalancerName"] = v
}
if v, ok := d.GetOk("master_zone_id"); ok {
request["MasterZoneId"] = v
}
if v, ok := d.GetOk("network_type"); ok {
request["NetworkType"] = v
}
if v, ok := d.GetOk("payment_type"); ok {
request["PayType"] = convertSlbLoadBalancerPaymentTypeRequest(v)
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("server_id"); ok {
request["ServerId"] = v
}
if v, ok := d.GetOk("server_intranet_address"); ok {
request["ServerIntranetAddress"] = v
}
if v, ok := d.GetOk("slave_zone_id"); ok {
request["SlaveZoneId"] = v
}
if v, ok := d.GetOk("status"); ok {
request["LoadBalancerStatus"] = v
}
if v, ok := d.GetOk("tags"); ok {
tags := make([]map[string]interface{}, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, map[string]interface{}{
"Key": key,
"Value": value.(string),
})
}
request["Tag"] = tags
}
if v, ok := d.GetOk("vswitch_id"); ok {
request["VSwitchId"] = v
}
if v, ok := d.GetOk("vpc_id"); ok {
request["VpcId"] = v
}
if v, ok := d.GetOk("page_number"); ok && v.(int) > 0 {
request["PageNumber"] = v.(int)
} else {
request["PageNumber"] = 1
}
if v, ok := d.GetOk("page_size"); ok && v.(int) > 0 {
request["PageSize"] = v.(int)
} else {
request["PageSize"] = PageSizeLarge
}
var objects []interface{}
var loadBalancerNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
loadBalancerNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewSlbClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_slb_load_balancers", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.LoadBalancers.LoadBalancer", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.LoadBalancers.LoadBalancer", response)
}
result, _ := resp.([]interface{})
if isPagingRequest(d) {
objects = result
break
}
for _, v := range result {
item := v.(map[string]interface{})
if loadBalancerNameRegex != nil {
if !loadBalancerNameRegex.MatchString(fmt.Sprint(item["LoadBalancerName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["LoadBalancerId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
slbs := make([]map[string]interface{}, 0)
for _, v := range objects {
object := v.(map[string]interface{})
mapping := map[string]interface{}{
"address": object["Address"],
"address_ip_version": object["AddressIPVersion"],
"address_type": object["AddressType"],
"create_time_stamp": formatInt(object["CreateTimeStamp"]),
"id": fmt.Sprint(object["LoadBalancerId"]),
"load_balancer_id": fmt.Sprint(object["LoadBalancerId"]),
"load_balancer_name": object["LoadBalancerName"],
"master_zone_id": object["MasterZoneId"],
"modification_protection_reason": object["ModificationProtectionReason"],
"modification_protection_status": object["ModificationProtectionStatus"],
"network_type": object["NetworkType"],
"payment_type": convertSlbLoadBalancerPaymentTypeResponse(object["PayType"]),
"region_id_alias": object["RegionIdAlias"],
"resource_group_id": object["ResourceGroupId"],
"slave_zone_id": object["SlaveZoneId"],
"status": object["LoadBalancerStatus"],
"vswitch_id": object["VSwitchId"],
"vpc_id": object["VpcId"],
}
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags.Tag", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["TagKey"].(string)
value := t.(map[string]interface{})["TagValue"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
slb := map[string]interface{}{
"id": fmt.Sprint(object["LoadBalancerId"]),
"region_id": object["RegionIdAlias"],
"master_availability_zone": object["MasterZoneId"],
"slave_availability_zone": object["SlaveZoneId"],
"status": object["LoadBalancerStatus"],
"name": object["LoadBalancerName"],
"network_type": object["NetworkType"],
"vpc_id": object["VpcId"],
"vswitch_id": object["VSwitchId"],
"address": object["Address"],
"internet": fmt.Sprint(object["NetworkType"]) == strings.ToLower(string(Internet)),
"creation_time": object["CreationTime"],
"tags": tags,
}
slbs = append(slbs, slb)
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["LoadBalancerId"]))
names = append(names, object["LoadBalancerName"])
s = append(s, mapping)
continue
}
slbService := SlbService{client}
id := fmt.Sprint(object["LoadBalancerId"])
getResp, err := slbService.DescribeSlbLoadBalancer(id)
if err != nil {
return WrapError(err)
}
mapping["auto_release_time"] = getResp["AutoReleaseTime"]
backendServer := make([]map[string]interface{}, 0)
if backendServerList, ok := getResp["BackendServers"].(map[string]interface{})["BackendServer"].([]interface{}); ok {
for _, v := range backendServerList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"description": m1["Description"],
"server_id": m1["ServerId"],
"type": m1["Type"],
"weight": formatInt(m1["Weight"]),
}
backendServer = append(backendServer, temp1)
}
}
}
mapping["backend_servers"] = backendServer
mapping["bandwidth"] = getResp["Bandwidth"]
mapping["delete_protection"] = getResp["DeleteProtection"]
mapping["end_time"] = getResp["EndTime"]
mapping["end_time_stamp"] = getResp["EndTimeStamp"]
mapping["internet_charge_type"] = convertSlbLoadBalancerInternetChargeTypeResponse(getResp["InternetChargeType"])
listenerPortAndProtocal := make([]map[string]interface{}, 0)
if listenerPortAndProtocalList, ok := getResp["ListenerPortsAndProtocal"].(map[string]interface{})["ListenerPortAndProtocal"].([]interface{}); ok {
for _, v := range listenerPortAndProtocalList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"listener_port": formatInt(m1["ListenerPort"]),
"listener_protocal": m1["ListenerProtocal"],
}
listenerPortAndProtocal = append(listenerPortAndProtocal, temp1)
}
}
}
mapping["listener_ports_and_protocal"] = listenerPortAndProtocal
listenerPortAndProtocol := make([]map[string]interface{}, 0)
if listenerPortAndProtocolList, ok := getResp["ListenerPortsAndProtocol"].(map[string]interface{})["ListenerPortAndProtocol"].([]interface{}); ok {
for _, v := range listenerPortAndProtocolList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"description": m1["Description"],
"forward_port": formatInt(m1["ForwardPort"]),
"listener_forward": m1["ListenerForward"],
"listener_port": formatInt(m1["ListenerPort"]),
"listener_protocol": m1["ListenerProtocol"],
}
listenerPortAndProtocol = append(listenerPortAndProtocol, temp1)
}
}
}
mapping["listener_ports_and_protocol"] = listenerPortAndProtocol
mapping["load_balancer_spec"] = getResp["LoadBalancerSpec"]
mapping["renewal_cyc_unit"] = getResp["RenewalCycUnit"]
mapping["renewal_duration"] = getResp["RenewalDuration"]
mapping["renewal_status"] = getResp["RenewalStatus"]
ids = append(ids, fmt.Sprint(object["LoadBalancerId"]))
names = append(names, object["LoadBalancerName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("balancers", s); err != nil {
return WrapError(err)
}
if err := d.Set("slbs", slbs); err != nil {
return WrapError(err)
}
if err := d.Set("total_count", formatInt(response["TotalCount"])); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/services/slb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSlbMasterSlaveServerGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSlbMasterSlaveServerGroupsRead,
Schema: map[string]*schema.Schema{
"load_balancer_id": {
Type: schema.TypeString,
Required: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
MinItems: 1,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"servers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"weight": {
Type: schema.TypeInt,
Computed: true,
},
"port": {
Type: schema.TypeInt,
Computed: true,
},
"server_type": {
Type: schema.TypeString,
Computed: true,
},
"is_backup": {
Type: schema.TypeInt,
Computed: true,
Removed: "Field 'is_backup' has been removed from provider version 1.63.0.",
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudSlbMasterSlaveServerGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := slb.CreateDescribeMasterSlaveServerGroupsRequest()
request.RegionId = client.RegionId
request.LoadBalancerId = d.Get("load_balancer_id").(string)
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[Trim(vv.(string))] = Trim(vv.(string))
}
}
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeMasterSlaveServerGroups(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_slb_master_slave_server_groups", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*slb.DescribeMasterSlaveServerGroupsResponse)
var filteredServerGroupsTemp []slb.MasterSlaveServerGroup
nameRegex, ok := d.GetOk("name_regex")
if (ok && nameRegex.(string) != "") || (len(idsMap) > 0) {
var r *regexp.Regexp
if nameRegex != "" {
r, err = regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
}
for _, serverGroup := range response.MasterSlaveServerGroups.MasterSlaveServerGroup {
if r != nil && !r.MatchString(serverGroup.MasterSlaveServerGroupName) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[serverGroup.MasterSlaveServerGroupId]; !ok {
continue
}
}
filteredServerGroupsTemp = append(filteredServerGroupsTemp, serverGroup)
}
} else {
filteredServerGroupsTemp = response.MasterSlaveServerGroups.MasterSlaveServerGroup
}
return slbMasterSlaveServerGroupsDescriptionAttributes(d, filteredServerGroupsTemp, meta)
}
func slbMasterSlaveServerGroupsDescriptionAttributes(d *schema.ResourceData, serverGroups []slb.MasterSlaveServerGroup, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var ids []string
var names []string
var s []map[string]interface{}
for _, serverGroup := range serverGroups {
mapping := map[string]interface{}{
"id": serverGroup.MasterSlaveServerGroupId,
"name": serverGroup.MasterSlaveServerGroupName,
}
request := slb.CreateDescribeMasterSlaveServerGroupAttributeRequest()
request.MasterSlaveServerGroupId = serverGroup.MasterSlaveServerGroupId
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeMasterSlaveServerGroupAttribute(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_slb_master_slave_server_groups", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*slb.DescribeMasterSlaveServerGroupAttributeResponse)
if response != nil && len(response.MasterSlaveBackendServers.MasterSlaveBackendServer) > 0 {
var backendServerMappings []map[string]interface{}
for _, backendServer := range response.MasterSlaveBackendServers.MasterSlaveBackendServer {
backendServerMapping := map[string]interface{}{
"instance_id": backendServer.ServerId,
"weight": backendServer.Weight,
"server_type": backendServer.ServerType,
}
backendServerMappings = append(backendServerMappings, backendServerMapping)
}
mapping["servers"] = backendServerMappings
}
ids = append(ids, serverGroup.MasterSlaveServerGroupId)
names = append(names, serverGroup.MasterSlaveServerGroupName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/slb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSlbRules() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSlbRulesRead,
Schema: map[string]*schema.Schema{
"load_balancer_id": {
Type: schema.TypeString,
Required: true,
},
"frontend_port": {
Type: schema.TypeInt,
Required: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
MinItems: 1,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"slb_rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"domain": {
Type: schema.TypeString,
Computed: true,
},
"url": {
Type: schema.TypeString,
Computed: true,
},
"server_group_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudSlbRulesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := slb.CreateDescribeRulesRequest()
request.RegionId = client.RegionId
request.LoadBalancerId = d.Get("load_balancer_id").(string)
request.ListenerPort = requests.NewInteger(d.Get("frontend_port").(int))
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[Trim(vv.(string))] = Trim(vv.(string))
}
}
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeRules(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_slb_rules", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*slb.DescribeRulesResponse)
var filteredRulesTemp []slb.Rule
nameRegex, ok := d.GetOk("name_regex")
if (ok && nameRegex.(string) != "") || (len(idsMap) > 0) {
var r *regexp.Regexp
if nameRegex != "" {
r, err = regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
}
for _, rule := range response.Rules.Rule {
if r != nil && !r.MatchString(rule.RuleName) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[rule.RuleId]; !ok {
continue
}
}
filteredRulesTemp = append(filteredRulesTemp, rule)
}
} else {
filteredRulesTemp = response.Rules.Rule
}
return slbRulesDescriptionAttributes(d, filteredRulesTemp)
}
func slbRulesDescriptionAttributes(d *schema.ResourceData, rules []slb.Rule) error {
var ids []string
var names []string
var s []map[string]interface{}
for _, rule := range rules {
mapping := map[string]interface{}{
"id": rule.RuleId,
"name": rule.RuleName,
"domain": rule.Domain,
"url": rule.Url,
"server_group_id": rule.VServerGroupId,
}
ids = append(ids, rule.RuleId)
names = append(names, rule.RuleName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("slb_rules", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/services/slb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSlbServerCertificates() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSlbServerCertificatesRead,
Schema: map[string]*schema.Schema{
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
MinItems: 1,
},
"tags": tagsSchema(),
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
// Computed values
"certificates": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"fingerprint": {
Type: schema.TypeString,
Computed: true,
},
"common_name": {
Type: schema.TypeString,
Computed: true,
},
"subject_alternative_names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"expired_time": {
Type: schema.TypeString,
Computed: true,
},
"expired_timestamp": {
Type: schema.TypeInt,
Computed: true,
},
"created_time": {
Type: schema.TypeString,
Computed: true,
},
"created_timestamp": {
Type: schema.TypeInt,
Computed: true,
},
"alicloud_certificate_id": {
Type: schema.TypeString,
Computed: true,
},
"alicloud_certificate_name": {
Type: schema.TypeString,
Computed: true,
},
"is_alicloud_certificate": {
Type: schema.TypeBool,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"tags": tagsSchema(),
},
},
},
},
}
}
func severCertificateTagsMappings(d *schema.ResourceData, id string, meta interface{}) map[string]string {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
tags, err := slbService.DescribeTags(id, nil, TagResourceCertificate)
if err != nil {
return nil
}
return slbTagsToMap(tags)
}
func dataSourceAlicloudSlbServerCertificatesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := slb.CreateDescribeServerCertificatesRequest()
request.RegionId = client.RegionId
tags := d.Get("tags").(map[string]interface{})
if tags != nil && len(tags) > 0 {
Tags := make([]slb.DescribeServerCertificatesTag, 0, len(tags))
for k, v := range tags {
certificatesTag := slb.DescribeServerCertificatesTag{
Key: k,
Value: v.(string),
}
Tags = append(Tags, certificatesTag)
}
request.Tag = &Tags
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[Trim(vv.(string))] = Trim(vv.(string))
}
}
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeServerCertificates(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_slb_server_certificates", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*slb.DescribeServerCertificatesResponse)
var filteredTemp []slb.ServerCertificate
nameRegex, ok := d.GetOk("name_regex")
if (ok && nameRegex.(string) != "") || (len(idsMap) > 0) {
var r *regexp.Regexp
if nameRegex != "" {
r, err = regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
}
for _, certificate := range response.ServerCertificates.ServerCertificate {
if r != nil && !r.MatchString(certificate.ServerCertificateName) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[certificate.ServerCertificateId]; !ok {
continue
}
}
filteredTemp = append(filteredTemp, certificate)
}
} else {
filteredTemp = response.ServerCertificates.ServerCertificate
}
return slbServerCertificatesDescriptionAttributes(d, filteredTemp, meta)
}
func slbServerCertificatesDescriptionAttributes(d *schema.ResourceData, certificates []slb.ServerCertificate, meta interface{}) error {
var ids []string
var names []string
var s []map[string]interface{}
for _, certificate := range certificates {
var subjectAlternativeNames []string
if certificate.SubjectAlternativeNames.SubjectAlternativeName != nil {
subjectAlternativeNames = certificate.SubjectAlternativeNames.SubjectAlternativeName
}
mapping := map[string]interface{}{
"id": certificate.ServerCertificateId,
"name": certificate.ServerCertificateName,
"fingerprint": certificate.Fingerprint,
"common_name": certificate.CommonName,
"subject_alternative_names": subjectAlternativeNames,
"expired_time": certificate.ExpireTime,
"expired_timestamp": certificate.ExpireTimeStamp,
"created_time": certificate.CreateTime,
"created_timestamp": certificate.CreateTimeStamp,
"alicloud_certificate_id": certificate.AliCloudCertificateId,
"alicloud_certificate_name": certificate.AliCloudCertificateName,
"is_alicloud_certificate": certificate.IsAliCloudCertificate == 1,
"resource_group_id": certificate.ResourceGroupId,
"tags": severCertificateTagsMappings(d, certificate.ServerCertificateId, meta),
}
ids = append(ids, certificate.ServerCertificateId)
names = append(names, certificate.ServerCertificateName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("certificates", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/services/slb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSlbServerGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSlbServerGroupsRead,
Schema: map[string]*schema.Schema{
"load_balancer_id": {
Type: schema.TypeString,
Required: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
MinItems: 1,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"slb_server_groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"servers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"weight": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudSlbServerGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := slb.CreateDescribeVServerGroupsRequest()
request.RegionId = client.RegionId
request.LoadBalancerId = d.Get("load_balancer_id").(string)
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[Trim(vv.(string))] = Trim(vv.(string))
}
}
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeVServerGroups(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_slb_server_groups", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*slb.DescribeVServerGroupsResponse)
var filteredServerGroupsTemp []slb.VServerGroup
nameRegex, ok := d.GetOk("name_regex")
if (ok && nameRegex.(string) != "") || (len(idsMap) > 0) {
var r *regexp.Regexp
if nameRegex != "" {
r, err = regexp.Compile(nameRegex.(string))
if err != nil {
return WrapError(err)
}
}
for _, serverGroup := range response.VServerGroups.VServerGroup {
if r != nil && !r.MatchString(serverGroup.VServerGroupName) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[serverGroup.VServerGroupId]; !ok {
continue
}
}
filteredServerGroupsTemp = append(filteredServerGroupsTemp, serverGroup)
}
} else {
filteredServerGroupsTemp = response.VServerGroups.VServerGroup
}
return slbServerGroupsDescriptionAttributes(d, filteredServerGroupsTemp, meta)
}
func slbServerGroupsDescriptionAttributes(d *schema.ResourceData, serverGroups []slb.VServerGroup, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var ids []string
var names []string
var s []map[string]interface{}
for _, serverGroup := range serverGroups {
mapping := map[string]interface{}{
"id": serverGroup.VServerGroupId,
"name": serverGroup.VServerGroupName,
}
request := slb.CreateDescribeVServerGroupAttributeRequest()
request.VServerGroupId = serverGroup.VServerGroupId
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeVServerGroupAttribute(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_slb_server_groups", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*slb.DescribeVServerGroupAttributeResponse)
if response != nil && len(response.BackendServers.BackendServer) > 0 {
var backendServerMappings []map[string]interface{}
for _, backendServer := range response.BackendServers.BackendServer {
backendServerMapping := map[string]interface{}{
"instance_id": backendServer.ServerId,
"weight": backendServer.Weight,
}
backendServerMappings = append(backendServerMappings, backendServerMapping)
}
mapping["servers"] = backendServerMappings
}
ids = append(ids, serverGroup.VServerGroupId)
names = append(names, serverGroup.VServerGroupName)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("slb_server_groups", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSlbTlsCipherPolicies() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSlbTlsCipherPoliciesRead,
Schema: map[string]*schema.Schema{
"include_listener": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"configuring", "normal"}, false),
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"tls_cipher_policy_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"policies": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ciphers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"relate_listeners": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"load_balancer_id": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeInt,
Computed: true,
},
"protocol": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"tls_cipher_policy_id": {
Type: schema.TypeString,
Computed: true,
},
"tls_cipher_policy_name": {
Type: schema.TypeString,
Computed: true,
},
"tls_versions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
},
}
}
func dataSourceAlicloudSlbTlsCipherPoliciesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListTLSCipherPolicies"
request := make(map[string]interface{})
if v, ok := d.GetOkExists("include_listener"); ok {
request["IncludeListener"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("tls_cipher_policy_name"); ok {
request["Name"] = v
}
var objects []map[string]interface{}
var tlsCipherPolicyNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
tlsCipherPolicyNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewSlbClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_slb_tls_cipher_policies", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.TLSCipherPolicies", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.TLSCipherPolicies", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if tlsCipherPolicyNameRegex != nil && !tlsCipherPolicyNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["InstanceId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"ciphers": object["Ciphers"],
"create_time": fmt.Sprint(object["CreateTime"]),
"status": object["Status"],
"id": fmt.Sprint(object["InstanceId"]),
"tls_cipher_policy_id": fmt.Sprint(object["InstanceId"]),
"tls_cipher_policy_name": object["Name"],
"tls_versions": object["TLSVersions"],
}
relateListeners := make([]map[string]interface{}, 0)
if relateListenersList, ok := object["RelateListeners"].([]interface{}); ok {
for _, v := range relateListenersList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"load_balancer_id": m1["LoadBalancerId"],
"port": formatInt(m1["Port"]),
"protocol": m1["Protocol"],
}
relateListeners = append(relateListeners, temp1)
}
}
}
mapping["relate_listeners"] = relateListeners
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("policies", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"sort"
"github.com/aliyun/alibaba-cloud-sdk-go/services/slb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSlbZones() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSlbZonesRead,
Schema: map[string]*schema.Schema{
"available_slb_address_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Vpc", "classic_intranet", "classic_internet"}, false),
},
"available_slb_address_ip_version": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ipv4", "ipv6"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Deprecated: "The parameter enable_details has been deprecated from version v1.154.0+",
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"zones": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"slb_slave_zone_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"supported_resources": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"address_type": {
Type: schema.TypeString,
Computed: true,
},
"address_ip_version": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudSlbZonesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slaveZones := make(map[string][]string)
request := slb.CreateDescribeAvailableResourceRequest()
request.RegionId = client.RegionId
if ipVersion, ok := d.GetOk("available_slb_address_ip_version"); ok {
request.AddressIPVersion = ipVersion.(string)
}
if addressType, ok := d.GetOk("available_slb_address_type"); ok {
request.AddressType = addressType.(string)
}
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeAvailableResource(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_slb_zones", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*slb.DescribeAvailableResourceResponse)
supportedResources := make(map[string][]map[string]interface{})
for _, resource := range response.AvailableResources.AvailableResource {
slaveIds := slaveZones[resource.MasterZoneId]
slaveIds = append(slaveIds, resource.SlaveZoneId)
if len(slaveIds) > 0 {
sort.Strings(slaveIds)
}
slaveZones[resource.MasterZoneId] = slaveIds
supportedResourceList := make([]map[string]interface{}, 0)
for _, v := range resource.SupportResources.SupportResource {
supportedResourceList = append(supportedResourceList, map[string]interface{}{
"address_type": v.AddressType,
"address_ip_version": v.AddressIPVersion,
})
}
supportedResources[resource.MasterZoneId] = supportedResourceList
}
var ids []string
for v, _ := range slaveZones {
ids = append(ids, v)
}
if len(ids) > 0 {
sort.Strings(ids)
}
var s []map[string]interface{}
for _, zoneId := range ids {
mapping := map[string]interface{}{
"id": zoneId,
"slb_slave_zone_ids": slaveZones[zoneId],
"supported_resources": supportedResources[zoneId],
}
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("zones", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSnatEntries() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSnatEntriesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"snat_entry_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"snat_ip": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"snat_table_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"source_cidr": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"source_vswitch_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "Deleting", "Pending"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"entries": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"snat_entry_id": {
Type: schema.TypeString,
Computed: true,
},
"snat_entry_name": {
Type: schema.TypeString,
Computed: true,
},
"snat_ip": {
Type: schema.TypeString,
Computed: true,
},
"source_cidr": {
Type: schema.TypeString,
Computed: true,
},
"source_vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudSnatEntriesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeSnatTableEntries"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("snat_entry_name"); ok {
request["SnatEntryName"] = v
}
if v, ok := d.GetOk("snat_ip"); ok {
request["SnatIp"] = v
}
request["SnatTableId"] = d.Get("snat_table_id")
if v, ok := d.GetOk("source_cidr"); ok {
request["SourceCIDR"] = v
}
if v, ok := d.GetOk("source_vswitch_id"); ok {
request["SourceVSwitchId"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var snatEntryNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
snatEntryNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_snat_entries", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.SnatTableEntries.SnatTableEntry", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.SnatTableEntries.SnatTableEntry", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if snatEntryNameRegex != nil {
if !snatEntryNameRegex.MatchString(fmt.Sprint(item["SnatEntryName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["SnatEntryId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["SnatEntryId"]),
"snat_entry_id": fmt.Sprint(object["SnatEntryId"]),
"snat_entry_name": object["SnatEntryName"],
"snat_ip": object["SnatIp"],
"source_cidr": object["SourceCIDR"],
"source_vswitch_id": object["SourceVSwitchId"],
"status": object["Status"],
}
ids = append(ids, fmt.Sprint(object["SnatEntryId"]))
names = append(names, object["SnatEntryName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("entries", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSslCertificatesServiceCertificates() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSslCertificatesServiceCertificatesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"lang": {
Type: schema.TypeString,
Optional: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"certificates": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"buy_in_aliyun": {
Type: schema.TypeBool,
Computed: true,
},
"cert": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"cert_id": {
Type: schema.TypeString,
Computed: true,
},
"certificate_name": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Deprecated: "Field 'name' has been deprecated from provider version 1.129.0 and it will be removed in the future version. Please use the new attribute 'certificate_name' instead.",
Computed: true,
},
"city": {
Type: schema.TypeString,
Computed: true,
},
"common": {
Type: schema.TypeString,
Computed: true,
},
"country": {
Type: schema.TypeString,
Computed: true,
},
"end_date": {
Type: schema.TypeString,
Computed: true,
},
"expired": {
Type: schema.TypeBool,
Computed: true,
},
"fingerprint": {
Type: schema.TypeString,
Computed: true,
},
"issuer": {
Type: schema.TypeString,
Computed: true,
},
"key": {
Type: schema.TypeString,
Computed: true,
},
"org_name": {
Type: schema.TypeString,
Computed: true,
},
"province": {
Type: schema.TypeString,
Computed: true,
},
"sans": {
Type: schema.TypeString,
Computed: true,
},
"start_date": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudSslCertificatesServiceCertificatesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeUserCertificateList"
request := make(map[string]interface{})
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
request["ShowSize"] = PageSizeLarge
request["CurrentPage"] = 1
var objects []map[string]interface{}
var certificateNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
certificateNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewCasClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-07-13"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ssl_certificates_service_certificates", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.CertificateList", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.CertificateList", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if certificateNameRegex != nil && !certificateNameRegex.MatchString(fmt.Sprint(item["name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["id"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["CurrentPage"] = request["CurrentPage"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"buy_in_aliyun": object["buyInAliyun"],
"id": fmt.Sprint(object["id"]),
"cert_id": fmt.Sprint(object["id"]),
"certificate_name": object["name"],
"city": object["city"],
"common": object["common"],
"country": object["country"],
"end_date": object["endDate"],
"expired": object["expired"],
"name": object["name"],
"fingerprint": object["fingerprint"],
"issuer": object["issuer"],
"org_name": object["orgName"],
"province": object["province"],
"sans": object["sans"],
"start_date": object["startDate"],
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["id"]))
names = append(names, object["name"])
s = append(s, mapping)
continue
}
casService := CasService{client}
id := fmt.Sprint(formatInt(object["id"]))
getResp, err := casService.DescribeSslCertificatesServiceCertificate(id)
if err != nil {
return WrapError(err)
}
mapping["cert"] = getResp["Cert"]
mapping["key"] = getResp["Key"]
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("certificates", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSslVpnClientCerts() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSslVpnClientCertsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
MinItems: 1,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ssl_vpn_server_id": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"certs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ssl_vpn_server_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"end_time": {
Type: schema.TypeInt,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudSslVpnClientCertsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := vpc.CreateDescribeSslVpnClientCertsRequest()
request.RegionId = client.RegionId
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var allSslVpnClientCerts []vpc.SslVpnClientCertKey
if v, ok := d.GetOk("ssl_vpn_server_id"); ok && v.(string) != "" {
request.SslVpnServerId = v.(string)
}
for {
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeSslVpnClientCerts(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ssl_vpn_client_certs", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*vpc.DescribeSslVpnClientCertsResponse)
if len(response.SslVpnClientCertKeys.SslVpnClientCertKey) < 1 {
break
}
allSslVpnClientCerts = append(allSslVpnClientCerts, response.SslVpnClientCertKeys.SslVpnClientCertKey...)
if len(response.SslVpnClientCertKeys.SslVpnClientCertKey) < PageSizeLarge {
break
}
if page, err := getNextpageNumber(request.PageNumber); err != nil {
return WrapError(err)
} else {
request.PageNumber = page
}
}
var filteredSslVpnClientCerts []vpc.SslVpnClientCertKey
var reg *regexp.Regexp
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[Trim(vv.(string))] = Trim(vv.(string))
}
}
if nameRegex, ok := d.GetOk("name_regex"); ok && nameRegex.(string) != "" {
if r, err := regexp.Compile(nameRegex.(string)); err == nil {
reg = r
} else {
return WrapError(err)
}
}
for _, sslVpnClientCertKey := range allSslVpnClientCerts {
if reg != nil {
if !reg.MatchString(sslVpnClientCertKey.Name) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[sslVpnClientCertKey.SslVpnClientCertId]; !ok {
continue
}
}
filteredSslVpnClientCerts = append(filteredSslVpnClientCerts, sslVpnClientCertKey)
}
return sslVpnClientCertsDecriptionAttributes(d, filteredSslVpnClientCerts, meta)
}
func sslVpnClientCertsDecriptionAttributes(d *schema.ResourceData, vpnSetTypes []vpc.SslVpnClientCertKey, meta interface{}) error {
var ids []string
var names []string
var s []map[string]interface{}
for _, vpn := range vpnSetTypes {
mapping := map[string]interface{}{
"ssl_vpn_server_id": vpn.SslVpnServerId,
"id": vpn.SslVpnClientCertId,
"name": vpn.Name,
"end_time": vpn.EndTime,
"create_time": TimestampToStr(vpn.CreateTime),
"status": vpn.Status,
}
ids = append(ids, vpn.SslVpnClientCertId)
names = append(names, vpn.Name)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("certs", s); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudSslVpnServers() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudSslVpnServersRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
MinItems: 1,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"vpn_gateway_id": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"servers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"vpn_gateway_id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"local_subnet": {
Type: schema.TypeString,
Computed: true,
},
"client_ip_pool": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"cipher": {
Type: schema.TypeString,
Computed: true,
},
"proto": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeInt,
Computed: true,
},
"compress": {
Type: schema.TypeBool,
Computed: true,
},
"connections": {
Type: schema.TypeInt,
Computed: true,
},
"max_connections": {
Type: schema.TypeInt,
Computed: true,
},
"internet_ip": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudSslVpnServersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := vpc.CreateDescribeSslVpnServersRequest()
request.RegionId = client.RegionId
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var allSslVpnServers []vpc.SslVpnServer
if v, ok := d.GetOk("vpn_gateway_id"); ok && v.(string) != "" {
request.VpnGatewayId = v.(string)
}
for {
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeSslVpnServers(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ssl_vpn_servers", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*vpc.DescribeSslVpnServersResponse)
if len(response.SslVpnServers.SslVpnServer) < 1 {
break
}
allSslVpnServers = append(allSslVpnServers, response.SslVpnServers.SslVpnServer...)
if len(response.SslVpnServers.SslVpnServer) < PageSizeLarge {
break
}
if page, err := getNextpageNumber(request.PageNumber); err != nil {
return WrapError(err)
} else {
request.PageNumber = page
}
}
var filteredSslVpnServers []vpc.SslVpnServer
var reg *regexp.Regexp
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[Trim(vv.(string))] = Trim(vv.(string))
}
}
if nameRegex, ok := d.GetOk("name_regex"); ok && nameRegex.(string) != "" {
if r, err := regexp.Compile(nameRegex.(string)); err == nil {
reg = r
} else {
return WrapError(err)
}
}
for _, sslVpnServer := range allSslVpnServers {
if reg != nil {
if !reg.MatchString(sslVpnServer.Name) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[sslVpnServer.SslVpnServerId]; !ok {
continue
}
}
filteredSslVpnServers = append(filteredSslVpnServers, sslVpnServer)
}
return sslVpnServersDecriptionAttributes(d, filteredSslVpnServers, meta)
}
func sslVpnServersDecriptionAttributes(d *schema.ResourceData, vpnSetTypes []vpc.SslVpnServer, meta interface{}) error {
var ids []string
var names []string
var s []map[string]interface{}
for _, vpn := range vpnSetTypes {
mapping := map[string]interface{}{
"id": vpn.SslVpnServerId,
"vpn_gateway_id": vpn.VpnGatewayId,
"local_subnet": vpn.LocalSubnet,
"name": vpn.Name,
"client_ip_pool": vpn.ClientIpPool,
"create_time": TimestampToStr(vpn.CreateTime),
"cipher": vpn.Cipher,
"proto": vpn.Proto,
"port": vpn.Port,
"compress": vpn.Compress,
"connections": vpn.Connections,
"max_connections": vpn.MaxConnections,
"internet_ip": vpn.InternetIp,
}
ids = append(ids, vpn.SslVpnServerId)
names = append(names, vpn.Name)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("servers", s); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudTsdbInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudTsdbInstancesRead,
Schema: map[string]*schema.Schema{
"app_key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"engine_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"tsdb_influxdb", "tsdb_tsdb"}, false),
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"query_str": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ACTIVATION", "CLASS_CHANGING", "CREATING", "DELETED", "LOCKED"}, false),
},
"status_list": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"auto_renew": {
Type: schema.TypeString,
Computed: true,
},
"cpu_number": {
Type: schema.TypeString,
Computed: true,
},
"disk_category": {
Type: schema.TypeString,
Computed: true,
},
"engine_type": {
Type: schema.TypeString,
Computed: true,
},
"expired_time": {
Type: schema.TypeInt,
Computed: true,
},
"instance_alias": {
Type: schema.TypeString,
Computed: true,
},
"instance_class": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_storage": {
Type: schema.TypeString,
Computed: true,
},
"memory_size": {
Type: schema.TypeString,
Computed: true,
},
"network_type": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_connection_address": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudTsdbInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeHiTSDBInstanceList"
request := make(map[string]interface{})
if v, ok := d.GetOk("app_key"); ok {
request["AppKey"] = v
}
if v, ok := d.GetOk("engine_type"); ok {
request["EngineType"] = v
}
if v, ok := d.GetOk("query_str"); ok {
request["QueryStr"] = v
}
if v, ok := d.GetOk("status_list"); ok {
request["StatusList"] = v
}
request["RegionId"] = client.RegionId
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewHitsdbClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_tsdb_instances", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.InstanceList", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.InstanceList", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["InstanceId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"engine_type": object["EngineType"],
"expired_time": object["ExpiredTime"],
"instance_alias": object["InstanceAlias"],
"instance_class": object["InstanceClass"],
"id": fmt.Sprint(object["InstanceId"]),
"instance_id": fmt.Sprint(object["InstanceId"]),
"instance_storage": object["InstanceStorage"],
"network_type": object["NetworkType"],
"payment_type": convertTsdbInstancePaymentTypeResponse(object["PaymentType"].(string)),
"status": object["Status"],
"vswitch_id": object["VswitchId"],
"vpc_id": object["VpcId"],
"zone_id": object["ZoneId"],
}
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["InstanceId"]))
s = append(s, mapping)
continue
}
hitsdbService := HitsdbService{client}
id := fmt.Sprint(object["InstanceId"])
getResp, err := hitsdbService.DescribeTsdbInstance(id)
if err != nil {
return WrapError(err)
}
mapping["auto_renew"] = getResp["AutoRenew"]
mapping["cpu_number"] = getResp["CpuNumber"]
mapping["disk_category"] = getResp["DiskCategory"]
mapping["memory_size"] = getResp["MemSize"]
mapping["vpc_connection_address"] = getResp["ConnectionString"]
ids = append(ids, fmt.Sprint(object["InstanceId"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceAlicloudTsdbZones() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudTsdbZonesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"zones": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
"local_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudTsdbZonesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeZones"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
var objects []map[string]interface{}
var response map[string]interface{}
conn, err := client.NewHitsdbClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_tsdb_zones", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.ZoneList.ZoneModel", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.ZoneList.ZoneModel", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
objects = append(objects, item)
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["ZoneId"]),
"zone_id": object["ZoneId"],
"local_name": object["LocalName"],
}
ids = append(ids, fmt.Sprint(object["ZoneId"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("zones", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudVideoSurveillanceSystemGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudVideoSurveillanceSystemGroupsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"in_protocol": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"gb28181", "rtmp"}, false),
},
"name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"on", "off"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"app": {
Type: schema.TypeString,
Computed: true,
},
"callback": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"enabled": {
Type: schema.TypeBool,
Computed: true,
},
"gb_id": {
Type: schema.TypeString,
Computed: true,
},
"gb_ip": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"group_id": {
Type: schema.TypeString,
Computed: true,
},
"group_name": {
Type: schema.TypeString,
Computed: true,
},
"in_protocol": {
Type: schema.TypeString,
Computed: true,
},
"out_protocol": {
Type: schema.TypeString,
Computed: true,
},
"play_domain": {
Type: schema.TypeString,
Computed: true,
},
"push_domain": {
Type: schema.TypeString,
Computed: true,
},
"stats": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"device_num": {
Type: schema.TypeString,
Computed: true,
},
"ied_num": {
Type: schema.TypeString,
Computed: true,
},
"ipc_num": {
Type: schema.TypeString,
Computed: true,
},
"platform_num": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudVideoSurveillanceSystemGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeGroups"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("in_protocol"); ok {
request["InProtocol"] = v
}
request["IncludeStats"] = true
if v, ok := d.GetOk("name"); ok {
request["Name"] = v
}
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNum"] = 1
var objects []map[string]interface{}
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
nameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewVsClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_video_surveillance_system_groups", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Groups", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Groups", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if nameRegex != nil && !nameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Id"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNum"] = request["PageNum"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"app": object["App"],
"callback": object["Callback"],
"create_time": object["CreatedTime"],
"description": object["Description"],
"enabled": object["Enabled"],
"gb_id": object["GbId"],
"gb_ip": object["GbIp"],
"id": fmt.Sprint(object["Id"]),
"group_id": fmt.Sprint(object["Id"]),
"group_name": object["Name"],
"in_protocol": object["InProtocol"],
"out_protocol": object["OutProtocol"],
"play_domain": object["PlayDomain"],
"push_domain": object["PushDomain"],
"stats": []map[string]interface{}{
{
"ipc_num": object["IpcNum"],
"device_num": object["DeviceNum"],
"ied_num": object["IedNum"],
"platform_num": object["PlatformNum"],
}},
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
names = append(names, object["Name"])
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudVodDomains() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudVodDomainsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"domain_search_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "fuzzy_match",
ValidateFunc: validation.StringInSlice([]string{"fuzzy_match", "pre_match", "suf_match", "full_match"}, false),
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"check_failed", "checking", "configure_failed", "configuring", "offline", "online"}, false),
},
"tags": tagsSchema(),
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"domains": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"gmt_modified": {
Type: schema.TypeString,
Computed: true,
},
"gmt_created": {
Type: schema.TypeString,
Computed: true,
},
"cname": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"ssl_protocol": {
Type: schema.TypeString,
Computed: true,
},
"domain_name": {
Type: schema.TypeString,
Computed: true,
},
"sources": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"source_content": {
Type: schema.TypeString,
Computed: true,
},
"source_port": {
Type: schema.TypeString,
Computed: true,
},
"source_priority": {
Type: schema.TypeString,
Computed: true,
},
"source_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"sand_box": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudVodDomainsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeVodUserDomains"
request := make(map[string]interface{})
if v, ok := d.GetOk("domain_search_type"); ok {
request["DomainSearchType"] = v
}
if v, ok := d.GetOk("status"); ok {
request["DomainStatus"] = v
}
if v, ok := d.GetOk("tags"); ok {
tags := make([]map[string]interface{}, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, map[string]interface{}{
"Key": key,
"Value": value.(string),
})
}
request["Tag"] = tags
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var domainNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
domainNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewVodClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-03-21"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_vod_domains", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Domains.PageData", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Domains.PageData", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if domainNameRegex != nil && !domainNameRegex.MatchString(fmt.Sprint(item["DomainName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DomainName"])]; !ok {
continue
}
}
if statusOk && status != "" && status != item["DomainStatus"] {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"description": object["Description"],
"id": fmt.Sprint(object["DomainName"]),
"domain_name": fmt.Sprint(object["DomainName"]),
"gmt_modified": object["GmtModified"],
"ssl_protocol": object["SslProtocol"],
"gmt_created": object["GmtModified"],
"cname": object["Cname"],
"status": object["DomainStatus"],
"sand_box": object["Sandbox"],
}
if v, ok := object["Sources"].(map[string]interface{})["Source"].([]interface{}); ok {
source := make([]map[string]interface{}, 0)
for _, val := range v {
item := val.(map[string]interface{})
temp := map[string]interface{}{
"source_content": item["Content"],
"source_port": item["Port"],
"source_priority": item["Priority"],
"source_type": item["Type"],
}
source = append(source, temp)
}
mapping["sources"] = source
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["DomainName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("domains", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudVpcBgpGroups() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudVpcBgpGroupsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"router_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "Deleting", "Pending"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"groups": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"auth_key": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"bgp_group_name": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"hold": {
Type: schema.TypeString,
Computed: true,
},
"ip_version": {
Type: schema.TypeString,
Computed: true,
},
"is_fake_asn": {
Type: schema.TypeBool,
Computed: true,
},
"keepalive": {
Type: schema.TypeString,
Computed: true,
},
"local_asn": {
Type: schema.TypeInt,
Computed: true,
},
"peer_asn": {
Type: schema.TypeInt,
Computed: true,
},
"route_limit": {
Type: schema.TypeString,
Computed: true,
},
"router_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudVpcBgpGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeBgpGroups"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("router_id"); ok {
request["RouterId"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var bgpGroupNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
bgpGroupNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_vpc_bgp_groups", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.BgpGroups.BgpGroup", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.BgpGroups.BgpGroup", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if bgpGroupNameRegex != nil && !bgpGroupNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["BgpGroupId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"auth_key": object["AuthKey"],
"id": fmt.Sprint(object["BgpGroupId"]),
"bgp_group_name": object["Name"],
"description": object["Description"],
"hold": object["Hold"],
"ip_version": object["IpVersion"],
"is_fake_asn": object["IsFake"],
"keepalive": object["Keepalive"],
"local_asn": formatInt(object["LocalAsn"]),
"peer_asn": formatInt(object["PeerAsn"]),
"route_limit": object["RouteLimit"],
"router_id": object["RouterId"],
"status": object["Status"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("groups", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudVpcBgpNetworks() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudVpcBgpNetworksRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"router_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "Pending", "Deleting"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"networks": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"dst_cidr_block": {
Type: schema.TypeString,
Computed: true,
},
"router_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudVpcBgpNetworksRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeBgpNetworks"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("router_id"); ok {
request["RouterId"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_vpc_bgp_networks", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.BgpNetworks.BgpNetwork", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.BgpNetworks.BgpNetwork", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["RouterId"], ":", item["DstCidrBlock"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["RouterId"], ":", object["DstCidrBlock"]),
"dst_cidr_block": fmt.Sprint(object["DstCidrBlock"]),
"router_id": object["RouterId"],
"status": object["Status"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("networks", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudVpcBgpPeers() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudVpcBgpPeersRead,
Schema: map[string]*schema.Schema{
"bgp_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"router_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "Deleted", "Deleting", "Modifying", "Pending"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"peers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"auth_key": {
Type: schema.TypeString,
Computed: true,
},
"bfd_multi_hop": {
Type: schema.TypeInt,
Computed: true,
},
"bgp_group_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"bgp_peer_id": {
Type: schema.TypeString,
Computed: true,
},
"bgp_peer_name": {
Type: schema.TypeString,
Computed: true,
},
"bgp_status": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"enable_bfd": {
Type: schema.TypeBool,
Computed: true,
},
"hold": {
Type: schema.TypeString,
Computed: true,
},
"ip_version": {
Type: schema.TypeString,
Computed: true,
},
"is_fake": {
Type: schema.TypeBool,
Computed: true,
},
"keepalive": {
Type: schema.TypeString,
Computed: true,
},
"local_asn": {
Type: schema.TypeString,
Computed: true,
},
"peer_asn": {
Type: schema.TypeString,
Computed: true,
},
"peer_ip_address": {
Type: schema.TypeString,
Computed: true,
},
"route_limit": {
Type: schema.TypeString,
Computed: true,
},
"router_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudVpcBgpPeersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeBgpPeers"
request := make(map[string]interface{})
if v, ok := d.GetOk("bgp_group_id"); ok {
request["BgpGroupId"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("router_id"); ok {
request["RouterId"] = v
}
request["PageSize"] = PageSizeMedium
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_vpc_bgp_peers", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.BgpPeers.BgpPeer", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.BgpPeers.BgpPeer", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["BgpPeerId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"auth_key": object["AuthKey"],
"bfd_multi_hop": formatInt(object["BfdMultiHop"]),
"bgp_group_id": object["BgpGroupId"],
"id": fmt.Sprint(object["BgpPeerId"]),
"bgp_peer_id": fmt.Sprint(object["BgpPeerId"]),
"bgp_peer_name": object["Name"],
"bgp_status": object["BgpStatus"],
"description": object["Description"],
"enable_bfd": object["EnableBfd"],
"hold": object["Hold"],
"ip_version": object["IpVersion"],
"is_fake": object["IsFake"],
"keepalive": object["Keepalive"],
"local_asn": object["LocalAsn"],
"peer_asn": object["PeerAsn"],
"peer_ip_address": object["PeerIpAddress"],
"route_limit": object["RouteLimit"],
"router_id": object["RouterId"],
"status": object["Status"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("peers", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudVpcDhcpOptionsSets() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudVpcDhcpOptionsSetsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"dhcp_options_set_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"domain_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "InUse", "Pending"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"sets": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"associate_vpcs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"associate_status": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"dhcp_options_set_description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"dhcp_options_set_id": {
Type: schema.TypeString,
Computed: true,
},
"dhcp_options_set_name": {
Type: schema.TypeString,
Computed: true,
},
"domain_name": {
Type: schema.TypeString,
Computed: true,
},
"domain_name_servers": {
Type: schema.TypeString,
Computed: true,
},
"owner_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudVpcDhcpOptionsSetsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListDhcpOptionsSets"
request := make(map[string]interface{})
if v, ok := d.GetOk("dhcp_options_set_name"); ok {
request["DhcpOptionsSetName"] = v
}
if v, ok := d.GetOk("domain_name"); ok {
request["DomainName"] = v
}
request["RegionId"] = client.RegionId
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var dhcpOptionsSetNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
dhcpOptionsSetNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_vpc_dhcp_options_sets", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.DhcpOptionsSets", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.DhcpOptionsSets", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if dhcpOptionsSetNameRegex != nil && !dhcpOptionsSetNameRegex.MatchString(fmt.Sprint(item["DhcpOptionsSetName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["DhcpOptionsSetId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"dhcp_options_set_description": object["DhcpOptionsSetDescription"],
"id": fmt.Sprint(object["DhcpOptionsSetId"]),
"dhcp_options_set_id": fmt.Sprint(object["DhcpOptionsSetId"]),
"dhcp_options_set_name": object["DhcpOptionsSetName"],
"domain_name": object["DhcpOptions"].(map[string]interface{})["DomainName"],
"domain_name_servers": object["DhcpOptions"].(map[string]interface{})["DomainNameServers"],
"owner_id": fmt.Sprint(object["OwnerId"]),
"status": object["Status"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["DhcpOptionsSetName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("sets", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudVpcFlowLogs() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudVpcFlowLogsRead,
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"flow_log_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"log_store_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"project_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"resource_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"resource_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"NetworkInterface", "VPC", "VSwitch"}, false),
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Inactive"}, false),
},
"traffic_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"All", "Allow", "Drop"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"logs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"flow_log_id": {
Type: schema.TypeString,
Computed: true,
},
"flow_log_name": {
Type: schema.TypeString,
Computed: true,
},
"log_store_name": {
Type: schema.TypeString,
Computed: true,
},
"project_name": {
Type: schema.TypeString,
Computed: true,
},
"resource_id": {
Type: schema.TypeString,
Computed: true,
},
"resource_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"traffic_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudVpcFlowLogsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeFlowLogs"
request := make(map[string]interface{})
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("flow_log_name"); ok {
request["FlowLogName"] = v
}
if v, ok := d.GetOk("log_store_name"); ok {
request["LogStoreName"] = v
}
if v, ok := d.GetOk("project_name"); ok {
request["ProjectName"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_id"); ok {
request["ResourceId"] = v
}
if v, ok := d.GetOk("resource_type"); ok {
request["ResourceType"] = v
}
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
if v, ok := d.GetOk("traffic_type"); ok {
request["TrafficType"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var flowLogNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
flowLogNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_vpc_flow_logs", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.FlowLogs.FlowLog", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.FlowLogs.FlowLog", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if flowLogNameRegex != nil {
if !flowLogNameRegex.MatchString(fmt.Sprint(item["FlowLogName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["FlowLogId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"description": object["Description"],
"id": fmt.Sprint(object["FlowLogId"]),
"flow_log_id": fmt.Sprint(object["FlowLogId"]),
"flow_log_name": object["FlowLogName"],
"log_store_name": object["LogStoreName"],
"project_name": object["ProjectName"],
"resource_id": object["ResourceId"],
"resource_type": object["ResourceType"],
"status": object["Status"],
"traffic_type": object["TrafficType"],
}
ids = append(ids, fmt.Sprint(object["FlowLogId"]))
names = append(names, object["FlowLogName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("logs", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudVpcIpv6Addresses() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudVpcIpv6AddressesRead,
Schema: map[string]*schema.Schema{
"associated_instance_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "Pending"}, false),
},
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"addresses": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"associated_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"associated_instance_type": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"ipv6_address": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"ipv6_address_id": {
Type: schema.TypeString,
Computed: true,
},
"ipv6_address_name": {
Type: schema.TypeString,
Computed: true,
},
"ipv6_gateway_id": {
Type: schema.TypeString,
Computed: true,
},
"network_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudVpcIpv6AddressesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeIpv6Addresses"
request := make(map[string]interface{})
if v, ok := d.GetOk("associated_instance_id"); ok {
request["AssociatedInstanceId"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("vswitch_id"); ok {
request["VSwitchId"] = v
}
if v, ok := d.GetOk("vpc_id"); ok {
request["VpcId"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_vpc_ipv6_addresses", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Ipv6Addresses.Ipv6Address", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Ipv6Addresses.Ipv6Address", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"associated_instance_id": object["AssociatedInstanceId"],
"associated_instance_type": object["AssociatedInstanceType"],
"ipv6_address": object["Ipv6Address"],
"id": fmt.Sprint(object["Ipv6AddressId"]),
"ipv6_address_id": fmt.Sprint(object["Ipv6AddressId"]),
"ipv6_address_name": object["Ipv6AddressName"],
"ipv6_gateway_id": object["Ipv6GatewayId"],
"network_type": object["NetworkType"],
"status": object["Status"],
"vswitch_id": object["VSwitchId"],
"vpc_id": object["VpcId"],
"create_time": object["AllocationTime"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Ipv6AddressName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("addresses", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudVpcIpv6EgressRules() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudVpcIpv6EgressRulesRead,
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ipv6_egress_rule_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ipv6_gateway_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "Deleting", "Pending"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_type": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"ipv6_egress_rule_id": {
Type: schema.TypeString,
Computed: true,
},
"ipv6_egress_rule_name": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"ipv6_gateway_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudVpcIpv6EgressRulesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeIpv6EgressOnlyRules"
request := make(map[string]interface{})
if v, ok := d.GetOk("instance_id"); ok {
request["InstanceId"] = v
}
if v, ok := d.GetOk("ipv6_egress_rule_name"); ok {
request["Name"] = v
}
request["Ipv6GatewayId"] = d.Get("ipv6_gateway_id")
request["RegionId"] = client.RegionId
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var ipv6EgressRuleNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
ipv6EgressRuleNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_vpc_ipv6_egress_rules", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Ipv6EgressOnlyRules.Ipv6EgressOnlyRule", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Ipv6EgressOnlyRules.Ipv6EgressOnlyRule", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if ipv6EgressRuleNameRegex != nil && !ipv6EgressRuleNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(request["Ipv6GatewayId"], ":", item["Ipv6EgressOnlyRuleId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"description": object["Description"],
"instance_id": object["InstanceId"],
"instance_type": object["InstanceType"],
"id": fmt.Sprint(request["Ipv6GatewayId"], ":", object["Ipv6EgressOnlyRuleId"]),
"ipv6_egress_rule_id": fmt.Sprint(object["Ipv6EgressOnlyRuleId"]),
"ipv6_egress_rule_name": object["Name"],
"status": object["Status"],
"ipv6_gateway_id": request["Ipv6GatewayId"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("rules", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudVpcIpv6Gateways() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudVpcIpv6GatewaysRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ipv6_gateway_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "Deleting", "Pending"}, false),
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"gateways": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"business_status": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"expired_time": {
Type: schema.TypeString,
Computed: true,
},
"instance_charge_type": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"ipv6_gateway_id": {
Type: schema.TypeString,
Computed: true,
},
"ipv6_gateway_name": {
Type: schema.TypeString,
Computed: true,
},
"spec": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudVpcIpv6GatewaysRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeIpv6Gateways"
request := make(map[string]interface{})
if v, ok := d.GetOk("ipv6_gateway_name"); ok {
request["Name"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("vpc_id"); ok {
request["VpcId"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var ipv6GatewayNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
ipv6GatewayNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_vpc_ipv6_gateways", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Ipv6Gateways.Ipv6Gateway", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Ipv6Gateways.Ipv6Gateway", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if ipv6GatewayNameRegex != nil && !ipv6GatewayNameRegex.MatchString(fmt.Sprint(item["Name"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Ipv6GatewayId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"business_status": object["BusinessStatus"],
"create_time": object["CreationTime"],
"description": object["Description"],
"expired_time": object["ExpiredTime"],
"instance_charge_type": convertVpcIpv6GatewayInstanceChargeTypeResponse(object["InstanceChargeType"].(string)),
"id": fmt.Sprint(object["Ipv6GatewayId"]),
"ipv6_gateway_id": fmt.Sprint(object["Ipv6GatewayId"]),
"ipv6_gateway_name": object["Name"],
"spec": object["Spec"],
"status": object["Status"],
"vpc_id": object["VpcId"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["Name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("gateways", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
func convertVpcIpv6GatewayInstanceChargeTypeResponse(source string) string {
switch source {
case "PostPaid":
return "PayAsYouGo"
}
return source
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudVpcIpv6InternetBandwidths() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudVpcIpv6InternetBandwidthsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ipv6_internet_bandwidth_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ipv6_address_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"FinacialLocked", "Normal", "SecurityLocked"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"bandwidths": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"bandwidth": {
Type: schema.TypeInt,
Computed: true,
},
"internet_charge_type": {
Type: schema.TypeString,
Computed: true,
},
"ipv6_address_id": {
Type: schema.TypeString,
Computed: true,
},
"ipv6_gateway_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"ipv6_internet_bandwidth_id": {
Type: schema.TypeString,
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudVpcIpv6InternetBandwidthsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeIpv6Addresses"
request := make(map[string]interface{})
if v, ok := d.GetOk("ipv6_internet_bandwidth_id"); ok {
request["Ipv6InternetBandwidthId"] = v
}
if v, ok := d.GetOk("ipv6_address_id"); ok {
request["Ipv6AddressId"] = v
}
request["RegionId"] = client.RegionId
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_vpc_ipv6_internet_bandwidths", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Ipv6Addresses.Ipv6Address", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Ipv6Addresses.Ipv6Address", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["Ipv6InternetBandwidth"].(map[string]interface{})["Ipv6InternetBandwidthId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Ipv6InternetBandwidth"].(map[string]interface{})["BusinessStatus"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"ipv6_address_id": object["Ipv6AddressId"],
"ipv6_gateway_id": object["Ipv6GatewayId"],
}
if ipv6InternetBandwidth, ok := object["Ipv6InternetBandwidth"]; ok {
if v, ok := ipv6InternetBandwidth.(map[string]interface{}); ok {
if v, ok := v["Bandwidth"]; ok {
mapping["bandwidth"] = formatInt(v)
}
if v, ok := v["BusinessStatus"]; ok {
mapping["status"] = v
}
if v, ok := v["InstanceChargeType"]; ok {
mapping["payment_type"] = convertVpcIpv6InternetBandwidthInstanceChargeTypeResponse(v.(string))
}
if v, ok := v["InternetChargeType"]; ok {
mapping["internet_charge_type"] = v
}
if v, ok := v["Ipv6InternetBandwidthId"]; ok {
mapping["ipv6_internet_bandwidth_id"] = fmt.Sprint(v)
mapping["id"] = fmt.Sprint(v)
}
}
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("bandwidths", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
func convertVpcIpv6InternetBandwidthInstanceChargeTypeResponse(source string) string {
switch source {
case "PostPaid":
return "PayAsYouGo"
}
return source
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudVpcNatIpCidrs() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudVpcNatIpCidrsRead,
Schema: map[string]*schema.Schema{
"nat_gateway_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"nat_ip_cidr_name": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"nat_ip_cidrs": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"cidrs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"is_default": {
Type: schema.TypeBool,
Computed: true,
},
"nat_gateway_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"nat_ip_cidr": {
Type: schema.TypeString,
Computed: true,
},
"nat_ip_cidr_description": {
Type: schema.TypeString,
Computed: true,
},
"nat_ip_cidr_id": {
Type: schema.TypeString,
Computed: true,
},
"nat_ip_cidr_name": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudVpcNatIpCidrsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListNatIpCidrs"
request := make(map[string]interface{})
request["NatGatewayId"] = d.Get("nat_gateway_id")
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("nat_ip_cidrs"); ok {
request["NatIpCidrs"] = v
}
if v, ok := d.GetOk("nat_ip_cidr_name"); ok {
request["NatIpCidrName"] = v
}
if v, ok := d.GetOk("status"); ok {
request["NatIpCidrStatus"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var natIpCidrNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
natIpCidrNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
request["ClientToken"] = buildClientToken("ListNatIpCidrs")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_vpc_nat_ip_cidrs", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.NatIpCidrs", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.NatIpCidrs", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if natIpCidrNameRegex != nil && !natIpCidrNameRegex.MatchString(fmt.Sprint(item["NatIpCidrName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprintf("%s:%s", item["NatGatewayId"], item["NatIpCidr"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"create_time": object["CreationTime"],
"is_default": object["IsDefault"],
"nat_gateway_id": object["NatGatewayId"],
"id": fmt.Sprintf("%s:%s", object["NatGatewayId"], object["NatIpCidr"]),
"nat_ip_cidr": fmt.Sprint(object["NatIpCidr"]),
"nat_ip_cidr_description": object["NatIpCidrDescription"],
"nat_ip_cidr_id": object["NatIpCidrId"],
"status": object["NatIpCidrStatus"],
"nat_ip_cidr_name": object["NatIpCidrName"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, mapping["nat_ip_cidr_name"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("cidrs", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudVpcNatIps() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudVpcNatIpsRead,
Schema: map[string]*schema.Schema{
"nat_gateway_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"nat_ip_cidr": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"nat_ip_name": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"nat_ip_ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "Creating", "Deleting"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ips": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"is_default": {
Type: schema.TypeBool,
Computed: true,
},
"nat_gateway_id": {
Type: schema.TypeString,
Computed: true,
},
"nat_ip": {
Type: schema.TypeString,
Computed: true,
},
"nat_ip_cidr": {
Type: schema.TypeString,
Computed: true,
},
"nat_ip_description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"nat_ip_id": {
Type: schema.TypeString,
Computed: true,
},
"nat_ip_name": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudVpcNatIpsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListNatIps"
request := make(map[string]interface{})
request["NatGatewayId"] = d.Get("nat_gateway_id")
if v, ok := d.GetOk("nat_ip_cidr"); ok {
request["NatIpCidr"] = v
}
if v, ok := d.GetOk("nat_ip_name"); ok {
request["NatIpName"] = v
}
if v, ok := d.GetOk("nat_ip_ids"); ok {
request["NatIpIds"] = v
}
if v, ok := d.GetOk("status"); ok {
request["NatIpStatus"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("status"); ok {
request["NatIpStatus"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var natIpNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
natIpNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
request["ClientToken"] = buildClientToken("ListNatIps")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_vpc_nat_ips", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.NatIps", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.NatIps", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if natIpNameRegex != nil && !natIpNameRegex.MatchString(fmt.Sprint(item["NatIpName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprintf("%s:%s", item["NatGatewayId"], item["NatIpId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"is_default": object["IsDefault"],
"nat_gateway_id": object["NatGatewayId"],
"nat_ip": object["NatIp"],
"nat_ip_cidr": object["NatIpCidr"],
"nat_ip_description": object["NatIpDescription"],
"id": fmt.Sprintf("%s:%s", object["NatGatewayId"], object["NatIpId"]),
"nat_ip_id": fmt.Sprint(object["NatIpId"]),
"nat_ip_name": object["NatIpName"],
"status": object["NatIpStatus"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["NatIpName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("ips", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudVpcTrafficMirrorFilterEgressRules() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudVpcTrafficMirrorFilterEgressRulesRead,
Schema: map[string]*schema.Schema{
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Created", "Creating", "Deleting", "Modifying"}, false),
},
"traffic_mirror_filter_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"destination_cidr_block": {
Type: schema.TypeString,
Computed: true,
},
"destination_port_range": {
Type: schema.TypeString,
Computed: true,
},
"priority": {
Type: schema.TypeInt,
Computed: true,
},
"rule_action": {
Type: schema.TypeString,
Computed: true,
},
"protocol": {
Type: schema.TypeString,
Computed: true,
},
"source_cidr_block": {
Type: schema.TypeString,
Computed: true,
},
"source_port_range": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"traffic_mirror_filter_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"traffic_mirror_filter_rule_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudVpcTrafficMirrorFilterEgressRulesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListTrafficMirrorFilters"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
request["TrafficMirrorFilterIds"] = []string{fmt.Sprint(d.Get("traffic_mirror_filter_id"))}
request["MaxResults"] = PageSizeSmall
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_vpc_traffic_mirror_filter_egress_rules", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.TrafficMirrorFilters", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.TrafficMirrorFilters", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
EgressRules := v.(map[string]interface{})["EgressRules"]
if EgressRulesMap, ok := EgressRules.([]interface{}); ok {
for _, v := range EgressRulesMap {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["TrafficMirrorFilterId"], ":", item["TrafficMirrorFilterRuleId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["TrafficMirrorFilterRuleStatus"].(string) {
continue
}
objects = append(objects, item)
}
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"destination_cidr_block": object["DestinationCidrBlock"],
"destination_port_range": object["DestinationPortRange"],
"priority": object["Priority"],
"rule_action": object["Action"],
"protocol": object["Protocol"],
"source_cidr_block": object["SourceCidrBlock"],
"source_port_range": object["SourcePortRange"],
"status": object["TrafficMirrorFilterRuleStatus"],
"traffic_mirror_filter_id": object["TrafficMirrorFilterId"],
"id": fmt.Sprint(object["TrafficMirrorFilterId"], ":", object["TrafficMirrorFilterRuleId"]),
"traffic_mirror_filter_rule_id": fmt.Sprint(object["TrafficMirrorFilterRuleId"]),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("rules", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudVpcTrafficMirrorFilterIngressRules() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudVpcTrafficMirrorFilterIngressRulesRead,
Schema: map[string]*schema.Schema{
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Created", "Creating", "Deleting", "Modifying"}, false),
},
"traffic_mirror_filter_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"rules": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"destination_cidr_block": {
Type: schema.TypeString,
Computed: true,
},
"destination_port_range": {
Type: schema.TypeString,
Computed: true,
},
"priority": {
Type: schema.TypeInt,
Computed: true,
},
"rule_action": {
Type: schema.TypeString,
Computed: true,
},
"protocol": {
Type: schema.TypeString,
Computed: true,
},
"source_cidr_block": {
Type: schema.TypeString,
Computed: true,
},
"source_port_range": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"traffic_mirror_filter_id": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"traffic_mirror_filter_rule_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudVpcTrafficMirrorFilterIngressRulesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListTrafficMirrorFilters"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
request["TrafficMirrorFilterIds"] = []string{fmt.Sprint(d.Get("traffic_mirror_filter_id"))}
request["MaxResults"] = PageSizeSmall
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_vpc_traffic_mirror_filter_ingress_rules", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.TrafficMirrorFilters", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.TrafficMirrorFilters", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
EgressRules := v.(map[string]interface{})["IngressRules"]
if EgressRulesMap, ok := EgressRules.([]interface{}); ok {
for _, v := range EgressRulesMap {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["TrafficMirrorFilterId"], ":", item["TrafficMirrorFilterRuleId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["TrafficMirrorFilterRuleStatus"].(string) {
continue
}
objects = append(objects, item)
}
}
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"destination_cidr_block": object["DestinationCidrBlock"],
"destination_port_range": object["DestinationPortRange"],
"priority": formatInt(object["Priority"]),
"rule_action": object["Action"],
"protocol": object["Protocol"],
"source_cidr_block": object["SourceCidrBlock"],
"source_port_range": object["SourcePortRange"],
"status": object["TrafficMirrorFilterRuleStatus"],
"traffic_mirror_filter_id": object["TrafficMirrorFilterId"],
"id": fmt.Sprint(object["TrafficMirrorFilterId"], ":", object["TrafficMirrorFilterRuleId"]),
"traffic_mirror_filter_rule_id": fmt.Sprint(object["TrafficMirrorFilterRuleId"]),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("rules", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudVpcTrafficMirrorFilters() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudVpcTrafficMirrorFiltersRead,
Schema: map[string]*schema.Schema{
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Created", "Creating", "Deleting", "Modifying"}, false),
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"traffic_mirror_filter_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(2, 128),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"filters": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"status": {
Type: schema.TypeString,
Computed: true,
},
"traffic_mirror_filter_description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"traffic_mirror_filter_id": {
Type: schema.TypeString,
Computed: true,
},
"traffic_mirror_filter_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudVpcTrafficMirrorFiltersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListTrafficMirrorFilters"
request := make(map[string]interface{})
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("traffic_mirror_filter_name"); ok {
request["TrafficMirrorFilterName"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var trafficMirrorFilterNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
trafficMirrorFilterNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_vpc_traffic_mirror_filters", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.TrafficMirrorFilters", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.TrafficMirrorFilters", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if trafficMirrorFilterNameRegex != nil && !trafficMirrorFilterNameRegex.MatchString(fmt.Sprint(item["TrafficMirrorFilterName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["TrafficMirrorFilterId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["TrafficMirrorFilterStatus"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"status": object["TrafficMirrorFilterStatus"],
"traffic_mirror_filter_description": object["TrafficMirrorFilterDescription"],
"id": fmt.Sprint(object["TrafficMirrorFilterId"]),
"traffic_mirror_filter_id": fmt.Sprint(object["TrafficMirrorFilterId"]),
"traffic_mirror_filter_name": object["TrafficMirrorFilterName"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["TrafficMirrorFilterName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("filters", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudVpcTrafficMirrorService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudVpcTrafficMirrorServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudVpcTrafficMirrorServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("VpcTrafficMirrorServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
request := map[string]interface{}{}
action := "GetTrafficMirrorServiceStatus"
request["ClientToken"] = buildClientToken(action)
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_vpc_traffic_mirror_service", action, AlibabaCloudSdkGoERROR)
}
if v, ok := response["Enabled"]; ok && v.(bool) {
d.SetId("VpcTrafficMirrorServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
action = "OpenTrafficMirrorService"
request["ClientToken"] = buildClientToken(action)
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ORDER.OPEND"}) {
d.SetId("VpcTrafficMirrorServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_vpc_traffic_mirror_service", action, AlibabaCloudSdkGoERROR)
}
d.SetId("VpcTrafficMirrorServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudVpcTrafficMirrorSessions() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudVpcTrafficMirrorSessionsRead,
Schema: map[string]*schema.Schema{
"enabled": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"priority": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Created", "Creating", "Deleting", "Modifying"}, false),
},
"traffic_mirror_filter_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"traffic_mirror_session_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"traffic_mirror_source_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"traffic_mirror_target_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"sessions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enabled": {
Type: schema.TypeBool,
Computed: true,
},
"packet_length": {
Type: schema.TypeInt,
Computed: true,
},
"priority": {
Type: schema.TypeInt,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"traffic_mirror_filter_id": {
Type: schema.TypeString,
Computed: true,
},
"traffic_mirror_session_business_status": {
Type: schema.TypeString,
Computed: true,
},
"traffic_mirror_session_description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"traffic_mirror_session_id": {
Type: schema.TypeString,
Computed: true,
},
"traffic_mirror_session_name": {
Type: schema.TypeString,
Computed: true,
},
"traffic_mirror_source_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"traffic_mirror_target_id": {
Type: schema.TypeString,
Computed: true,
},
"traffic_mirror_target_type": {
Type: schema.TypeString,
Computed: true,
},
"virtual_network_id": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudVpcTrafficMirrorSessionsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ListTrafficMirrorSessions"
request := make(map[string]interface{})
if v, ok := d.GetOk("enabled"); ok {
request["Enabled"] = v
}
if v, ok := d.GetOk("priority"); ok {
request["Priority"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("traffic_mirror_filter_id"); ok {
request["TrafficMirrorFilterId"] = v
}
if v, ok := d.GetOk("traffic_mirror_session_name"); ok {
request["TrafficMirrorSessionName"] = v
}
if v, ok := d.GetOk("traffic_mirror_source_id"); ok {
request["TrafficMirrorSourceId"] = v
}
if v, ok := d.GetOk("traffic_mirror_target_id"); ok {
request["TrafficMirrorTargetId"] = v
}
request["MaxResults"] = PageSizeLarge
var objects []map[string]interface{}
var trafficMirrorSessionNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
trafficMirrorSessionNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_vpc_traffic_mirror_sessions", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.TrafficMirrorSessions", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.TrafficMirrorSessions", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if trafficMirrorSessionNameRegex != nil && !trafficMirrorSessionNameRegex.MatchString(fmt.Sprint(item["TrafficMirrorSessionName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["TrafficMirrorSessionId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["TrafficMirrorSessionStatus"].(string) {
continue
}
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"enabled": object["Enabled"],
"packet_length": formatInt(object["PacketLength"]),
"priority": formatInt(object["Priority"]),
"status": object["TrafficMirrorSessionStatus"],
"traffic_mirror_filter_id": object["TrafficMirrorFilterId"],
"traffic_mirror_session_business_status": object["TrafficMirrorSessionBusinessStatus"],
"traffic_mirror_session_description": object["TrafficMirrorSessionDescription"],
"id": fmt.Sprint(object["TrafficMirrorSessionId"]),
"traffic_mirror_session_id": fmt.Sprint(object["TrafficMirrorSessionId"]),
"traffic_mirror_session_name": object["TrafficMirrorSessionName"],
"traffic_mirror_source_ids": object["TrafficMirrorSourceIds"],
"traffic_mirror_target_id": object["TrafficMirrorTargetId"],
"traffic_mirror_target_type": object["TrafficMirrorTargetType"],
"virtual_network_id": formatInt(object["VirtualNetworkId"]),
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["TrafficMirrorSessionName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("sessions", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudVpcs() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudVpcsRead,
Schema: map[string]*schema.Schema{
"cidr_block": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"dhcp_options_set_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"is_default": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "Pending"}, false),
},
"tags": tagsSchema(),
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"vpc_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vpc_owner_id": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"page_number": {
Type: schema.TypeInt,
Optional: true,
},
"page_size": {
Type: schema.TypeInt,
Optional: true,
Default: 50,
},
"vpcs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"creation_time": {
Type: schema.TypeString,
Computed: true,
},
"cidr_block": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"ipv6_cidr_block": {
Type: schema.TypeString,
Computed: true,
},
"is_default": {
Type: schema.TypeBool,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"route_table_id": {
Type: schema.TypeString,
Computed: true,
},
"router_id": {
Type: schema.TypeString,
Computed: true,
},
"vrouter_id": {
Type: schema.TypeString,
Computed: true,
},
"secondary_cidr_blocks": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"user_cidrs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"vswitch_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"total_count": {
Type: schema.TypeInt,
Computed: true,
},
},
}
}
func dataSourceAlicloudVpcsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeVpcs"
request := make(map[string]interface{})
if v, ok := d.GetOk("dhcp_options_set_id"); ok {
request["DhcpOptionsSetId"] = v
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
if v, ok := d.GetOkExists("is_default"); ok {
request["IsDefault"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("tags"); ok {
tags := make([]map[string]interface{}, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, map[string]interface{}{
"Key": key,
"Value": value.(string),
})
}
request["Tag"] = tags
}
if v, ok := d.GetOk("vpc_name"); ok {
request["VpcName"] = v
}
if v, ok := d.GetOk("vpc_owner_id"); ok {
request["VpcOwnerId"] = v
}
if v, ok := d.GetOk("page_number"); ok && v.(int) > 0 {
request["PageNumber"] = v.(int)
} else {
request["PageNumber"] = 1
}
if v, ok := d.GetOk("page_size"); ok && v.(int) > 0 {
request["PageSize"] = v.(int)
} else {
request["PageSize"] = PageSizeLarge
}
var objects []interface{}
var vpcNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
vpcNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_vpcs", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.Vpcs.Vpc", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Vpcs.Vpc", response)
}
result, _ := resp.([]interface{})
if isPagingRequest(d) {
objects = result
break
}
for _, v := range result {
item := v.(map[string]interface{})
if v, ok := d.GetOk("cidr_block"); ok && v.(string) != "" && item["CidrBlock"].(string) != v.(string) {
continue
}
if v, ok := d.GetOk("vswitch_id"); ok && !vpcVswitchIdListContains(item, v.(string)) {
continue
}
if vpcNameRegex != nil {
if !vpcNameRegex.MatchString(fmt.Sprint(item["VpcName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["VpcId"])]; !ok {
continue
}
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, v := range objects {
object := v.(map[string]interface{})
mapping := map[string]interface{}{
"region_id": object["RegionId"],
"creation_time": object["CreationTime"],
"cidr_block": object["CidrBlock"],
"description": object["Description"],
"ipv6_cidr_block": object["Ipv6CidrBlock"],
"is_default": object["IsDefault"],
"resource_group_id": object["ResourceGroupId"],
"router_id": object["VRouterId"],
"vrouter_id": object["VRouterId"],
"secondary_cidr_blocks": object["SecondaryCidrBlocks"].(map[string]interface{})["SecondaryCidrBlock"],
"status": object["Status"],
"user_cidrs": object["UserCidrs"].(map[string]interface{})["UserCidr"],
"vswitch_ids": object["VSwitchIds"].(map[string]interface{})["VSwitchId"],
"id": fmt.Sprint(object["VpcId"]),
"vpc_id": fmt.Sprint(object["VpcId"]),
"vpc_name": object["VpcName"],
}
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags.Tag", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["Key"].(string)
value := t.(map[string]interface{})["Value"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
ids = append(ids, fmt.Sprint(object["VpcId"]))
names = append(names, object["VpcName"])
s = append(s, mapping)
continue
}
vpcService := VpcService{client}
id := fmt.Sprint(object["VpcId"])
getResp, err := vpcService.DescribeRouteTableList(id)
if err != nil {
return WrapError(err)
}
mapping["route_table_id"] = getResp["RouteTableId"]
ids = append(ids, fmt.Sprint(object["VpcId"]))
names = append(names, object["VpcName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("vpcs", s); err != nil {
return WrapError(err)
}
if err := d.Set("total_count", formatInt(response["TotalCount"])); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
func vpcVswitchIdListContains(vpc map[string]interface{}, vswitchId string) bool {
if v, ok := vpc["VSwitchIds"].(map[string]interface{})["VSwitchId"].([]interface{}); ok {
for _, idListItem := range v {
if fmt.Sprint(idListItem) == vswitchId {
return true
}
}
return false
}
return false
}
package alicloud
import (
"regexp"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudVpnConnections() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudVpnConnectionsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
MinItems: 1,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"vpn_gateway_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"customer_gateway_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"connections": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"customer_gateway_id": {
Type: schema.TypeString,
Computed: true,
},
"vpn_gateway_id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"local_subnet": {
Type: schema.TypeString,
Computed: true,
},
"remote_subnet": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"effect_immediately": {
Type: schema.TypeBool,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"ipsec_config": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ipsec_enc_alg": {
Type: schema.TypeString,
Optional: true,
},
"ipsec_auth_alg": {
Type: schema.TypeString,
Optional: true,
},
"ipsec_pfs": {
Type: schema.TypeString,
Optional: true,
},
"ipsec_lifetime": {
Type: schema.TypeInt,
Optional: true,
},
},
},
},
"ike_config": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"psk": {
Type: schema.TypeString,
Optional: true,
},
"ike_version": {
Type: schema.TypeString,
Optional: true,
},
"ike_mode": {
Type: schema.TypeString,
Optional: true,
},
"ike_enc_alg": {
Type: schema.TypeString,
Optional: true,
},
"ike_auth_alg": {
Type: schema.TypeString,
Optional: true,
},
"ike_pfs": {
Type: schema.TypeString,
Optional: true,
},
"ike_lifetime": {
Type: schema.TypeInt,
Optional: true,
},
"ike_local_id": {
Type: schema.TypeString,
Optional: true,
},
"ike_remote_id": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
},
},
},
},
}
}
func dataSourceAlicloudVpnConnectionsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := vpc.CreateDescribeVpnConnectionsRequest()
request.RegionId = string(client.Region)
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var allVpnConns []vpc.VpnConnection
if v, ok := d.GetOk("vpn_gateway_id"); ok && v.(string) != "" {
request.VpnGatewayId = v.(string)
}
if v, ok := d.GetOk("customer_gateway_id"); ok && v.(string) != "" {
request.CustomerGatewayId = v.(string)
}
for {
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeVpnConnections(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_vpn_connections", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*vpc.DescribeVpnConnectionsResponse)
if len(response.VpnConnections.VpnConnection) < 1 {
break
}
allVpnConns = append(allVpnConns, response.VpnConnections.VpnConnection...)
if len(response.VpnConnections.VpnConnection) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
var filteredVpnConns []vpc.VpnConnection
var reg *regexp.Regexp
var ids []string
if v, ok := d.GetOk("ids"); ok && len(v.([]interface{})) > 0 {
for _, item := range v.([]interface{}) {
if item == nil {
continue
}
ids = append(ids, strings.Trim(item.(string), " "))
}
}
if nameRegex, ok := d.GetOk("name_regex"); ok && nameRegex.(string) != "" {
if r, err := regexp.Compile(nameRegex.(string)); err == nil {
reg = r
} else {
return WrapError(err)
}
}
for _, vpnConn := range allVpnConns {
if reg != nil {
if !reg.MatchString(vpnConn.Name) {
continue
}
}
if ids != nil && len(ids) != 0 {
for _, id := range ids {
if vpnConn.VpnConnectionId == id {
filteredVpnConns = append(filteredVpnConns, vpnConn)
}
}
} else {
filteredVpnConns = append(filteredVpnConns, vpnConn)
}
}
return vpnConnectionsDecriptionAttributes(d, filteredVpnConns, meta)
}
func vpnConnectionsDecriptionAttributes(d *schema.ResourceData, vpnSetTypes []vpc.VpnConnection, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpnGatewayService := VpnGatewayService{client}
var ids []string
var names []string
var s []map[string]interface{}
for _, conn := range vpnSetTypes {
mapping := map[string]interface{}{
"customer_gateway_id": conn.CustomerGatewayId,
"vpn_gateway_id": conn.VpnGatewayId,
"id": conn.VpnConnectionId,
"name": conn.Name,
"local_subnet": conn.LocalSubnet,
"remote_subnet": conn.RemoteSubnet,
"create_time": TimestampToStr(conn.CreateTime),
"effect_immediately": conn.EffectImmediately,
"status": conn.Status,
"ike_config": vpnGatewayService.ParseIkeConfig(conn.IkeConfig),
"ipsec_config": vpnGatewayService.ParseIpsecConfig(conn.IpsecConfig),
}
ids = append(ids, conn.VpnConnectionId)
names = append(names, conn.Name)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("connections", s); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudVpnCustomerGateways() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudVpnCgwsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
MinItems: 1,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"gateways": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"ip_address": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudVpnCgwsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := vpc.CreateDescribeCustomerGatewaysRequest()
request.RegionId = client.RegionId
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var allCgws []vpc.CustomerGateway
for {
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeCustomerGateways(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "aliclioud_vpn_customer_gateways", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*vpc.DescribeCustomerGatewaysResponse)
if len(response.CustomerGateways.CustomerGateway) < 1 {
break
}
allCgws = append(allCgws, response.CustomerGateways.CustomerGateway...)
if len(response.CustomerGateways.CustomerGateway) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}
var filteredCgws []vpc.CustomerGateway
var reg *regexp.Regexp
var ids []string
if v, ok := d.GetOk("ids"); ok && len(v.([]interface{})) > 0 {
for _, item := range v.([]interface{}) {
if item == nil {
continue
}
ids = append(ids, strings.Trim(item.(string), " "))
}
}
if nameRegex, ok := d.GetOk("name_regex"); ok && nameRegex.(string) != "" {
if r, err := regexp.Compile(nameRegex.(string)); err == nil {
reg = r
} else {
return WrapError(err)
}
}
for _, cgw := range allCgws {
if reg != nil {
if !reg.MatchString(cgw.Name) {
continue
}
}
if ids != nil && len(ids) != 0 {
for _, id := range ids {
if cgw.CustomerGatewayId == id {
filteredCgws = append(filteredCgws, cgw)
}
}
} else {
filteredCgws = append(filteredCgws, cgw)
}
}
return vpnCgwsDecriptionAttributes(d, filteredCgws, meta)
}
func vpnCgwsDecriptionAttributes(d *schema.ResourceData, vpnSetTypes []vpc.CustomerGateway, meta interface{}) error {
var ids []string
var names []string
var s []map[string]interface{}
for _, vpn := range vpnSetTypes {
mapping := map[string]interface{}{
"id": vpn.CustomerGatewayId,
"name": vpn.Name,
"ip_address": vpn.IpAddress,
"description": vpn.Description,
"create_time": TimestampToStr(vpn.CreateTime),
}
ids = append(ids, vpn.CustomerGatewayId)
names = append(names, vpn.Name)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("gateways", s); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"regexp"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudVpnGateways() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudVpnsRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
MinItems: 1,
},
"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Init", "Provisioning", "Active", "Updating", "Deleting"}, false),
},
"business_status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Normal", "FinancialLocked"}, false),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
// Computed values
"gateways": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"internet_ip": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"end_time": {
Type: schema.TypeString,
Computed: true,
},
"specification": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"business_status": {
Type: schema.TypeString,
Computed: true,
},
"instance_charge_type": {
Type: schema.TypeString,
Computed: true,
},
"enable_ipsec": {
Type: schema.TypeString,
Computed: true,
},
"enable_ssl": {
Type: schema.TypeString,
Computed: true,
},
"ssl_connections": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudVpnsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := vpc.CreateDescribeVpnGatewaysRequest()
request.RegionId = client.RegionId
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
var allVpns []vpc.VpnGateway
if v, ok := d.GetOk("vpc_id"); ok && v.(string) != "" {
request.VpcId = v.(string)
}
if v, ok := d.GetOk("status"); ok && v.(string) != "" {
request.Status = strings.ToLower(v.(string))
}
if v, ok := d.GetOk("business_status"); ok && v.(string) != "" {
request.BusinessStatus = v.(string)
}
for {
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeVpnGateways(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_vpn_gateways", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*vpc.DescribeVpnGatewaysResponse)
if len(response.VpnGateways.VpnGateway) < 1 {
break
}
allVpns = append(allVpns, response.VpnGateways.VpnGateway...)
if len(response.VpnGateways.VpnGateway) < PageSizeLarge {
break
}
if page, err := getNextpageNumber(request.PageNumber); err != nil {
return WrapError(err)
} else {
request.PageNumber = page
}
}
var filteredVpns []vpc.VpnGateway
var reg *regexp.Regexp
var ids []string
if v, ok := d.GetOk("ids"); ok && len(v.([]interface{})) > 0 {
for _, item := range v.([]interface{}) {
if item == nil {
continue
}
ids = append(ids, strings.Trim(item.(string), " "))
}
}
if nameRegex, ok := d.GetOk("name_regex"); ok && nameRegex.(string) != "" {
if r, err := regexp.Compile(nameRegex.(string)); err == nil {
reg = r
} else {
return WrapError(err)
}
}
for _, vpn := range allVpns {
if reg != nil {
if !reg.MatchString(vpn.Name) {
continue
}
}
if ids != nil && len(ids) != 0 {
for _, id := range ids {
if vpn.VpnGatewayId == id {
filteredVpns = append(filteredVpns, vpn)
}
}
} else {
filteredVpns = append(filteredVpns, vpn)
}
}
return vpnsDecriptionAttributes(d, filteredVpns, meta)
}
func convertStatus(lower string) string {
upStr := strings.ToUpper(lower)
wholeStr := string(upStr[0]) + lower[1:]
return wholeStr
}
func convertChargeType(originType string) string {
if string("PostpayByFlow") == originType {
return string(PostPaid)
} else {
return string(PrePaid)
}
}
func vpnsDecriptionAttributes(d *schema.ResourceData, vpnSetTypes []vpc.VpnGateway, meta interface{}) error {
var ids []string
var names []string
var s []map[string]interface{}
for _, vpn := range vpnSetTypes {
mapping := map[string]interface{}{
"id": vpn.VpnGatewayId,
"vpc_id": vpn.VpcId,
"internet_ip": vpn.InternetIp,
"create_time": TimestampToStr(vpn.CreateTime),
"end_time": TimestampToStr(vpn.EndTime),
"specification": vpn.Spec,
"name": vpn.Name,
"description": vpn.Description,
"status": convertStatus(vpn.Status),
"business_status": vpn.BusinessStatus,
"instance_charge_type": convertChargeType(vpn.ChargeType),
"enable_ipsec": vpn.IpsecVpn,
"enable_ssl": vpn.SslVpn,
"ssl_connections": vpn.SslMaxConnections,
}
ids = append(ids, vpn.VpnGatewayId)
names = append(names, vpn.Name)
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("gateways", s); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudVsService() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudVsServiceRead,
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"On", "Off"}, false),
Optional: true,
Default: "Off",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAlicloudVsServiceRead(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("enable"); !ok || v.(string) != "On" {
d.SetId("VsServiceHasNotBeenOpened")
d.Set("status", "")
return nil
}
action := "OpenVsService"
request := map[string]interface{}{}
conn, err := meta.(*connectivity.AliyunClient).NewTeaCommonClient(connectivity.OpenVsService)
if err != nil {
return WrapError(err)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"QPS Limit Exceeded"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
addDebug(action, response, nil)
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ORDER.OPEND"}) {
d.SetId("VsServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_vs_service", action, AlibabaCloudSdkGoERROR)
}
d.SetId("VsServiceHasBeenOpened")
d.Set("status", "Opened")
return nil
}
package alicloud
import (
"fmt"
"regexp"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudVswitches() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudVswitchesRead,
Schema: map[string]*schema.Schema{
"cidr_block": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"is_default": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"route_table_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Available", "Pending"}, false),
},
"tags": tagsSchema(),
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"vswitch_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vswitch_owner_id": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"vswitches": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"creation_time": {
Type: schema.TypeString,
Computed: true,
},
"available_ip_address_count": {
Type: schema.TypeInt,
Computed: true,
},
"cidr_block": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"is_default": {
Type: schema.TypeBool,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"route_table_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_name": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudVswitchesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeVSwitches"
request := make(map[string]interface{})
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
if v, ok := d.GetOkExists("is_default"); ok {
request["IsDefault"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("route_table_id"); ok {
request["RouteTableId"] = v
}
if v, ok := d.GetOk("tags"); ok {
tags := make([]map[string]interface{}, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, map[string]interface{}{
"Key": key,
"Value": value.(string),
})
}
request["Tag"] = tags
}
if v, ok := d.GetOk("vswitch_name"); ok {
request["VSwitchName"] = v
}
if v, ok := d.GetOk("vswitch_owner_id"); ok {
request["VSwitchOwnerId"] = v
}
if v, ok := d.GetOk("vpc_id"); ok {
request["VpcId"] = v
}
if v, ok := d.GetOk("zone_id"); ok {
request["ZoneId"] = v
}
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
var objects []map[string]interface{}
var vSwitchNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
vSwitchNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOk("status")
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_vswitches", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.VSwitches.VSwitch", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.VSwitches.VSwitch", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if vSwitchNameRegex != nil {
if !vSwitchNameRegex.MatchString(fmt.Sprint(item["VSwitchName"])) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["VSwitchId"])]; !ok {
continue
}
}
if v, ok := d.GetOk("cidr_block"); ok && fmt.Sprint(item["CidrBlock"]) != Trim(v.(string)) {
continue
}
if statusOk && status.(string) != "" && status.(string) != item["Status"].(string) {
continue
}
objects = append(objects, item)
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"creation_time": object["CreationTime"],
"available_ip_address_count": object["AvailableIpAddressCount"],
"cidr_block": object["CidrBlock"],
"description": object["Description"],
"is_default": object["IsDefault"],
"resource_group_id": object["ResourceGroupId"],
"route_table_id": object["RouteTable"].(map[string]interface{})["RouteTableId"],
"status": object["Status"],
"id": fmt.Sprint(object["VSwitchId"]),
"vswitch_id": fmt.Sprint(object["VSwitchId"]),
"vswitch_name": object["VSwitchName"],
"name": object["VSwitchName"],
"vpc_id": object["VpcId"],
"zone_id": object["ZoneId"],
}
tags := make(map[string]interface{})
t, _ := jsonpath.Get("$.Tags.Tag", object)
if t != nil {
for _, t := range t.([]interface{}) {
key := t.(map[string]interface{})["Key"].(string)
value := t.(map[string]interface{})["Value"].(string)
if !ignoredTags(key, value) {
tags[key] = value
}
}
}
mapping["tags"] = tags
ids = append(ids, fmt.Sprint(object["VSwitchId"]))
names = append(names, object["VSwitchName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("vswitches", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudWafCertificates() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudWafCertificatesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"domain": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"certificates": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"certificate_id": {
Type: schema.TypeString,
Computed: true,
},
"certificate_name": {
Type: schema.TypeString,
Computed: true,
},
"common_name": {
Type: schema.TypeString,
Computed: true,
},
"domain": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"is_using": {
Type: schema.TypeBool,
Computed: true,
},
"sans": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
},
}
}
func dataSourceAlicloudWafCertificatesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeCertificates"
request := make(map[string]interface{})
if v, ok := d.GetOk("domain"); ok {
request["Domain"] = v
}
request["InstanceId"] = d.Get("instance_id")
var objects []map[string]interface{}
var certificateNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
certificateNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
parts, err := ParseResourceId(vv.(string), 3)
if err != nil {
return WrapError(err)
}
idsMap[parts[2]] = parts[2]
}
}
var response map[string]interface{}
conn, err := client.NewWafClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_waf_certificates", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.Certificates", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.Certificates", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if certificateNameRegex != nil && !certificateNameRegex.MatchString(fmt.Sprint(item["CertificateName"])) {
continue
}
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["CertificateId"])]; !ok {
continue
}
}
objects = append(objects, item)
}
ids := make([]string, 0)
names := make([]interface{}, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"id": fmt.Sprint(object["CertificateId"]),
"certificate_id": fmt.Sprint(object["CertificateId"]),
"certificate_name": object["CertificateName"],
"common_name": object["CommonName"],
"domain": request["Domain"],
"instance_id": request["InstanceId"],
"is_using": object["IsUsing"],
"sans": object["Sans"],
}
ids = append(ids, fmt.Sprint(mapping["id"]))
names = append(names, object["CertificateName"])
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("certificates", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudWafDomains() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudWafDomainsRead,
Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
ForceNew: true,
},
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"domains": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cluster_type": {
Type: schema.TypeString,
Computed: true,
},
"cname": {
Type: schema.TypeString,
Computed: true,
},
"connection_time": {
Type: schema.TypeInt,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"domain_name": {
Type: schema.TypeString,
Computed: true,
},
"domain": {
Type: schema.TypeString,
Computed: true,
},
"http2_port": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"http_port": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"http_to_user_ip": {
Type: schema.TypeString,
Computed: true,
},
"https_port": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"https_redirect": {
Type: schema.TypeString,
Computed: true,
},
"is_access_product": {
Type: schema.TypeString,
Computed: true,
},
"load_balancing": {
Type: schema.TypeString,
Computed: true,
},
"log_headers": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Computed: true,
},
"value": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"read_time": {
Type: schema.TypeInt,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
},
"source_ips": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"version": {
Type: schema.TypeInt,
Computed: true,
},
"write_time": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func dataSourceAlicloudWafDomainsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeDomainNames"
request := make(map[string]interface{})
request["InstanceId"] = d.Get("instance_id")
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
var domainNameRegex *regexp.Regexp
if v, ok := d.GetOk("name_regex"); ok {
r, err := regexp.Compile(v.(string))
if err != nil {
return WrapError(err)
}
domainNameRegex = r
}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
var response map[string]interface{}
conn, err := client.NewWafClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_waf_domains", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
ids := make([]string, 0)
names := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range response["DomainNames"].([]interface{}) {
if domainNameRegex != nil {
if !domainNameRegex.MatchString(object.(string)) {
continue
}
}
if len(idsMap) > 0 {
if _, ok := idsMap[object.(string)]; !ok {
continue
}
}
mapping := map[string]interface{}{
"id": fmt.Sprint(object),
"domain_name": object,
"domain": object,
}
ids = append(ids, fmt.Sprint(object.(string)))
if detailedEnabled := d.Get("enable_details"); !detailedEnabled.(bool) {
names = append(names, object.(string))
s = append(s, mapping)
continue
}
waf_openapiService := Waf_openapiService{client}
id := fmt.Sprint(request["InstanceId"], ":", object.(string))
getResp, err := waf_openapiService.DescribeWafDomain(id)
if err != nil {
return WrapError(err)
}
mapping["cluster_type"] = convertClusterTypeResponse(formatInt(getResp["ClusterType"]))
mapping["cname"] = getResp["Cname"]
mapping["connection_time"] = getResp["ConnectionTime"]
mapping["http2_port"] = convertJsonStringToStringList(getResp["Http2Port"])
mapping["http_port"] = convertJsonStringToStringList(getResp["HttpPort"])
mapping["http_to_user_ip"] = convertHttpToUserIpResponse(formatInt(getResp["HttpToUserIp"]))
mapping["https_port"] = convertJsonStringToStringList(getResp["HttpsPort"])
mapping["https_redirect"] = convertHttpsRedirectResponse(formatInt(getResp["HttpsRedirect"]))
mapping["is_access_product"] = convertIsAccessProductResponse(formatInt(getResp["IsAccessProduct"]))
mapping["load_balancing"] = convertLoadBalancingResponse(formatInt(getResp["LoadBalancing"]))
if v, ok := getResp["LogHeaders"].([]interface{}); ok {
logHeaders := make([]map[string]interface{}, 0)
for _, val := range v {
item := val.(map[string]interface{})
logHeaders = append(logHeaders, map[string]interface{}{
"key": item["k"].(string),
"value": item["v"].(string),
})
}
mapping["log_headers"] = logHeaders
}
mapping["read_time"] = getResp["ReadTime"]
mapping["resource_group_id"] = getResp["ResourceGroupId"]
mapping["source_ips"] = getResp["SourceIps"]
mapping["version"] = getResp["Version"]
mapping["write_time"] = getResp["WriteTime"]
names = append(names, object.(string))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("names", names); err != nil {
return WrapError(err)
}
if err := d.Set("domains", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"fmt"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudWafInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudWafInstancesRead,
Schema: map[string]*schema.Schema{
"ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"instance_source": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IntInSlice([]int{0, 1}),
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"end_date": {
Type: schema.TypeInt,
Computed: true,
},
"in_debt": {
Type: schema.TypeInt,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
},
"remain_day": {
Type: schema.TypeInt,
Computed: true,
},
"status": {
Type: schema.TypeInt,
Computed: true,
},
"subscription_type": {
Type: schema.TypeString,
Computed: true,
},
"trial": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func dataSourceAlicloudWafInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DescribeInstanceInfos"
request := make(map[string]interface{})
if v, ok := d.GetOk("instance_source"); ok {
request["InstanceSource"] = v
}
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
var objects []map[string]interface{}
idsMap := make(map[string]string)
if v, ok := d.GetOk("ids"); ok {
for _, vv := range v.([]interface{}) {
if vv == nil {
continue
}
idsMap[vv.(string)] = vv.(string)
}
}
status, statusOk := d.GetOkExists("status")
var response map[string]interface{}
conn, err := client.NewWafClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_waf_instances", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
resp, err := jsonpath.Get("$.InstanceInfos", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.InstanceInfos", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if len(idsMap) > 0 {
if _, ok := idsMap[fmt.Sprint(item["InstanceId"])]; !ok {
continue
}
}
if statusOk && status.(int) != formatInt(item["Status"]) {
continue
}
objects = append(objects, item)
}
ids := make([]string, 0)
s := make([]map[string]interface{}, 0)
for _, object := range objects {
mapping := map[string]interface{}{
"end_date": formatInt(object["EndDate"]),
"in_debt": formatInt(object["InDebt"]),
"id": fmt.Sprint(object["InstanceId"]),
"instance_id": object["InstanceId"],
"remain_day": formatInt(object["RemainDay"]),
"status": formatInt(object["Status"]),
"subscription_type": object["SubscriptionType"],
"trial": formatInt(object["Trial"]),
}
ids = append(ids, fmt.Sprint(object["InstanceId"]))
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(ids))
if err := d.Set("ids", ids); err != nil {
return WrapError(err)
}
if err := d.Set("instances", s); err != nil {
return WrapError(err)
}
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"log"
"regexp"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/yundun_dbaudit"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudDbauditInstances() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudDbauditInstancesRead,
Schema: map[string]*schema.Schema{
"description_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateRegexp,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
ForceNew: true,
},
"descriptions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"instances": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"user_vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"private_domain": {
Type: schema.TypeString,
Computed: true,
},
"public_domain": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"instance_status": {
Type: schema.TypeString,
Computed: true,
},
"license_code": {
Type: schema.TypeString,
Computed: true,
},
"public_network_access": {
Type: schema.TypeBool,
Computed: true,
},
"tags": tagsSchema(),
},
},
},
"tags": tagsSchema(),
},
}
}
func dataSourceAlicloudDbauditInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := yundun_dbaudit.CreateDescribeInstancesRequest()
request.PageSize = requests.NewInteger(PageSizeSmall)
request.CurrentPage = requests.NewInteger(1)
var instances []yundun_dbaudit.Instance
// get name Regex
var nameRegex *regexp.Regexp
if v, ok := d.GetOk("description_regex"); ok {
if r, err := regexp.Compile(v.(string)); err == nil {
nameRegex = r
}
}
if v, ok := d.GetOk("ids"); ok {
ids, _ := v.([]interface{})
var ids_str []string
for _, v_instance_id := range ids {
if v_instance_id == nil {
continue
}
ids_str = append(ids_str, v_instance_id.(string))
}
request.InstanceId = &ids_str
}
if v, ok := d.GetOk("tags"); ok {
var tags []yundun_dbaudit.DescribeInstancesTag
for key, value := range v.(map[string]interface{}) {
tags = append(tags, yundun_dbaudit.DescribeInstancesTag{
Key: key,
Value: value.(string),
})
}
request.Tag = &tags
}
for {
raw, err := client.WithDbauditClient(func(dbauditClient *yundun_dbaudit.Client) (interface{}, error) {
return dbauditClient.DescribeInstances(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_yundun_dbaudit", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*yundun_dbaudit.DescribeInstancesResponse)
if len(response.Instances) < 1 {
break
}
for _, e := range response.Instances {
if nameRegex != nil && !nameRegex.MatchString(e.Description) {
continue
}
instances = append(instances, e)
}
if len(response.Instances) < PageSizeSmall {
break
}
currentPageNo := request.CurrentPage
if page, err := getNextpageNumber(currentPageNo); err != nil {
return WrapError(err)
} else {
request.CurrentPage = page
}
}
var instanceTags []yundun_dbaudit.TagResources
for _, inst := range instances {
request := yundun_dbaudit.CreateListTagResourcesRequest()
request.RegionId = client.RegionId
request.ResourceType = strings.ToUpper(string(TagResourceInstance))
request.ResourceId = &[]string{inst.InstanceId}
raw, err := client.WithDbauditClient(func(dbauditClient *yundun_dbaudit.Client) (interface{}, error) {
return dbauditClient.ListTagResources(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_yundun_dbaudit_tags", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*yundun_dbaudit.ListTagResourcesResponse)
instanceTags = append(instanceTags, yundun_dbaudit.TagResources{TagResource: response.TagResources})
}
return WrapError(extractDbauditInstance(d, instances, instanceTags))
}
func extractDbauditInstance(d *schema.ResourceData, specs []yundun_dbaudit.Instance, tags []yundun_dbaudit.TagResources) error {
var instanceIds []string
var descriptions []string
var instances []map[string]interface{}
for i := 0; i < len(specs); i++ {
instanceMap := map[string]interface{}{
"id": specs[i].InstanceId,
"description": specs[i].Description,
"user_vswitch_id": specs[i].VswitchId,
"private_domain": specs[i].IntranetEndpoint,
"public_domain": specs[i].InternetEndpoint,
"instance_status": specs[i].InstanceStatus,
"license_code": specs[i].LicenseCode,
"public_network_access": specs[i].PublicNetworkAccess,
"tags": dbauditTagsToMap(tags[i].TagResource),
}
instanceIds = append(instanceIds, specs[i].InstanceId)
descriptions = append(descriptions, specs[i].Description)
instances = append(instances, instanceMap)
}
d.SetId(dataResourceIdHash(instanceIds))
if err := d.Set("ids", instanceIds); err != nil {
return WrapError(err)
}
if err := d.Set("descriptions", descriptions); err != nil {
return WrapError(err)
}
if err := d.Set("instances", instances); err != nil {
return WrapError(err)
}
// storage locally
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), instances)
}
log.Printf("DEBUF data source finnished")
return nil
}
func dbauditTagsToMap(tags []yundun_dbaudit.TagResource) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !dbauditTagIgnored(t) {
result[t.TagKey] = t.TagValue
}
}
return result
}
func dbauditTagIgnored(t yundun_dbaudit.TagResource) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, t.TagKey)
ok, _ := regexp.MatchString(v, t.TagKey)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific tag %s (val: %s), ignoring.\n", t.TagKey, t.TagValue)
return true
}
}
return false
}
package alicloud
import (
"fmt"
"reflect"
"regexp"
"sort"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/services/hbase"
"github.com/denverdino/aliyungo/common"
"github.com/aliyun/alibaba-cloud-sdk-go/services/adb"
"github.com/aliyun/alibaba-cloud-sdk-go/services/dds"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/aliyun/alibaba-cloud-sdk-go/services/elasticsearch"
"github.com/aliyun/alibaba-cloud-sdk-go/services/gpdb"
"github.com/aliyun/alibaba-cloud-sdk-go/services/polardb"
r_kvstore "github.com/aliyun/alibaba-cloud-sdk-go/services/r-kvstore"
"github.com/aliyun/alibaba-cloud-sdk-go/services/slb"
"github.com/aliyun/fc-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func dataSourceAlicloudZones() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudZonesRead,
Schema: map[string]*schema.Schema{
"available_instance_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^ecs\..*`), "prefix must be 'ecs.'"),
},
"available_resource_creation": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
string(ResourceTypeInstance),
string(ResourceTypeRds),
string(ResourceTypePolarDB),
string(ResourceTypeRkv),
string(ResourceTypeVSwitch),
string(ResourceTypeDisk),
string(IoOptimized),
string(ResourceTypeFC),
string(ResourceTypeElasticsearch),
string(ResourceTypeSlb),
string(ResourceTypeMongoDB),
string(ResourceTypeGpdb),
string(ResourceTypeHBase),
string(ResourceTypeAdb),
}, false),
},
"available_slb_address_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
string(Vpc),
string(ClassicIntranet),
string(ClassicInternet),
}, false),
},
"available_slb_address_ip_version": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
string(IPV4),
string(IPV6),
}, false),
},
"available_disk_category": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
"all",
"cloud",
"ephemeral_ssd",
"cloud_essd",
"cloud_efficiency",
"cloud_ssd",
"local_disk",
}, false),
},
"multi": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"instance_charge_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: PostPaid,
// %q must contain a valid InstanceChargeType, expected common.PrePaid, common.PostPaid
ValidateFunc: validation.StringInSlice([]string{string(common.PrePaid), string(common.PostPaid)}, false),
},
"network_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Vpc", "Classic"}, false),
},
"spot_strategy": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: NoSpot,
ValidateFunc: validation.StringInSlice([]string{"NoSpot", "SpotAsPriceGo", "SpotWithPriceLimit"}, false),
},
"enable_details": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
// Computed values.
"zones": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"local_name": {
Type: schema.TypeString,
Computed: true,
},
"available_instance_types": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"available_resource_creation": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"available_disk_categories": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"multi_zone_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"slb_slave_zone_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
},
}
}
func dataSourceAlicloudZonesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
resType := d.Get("available_resource_creation").(string)
multi := d.Get("multi").(bool)
var zoneIds []string
rdsZones := make(map[string]string)
polarDBZones := make(map[string]string)
rkvZones := make(map[string]string)
mongoDBZones := make(map[string]string)
gpdbZones := make(map[string]string)
hbaseZones := make(map[string]string)
adbZones := make(map[string]string)
instanceChargeType := d.Get("instance_charge_type").(string)
if strings.ToLower(Trim(resType)) == strings.ToLower(string(ResourceTypePolarDB)) {
request := polardb.CreateDescribeRegionsRequest()
request.RegionId = client.RegionId
raw, err := client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.DescribeRegions(request)
})
if err != nil {
return WrapError(fmt.Errorf("[ERROR] DescribeRegions got an error: %#v", err))
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
regions, _ := raw.(*polardb.DescribeRegionsResponse)
if len(regions.Regions.Region) <= 0 {
return WrapError(fmt.Errorf("[ERROR] There is no available region for PolarDB."))
}
for _, r := range regions.Regions.Region {
for _, zone := range r.Zones.Zone {
if multi && strings.Contains(zone.ZoneId, MULTI_IZ_SYMBOL) && r.RegionId == string(client.Region) {
zoneIds = append(zoneIds, zone.ZoneId)
continue
}
polarDBZones[zone.ZoneId] = r.RegionId
}
}
}
if strings.ToLower(Trim(resType)) == strings.ToLower(string(ResourceTypeRkv)) {
request := r_kvstore.CreateDescribeAvailableResourceRequest()
request.RegionId = client.RegionId
request.InstanceChargeType = instanceChargeType
raw, err := client.WithRkvClient(func(rkvClient *r_kvstore.Client) (interface{}, error) {
return rkvClient.DescribeAvailableResource(request)
})
if err != nil {
return WrapError(fmt.Errorf("[ERROR] DescribeAvailableResource got an error: %#v", err))
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
zones, _ := raw.(*r_kvstore.DescribeAvailableResourceResponse)
if len(zones.AvailableZones.AvailableZone) <= 0 {
return WrapError(fmt.Errorf("[ERROR] There is no available zones for KVStore"))
}
for _, zone := range zones.AvailableZones.AvailableZone {
if multi && strings.Contains(zone.ZoneId, MULTI_IZ_SYMBOL) {
zoneIds = append(zoneIds, zone.ZoneId)
continue
}
rkvZones[zone.ZoneId] = zone.RegionId
}
}
if strings.ToLower(Trim(resType)) == strings.ToLower(string(ResourceTypeMongoDB)) {
request := dds.CreateDescribeRegionsRequest()
request.RegionId = client.RegionId
raw, err := client.WithDdsClient(func(ddsClient *dds.Client) (interface{}, error) {
return ddsClient.DescribeRegions(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_zones", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
regions, _ := raw.(*dds.DescribeRegionsResponse)
if len(regions.Regions.DdsRegion) <= 0 {
return WrapError(fmt.Errorf("[ERROR] There is no available region for MongoDB."))
}
for _, r := range regions.Regions.DdsRegion {
for _, zonid := range r.Zones.Zone {
if multi && strings.Contains(zonid.ZoneId, MULTI_IZ_SYMBOL) && r.RegionId == string(client.Region) {
zoneIds = append(zoneIds, zonid.ZoneId)
continue
}
mongoDBZones[zonid.ZoneId] = r.RegionId
}
}
}
if strings.ToLower(Trim(resType)) == strings.ToLower(string(ResourceTypeHBase)) {
request := hbase.CreateDescribeRegionsRequest()
request.RegionId = client.RegionId
raw, err := client.WithHbaseClient(func(hbaseClient *hbase.Client) (interface{}, error) {
return hbaseClient.DescribeRegions(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_zones", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
regions, _ := raw.(*hbase.DescribeRegionsResponse)
if len(regions.Regions.Region) <= 0 {
return WrapError(fmt.Errorf("[ERROR] There is no available region for HBase."))
}
for _, r := range regions.Regions.Region {
for _, zonid := range r.Zones.Zone {
if r.RegionId == string(client.Region) {
hbaseZones[zonid.Id] = r.RegionId
}
}
}
}
if strings.ToLower(Trim(resType)) == strings.ToLower(string(ResourceTypeAdb)) {
request := adb.CreateDescribeRegionsRequest()
request.RegionId = client.RegionId
raw, err := client.WithAdbClient(func(adbClient *adb.Client) (interface{}, error) {
return adbClient.DescribeRegions(request)
})
if err != nil {
return WrapError(fmt.Errorf("[ERROR] DescribeRegions got an error: %#v", err))
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
regions, _ := raw.(*adb.DescribeRegionsResponse)
if len(regions.Regions.Region) <= 0 {
return WrapError(fmt.Errorf("[ERROR] There is no available region for adb."))
}
for _, r := range regions.Regions.Region {
for _, zone := range r.Zones.Zone {
if multi && strings.Contains(zone.ZoneId, MULTI_IZ_SYMBOL) && r.RegionId == string(client.Region) {
zoneIds = append(zoneIds, zone.ZoneId)
continue
}
adbZones[zone.ZoneId] = r.RegionId
}
}
}
if strings.ToLower(Trim(resType)) == strings.ToLower(string(ResourceTypeGpdb)) {
request := gpdb.CreateDescribeRegionsRequest()
request.RegionId = client.RegionId
raw, err := client.WithGpdbClient(func(gpdbClient *gpdb.Client) (interface{}, error) {
return gpdbClient.DescribeRegions(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_zones", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*gpdb.DescribeRegionsResponse)
if len(response.Regions.Region) <= 0 {
return WrapError(fmt.Errorf("[ERROR] There is no available region for gpdb."))
}
for _, r := range response.Regions.Region {
for _, zoneId := range r.Zones.Zone {
if multi && strings.Contains(zoneId.ZoneId, MULTI_IZ_SYMBOL) && r.RegionId == string(client.Region) {
zoneIds = append(zoneIds, zoneId.ZoneId)
continue
}
gpdbZones[zoneId.ZoneId] = r.RegionId
}
}
}
elasticsearchZones := make(map[string]string)
if strings.ToLower(Trim(resType)) == strings.ToLower(string(ResourceTypeElasticsearch)) {
request := elasticsearch.CreateGetRegionConfigurationRequest()
request.RegionId = client.RegionId
raw, err := client.WithElasticsearchClient(func(elasticsearchClient *elasticsearch.Client) (interface{}, error) {
return elasticsearchClient.GetRegionConfiguration(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_zones", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.GetActionName(), request)
zones, _ := raw.(*elasticsearch.GetRegionConfigurationResponse)
for _, zoneID := range zones.Result.Zones {
if multi && strings.Contains(zoneID, MULTI_IZ_SYMBOL) {
zoneIds = append(zoneIds, zoneID)
continue
}
elasticsearchZones[zoneID] = string(client.Region)
}
}
if len(zoneIds) > 0 {
sort.Strings(zoneIds)
return zoneIdsDescriptionAttributes(d, zoneIds)
}
// Retrieving available zones for VPC-FC
if strings.ToLower(Trim(resType)) == strings.ToLower(string(ResourceTypeFC)) {
var clientInfo *fc.Client
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
clientInfo = fcClient
return fcClient.GetAccountSettings(fc.NewGetAccountSettingsInput())
})
if err != nil {
return fmt.Errorf("[API ERROR] FC GetAccountSettings: %#v", err)
}
addDebug("GetAccountSettings", raw, clientInfo)
out, _ := raw.(*fc.GetAccountSettingsOutput)
if out != nil && len(out.AvailableAZs) > 0 {
sort.Strings(out.AvailableAZs)
return zoneIdsDescriptionAttributes(d, out.AvailableAZs)
}
}
// Retrieving available zones for SLB
slaveZones := make(map[string][]string)
if strings.ToLower(Trim(resType)) == strings.ToLower(string(ResourceTypeSlb)) {
request := slb.CreateDescribeAvailableResourceRequest()
request.RegionId = client.RegionId
if ipVersion, ok := d.GetOk("available_slb_address_ip_version"); ok {
request.AddressIPVersion = ipVersion.(string)
}
if addressType, ok := d.GetOk("available_slb_address_type"); ok {
request.AddressType = addressType.(string)
}
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeAvailableResource(request)
})
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_zones", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*slb.DescribeAvailableResourceResponse)
for _, resource := range response.AvailableResources.AvailableResource {
slaveIds := slaveZones[resource.MasterZoneId]
slaveIds = append(slaveIds, resource.SlaveZoneId)
if len(slaveIds) > 0 {
sort.Strings(slaveIds)
}
slaveZones[resource.MasterZoneId] = slaveIds
}
}
_, validZones, _, err := ecsService.DescribeAvailableResources(d, meta, ZoneResource)
if err != nil {
return err
}
req := ecs.CreateDescribeZonesRequest()
req.RegionId = client.RegionId
req.InstanceChargeType = instanceChargeType
if v, ok := d.GetOk("spot_strategy"); ok && v.(string) != "" {
req.SpotStrategy = v.(string)
}
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeZones(req)
})
if err != nil {
return fmt.Errorf("DescribeZones got an error: %#v", err)
}
addDebug(req.GetActionName(), raw, req.RpcRequest, req)
resp, _ := raw.(*ecs.DescribeZonesResponse)
if resp == nil || len(resp.Zones.Zone) < 1 {
return fmt.Errorf("There are no availability zones in the region: %#v.", client.Region)
}
mapZones := make(map[string]ecs.Zone)
insType, _ := d.Get("available_instance_type").(string)
diskType, _ := d.Get("available_disk_category").(string)
for _, zone := range resp.Zones.Zone {
for _, v := range validZones {
if zone.ZoneId != v.ZoneId {
continue
}
if len(zone.AvailableInstanceTypes.InstanceTypes) <= 0 ||
(insType != "" && !constraints(zone.AvailableInstanceTypes.InstanceTypes, insType)) {
continue
}
if len(zone.AvailableDiskCategories.DiskCategories) <= 0 ||
(diskType != "" && !constraints(zone.AvailableDiskCategories.DiskCategories, diskType)) {
continue
}
if len(rdsZones) > 0 {
if _, ok := rdsZones[zone.ZoneId]; !ok {
continue
}
}
if len(polarDBZones) > 0 {
if _, ok := polarDBZones[zone.ZoneId]; !ok {
continue
}
}
if len(rkvZones) > 0 {
if _, ok := rkvZones[zone.ZoneId]; !ok {
continue
}
}
if len(mongoDBZones) > 0 {
if _, ok := mongoDBZones[zone.ZoneId]; !ok {
continue
}
}
if len(hbaseZones) > 0 {
if _, ok := hbaseZones[zone.ZoneId]; !ok {
continue
}
}
if len(gpdbZones) > 0 {
if _, ok := gpdbZones[zone.ZoneId]; !ok {
continue
}
}
if len(elasticsearchZones) > 0 {
if _, ok := elasticsearchZones[zone.ZoneId]; !ok {
continue
}
}
if len(slaveZones) > 0 {
if _, ok := slaveZones[zone.ZoneId]; !ok {
continue
}
}
if len(adbZones) > 0 {
if _, ok := adbZones[zone.ZoneId]; !ok {
continue
}
}
zoneIds = append(zoneIds, zone.ZoneId)
mapZones[zone.ZoneId] = zone
}
}
if len(zoneIds) > 0 {
// Sort zones before reading
sort.Strings(zoneIds)
}
var s []map[string]interface{}
for _, zoneId := range zoneIds {
mapping := map[string]interface{}{"id": zoneId}
if len(slaveZones) > 0 {
mapping["slb_slave_zone_ids"] = slaveZones[zoneId]
}
if !d.Get("enable_details").(bool) {
s = append(s, mapping)
continue
}
mapping["local_name"] = mapZones[zoneId].LocalName
mapping["available_instance_types"] = mapZones[zoneId].AvailableInstanceTypes.InstanceTypes
mapping["available_resource_creation"] = mapZones[zoneId].AvailableResourceCreation.ResourceTypes
mapping["available_disk_categories"] = mapZones[zoneId].AvailableDiskCategories.DiskCategories
s = append(s, mapping)
}
d.SetId(dataResourceIdHash(zoneIds))
if err := d.Set("zones", s); err != nil {
return err
}
if err := d.Set("ids", zoneIds); err != nil {
return err
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
// check array constraints str
func constraints(arr interface{}, v string) bool {
arrs := reflect.ValueOf(arr)
len := arrs.Len()
for i := 0; i < len; i++ {
if arrs.Index(i).String() == v {
return true
}
}
return false
}
func zoneIdsDescriptionAttributes(d *schema.ResourceData, zones []string) error {
var s []map[string]interface{}
var zoneIds []string
for _, t := range zones {
mapping := map[string]interface{}{
"id": t,
"multi_zone_ids": splitMultiZoneId(t),
}
s = append(s, mapping)
zoneIds = append(zoneIds, t)
}
d.SetId(dataResourceIdHash(zones))
if err := d.Set("zones", s); err != nil {
return WrapError(err)
}
if err := d.Set("ids", zoneIds); err != nil {
return WrapError(err)
}
// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
package alicloud
import (
"encoding/json"
"sort"
"strconv"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func httpHttpsDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if listener_forward, ok := d.GetOk("listener_forward"); ok && listener_forward.(string) == string(OnFlag) {
return true
}
if protocol, ok := d.GetOk("protocol"); ok && (Protocol(protocol.(string)) == Http || Protocol(protocol.(string)) == Https) {
return false
}
return true
}
func httpDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if protocol, ok := d.GetOk("protocol"); ok && Protocol(protocol.(string)) == Http {
return false
}
return true
}
func forwardPortDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
httpDiff := httpDiffSuppressFunc(k, old, new, d)
if listenerForward, ok := d.GetOk("listener_forward"); !httpDiff && ok && listenerForward.(string) == string(OnFlag) {
return false
}
return true
}
func httpsDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if protocol, ok := d.GetOk("protocol"); ok && Protocol(protocol.(string)) == Https {
return false
}
return true
}
func stickySessionTypeDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
httpDiff := httpHttpsDiffSuppressFunc(k, old, new, d)
if session, ok := d.GetOk("sticky_session"); !httpDiff && ok && session.(string) == string(OnFlag) {
return false
}
return true
}
func cookieTimeoutDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
stickSessionTypeDiff := stickySessionTypeDiffSuppressFunc(k, old, new, d)
if session_type, ok := d.GetOk("sticky_session_type"); !stickSessionTypeDiff && ok && session_type.(string) == string(InsertStickySessionType) {
return false
}
return true
}
func cookieDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
stickSessionTypeDiff := stickySessionTypeDiffSuppressFunc(k, old, new, d)
if session_type, ok := d.GetOk("sticky_session_type"); !stickSessionTypeDiff && ok && session_type.(string) == string(ServerStickySessionType) {
return false
}
return true
}
func tcpUdpDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if protocol, ok := d.GetOk("protocol"); ok && (Protocol(protocol.(string)) == Tcp || Protocol(protocol.(string)) == Udp) {
return false
}
return true
}
func healthCheckDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
httpDiff := httpHttpsDiffSuppressFunc(k, old, new, d)
if health, ok := d.GetOk("health_check"); httpDiff || (ok && health.(string) == string(OnFlag)) {
return false
}
return true
}
func healthCheckTypeDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if protocol, ok := d.GetOk("protocol"); ok && Protocol(protocol.(string)) == Tcp {
return false
}
return true
}
func establishedTimeoutDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if protocol, ok := d.GetOk("protocol"); ok && Protocol(protocol.(string)) == Tcp {
return false
}
return true
}
func httpHttpsTcpDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
httpDiff := httpHttpsDiffSuppressFunc(k, old, new, d)
health, okHc := d.GetOk("health_check")
protocol, okPro := d.GetOk("protocol")
checkType, okType := d.GetOk("health_check_type")
if (!httpDiff && okHc && health.(string) == string(OnFlag)) ||
(okPro && Protocol(protocol.(string)) == Tcp && okType && checkType.(string) == string(HTTPHealthCheckType)) {
return false
}
return true
}
func sslCertificateIdDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if protocol, ok := d.GetOk("protocol"); ok && Protocol(protocol.(string)) == Https {
return false
}
return true
}
func dnsValueDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
switch d.Get("type") {
case "NS", "MX", "CNAME", "SRV":
new = strings.TrimSuffix(strings.TrimSpace(new), ".")
}
return old == new
}
func dnsPriorityDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
return d.Get("type").(string) != "MX"
}
func slbAclDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if status, ok := d.GetOk("acl_status"); ok && status.(string) == string(OnFlag) {
return false
}
return true
}
func slbServerCertificateDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if alicloudCertificateId, ok := d.GetOk("alicloud_certificate_id"); !ok || alicloudCertificateId.(string) == "" {
return false
}
return true
}
func ecsInternetDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if max, ok := d.GetOk("internet_max_bandwidth_out"); ok && max.(int) > 0 {
return false
}
return true
}
func csKubernetesMasterPostPaidDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
return d.Get("master_instance_charge_type").(string) == "PostPaid" || !(d.Id() == "") && !d.Get("force_update").(bool)
}
func csKubernetesWorkerPostPaidDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
return d.Get("worker_instance_charge_type").(string) == "PostPaid" || !(d.Id() == "") && !d.Get("force_update").(bool)
}
func csNodepoolInstancePostPaidDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("instance_charge_type"); ok && v.(string) == "PostPaid" {
return true
}
return false
}
func masterDiskPerformanceLevelDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("master_disk_category"); ok && v.(string) != "cloud_essd" {
return true
}
return false
}
func workerDiskPerformanceLevelDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("worker_disk_category"); ok && v.(string) != "cloud_essd" {
return true
}
return false
}
func csNodepoolDiskPerformanceLevelDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("system_disk_category"); ok && v.(string) != "cloud_essd" {
return true
}
return false
}
func csNodepoolSpotInstanceSettingDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("spot_strategy"); ok && v.(string) == "SpotWithPriceLimit" {
return false
}
return true
}
func csNodepoolScalingPolicyDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if _, ok := d.GetOk("scaling_config"); ok {
return false
}
return true
}
func logRetentionPeriodDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if d.Get("enable_backup_log").(bool) {
return false
}
if d.Get("log_backup").(bool) {
return false
}
if v, err := strconv.Atoi(new); err != nil && v > d.Get("backup_retention_period").(int) {
return false
}
if v, err := strconv.Atoi(new); err != nil && v > d.Get("retention_period").(int) {
return false
}
return true
}
func enableBackupLogDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if d.Get("enable_backup_log").(bool) {
return false
}
if d.Get("log_backup").(bool) {
return false
}
return true
}
func archiveBackupPeriodDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if d.Get("enable_backup_log").(bool) {
return false
}
if d.Get("log_backup").(bool) {
return false
}
if v, err := strconv.Atoi(new); err != nil && v+730 >= d.Get("backup_retention_period").(int) {
return false
}
if v, err := strconv.Atoi(new); err != nil && v+730 >= d.Get("retention_period").(int) {
return false
}
return true
}
func PostPaidDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
// payment_type is the instance_charge_type's replacement.
// If both instance_charge_type and payment_type are "", it means hiding a default "PostPaid"
if v, ok := d.GetOk("instance_charge_type"); ok && strings.ToLower(v.(string)) == "prepaid" {
return false
}
if v, ok := d.GetOk("payment_type"); ok && v.(string) == "Subscription" {
return false
}
return true
}
func PostPaidAndRenewDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if strings.ToLower(d.Get("instance_charge_type").(string)) == "prepaid" && d.Get("auto_renew").(bool) {
return false
}
return true
}
func redisPostPaidDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
return strings.ToLower(d.Get("payment_type").(string)) == "postpaid"
}
func redisPostPaidAndRenewDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if strings.ToLower(d.Get("payment_type").(string)) == "prepaid" && d.Get("auto_renew").(bool) {
return false
}
return true
}
func ramSAMLProviderDiffSuppressFunc(old, new string) bool {
if strings.Replace(old, "\n", "", -1) != strings.Replace(new, "\n", "", -1) {
return false
}
return true
}
func redisSecurityGroupIdDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
oldArray := strings.Split(old, ",")
newArray := strings.Split(new, ",")
if len(oldArray) != len(newArray) {
return false
}
sort.Strings(oldArray)
sort.Strings(newArray)
for i := range newArray {
if newArray[i] != oldArray[i] {
return false
}
}
return true
}
func elasticsearchEnablePublicDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
return d.Get("enable_public").(bool) == false
}
func elasticsearchEnableKibanaPublicDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
return d.Get("enable_kibana_public_network").(bool) == false
}
func elasticsearchEnableKibanaPrivateDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
return d.Get("enable_kibana_private_network").(bool) == false
}
func ecsNotAutoRenewDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if d.Get("instance_charge_type").(string) == "PostPaid" {
return true
}
if RenewalStatus(d.Get("renewal_status").(string)) == RenewAutoRenewal {
return false
}
return true
}
func polardbPostPaidDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if d.Get("pay_type").(string) == "PrePaid" {
return false
}
return true
}
func polardbPostPaidAndRenewDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if d.Get("pay_type").(string) == "PrePaid" && d.Get("renewal_status").(string) != string(RenewNotRenewal) {
return false
}
return true
}
func adbPostPaidAndRenewDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("pay_type"); ok && v.(string) == "PrePaid" && d.Get("renewal_status").(string) != string(RenewNotRenewal) {
return false
}
if v, ok := d.GetOk("payment_type"); ok && v.(string) == "Subscription" && d.Get("renewal_status").(string) != string(RenewNotRenewal) {
return false
}
return true
}
func adbPostPaidDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("pay_type"); ok && v.(string) == "PrePaid" {
return false
}
if v, ok := d.GetOk("payment_type"); ok && v.(string) == "Subscription" {
return false
}
return true
}
func ecsSpotStrategyDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if d.Get("instance_charge_type").(string) == string(PostPaid) {
return false
}
return true
}
func ecsSpotPriceLimitDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if d.Get("instance_charge_type").(string) == "PostPaid" && d.Get("spot_strategy").(string) == "SpotWithPriceLimit" {
return false
}
return true
}
func ecsSystemDiskPerformanceLevelSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if d.Get("system_disk_category").(string) == string(DiskCloudESSD) {
return false
}
return true
}
func ecsSecurityGroupRulePortRangeDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
protocol := d.Get("ip_protocol").(string)
if protocol == "tcp" || protocol == "udp" {
if new == AllPortRange {
return true
}
return false
}
if new == AllPortRange {
return false
}
return true
}
func ecsSecurityGroupRulePreFixListIdDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
_, cidrIpExist := d.GetOk("cidr_ip")
_, SourceSecurityGroupIdExist := d.GetOk("source_security_group_id")
if cidrIpExist || SourceSecurityGroupIdExist {
return true
}
return false
}
func vpcTypeResourceDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if len(Trim(d.Get("vswitch_id").(string))) > 0 {
return false
}
return true
}
func routerInterfaceAcceptsideDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
return d.Get("role").(string) == string(AcceptingSide)
}
func routerInterfaceVBRTypeDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if d.Get("role").(string) == string(AcceptingSide) {
return true
}
if d.Get("router_type").(string) == string(VRouter) {
return true
}
return false
}
func workerDataDiskSizeSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
_, ok := d.GetOk("worker_data_disk_category")
return !ok || !(d.Id() == "") && !d.Get("force_update").(bool)
}
func imageIdSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
// setting image_id is not recommended, but is needed by some users.
// when image_id is left blank, server will set a random default to it, we only know the default value after creation.
// we suppress diff here to prevent unintentional force new action.
// if we want to change cluster's image_id to default, we have to find out what the default image_id is,
// then fill that image_id in this field.
return new == "" || !(d.Id() == "") && !d.Get("force_update").(bool)
}
func esVersionDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
oldVersion := strings.Split(strings.Split(old, "_")[0], ".")
newVersion := strings.Split(strings.Split(new, "_")[0], ".")
if len(oldVersion) >= 2 && len(newVersion) >= 2 {
if oldVersion[0] == newVersion[0] && oldVersion[1] == newVersion[1] {
return true
}
}
return false
}
func vpnSslConnectionsDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if enable_ssl, ok := d.GetOk("enable_ssl"); !ok || !enable_ssl.(bool) {
return true
}
return false
}
func slbRuleStickySessionTypeDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
listenerSync := slbRuleListenerSyncDiffSuppressFunc(k, old, new, d)
if session, ok := d.GetOk("sticky_session"); !listenerSync && ok && session.(string) == string(OnFlag) {
return false
}
return true
}
func slbRuleCookieTimeoutDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
stickSessionTypeDiff := slbRuleStickySessionTypeDiffSuppressFunc(k, old, new, d)
if session_type, ok := d.GetOk("sticky_session_type"); !stickSessionTypeDiff && ok && session_type.(string) == string(InsertStickySessionType) {
return false
}
return true
}
func slbRuleCookieDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
stickSessionTypeDiff := slbRuleStickySessionTypeDiffSuppressFunc(k, old, new, d)
if session_type, ok := d.GetOk("sticky_session_type"); !stickSessionTypeDiff && ok && session_type.(string) == string(ServerStickySessionType) {
return false
}
return true
}
func slbRuleHealthCheckDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
listenerSync := slbRuleListenerSyncDiffSuppressFunc(k, old, new, d)
if health, ok := d.GetOk("health_check"); !listenerSync && ok && health.(string) == string(OnFlag) {
return false
}
return true
}
func slbRuleListenerSyncDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if listenerSync, ok := d.GetOk("listener_sync"); ok && listenerSync.(string) == string(OffFlag) {
return false
}
return true
}
func kmsDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("password"); ok && v.(string) != "" {
return true
}
if v, ok := d.GetOk("account_password"); ok && v.(string) != "" {
return true
}
return false
}
func sagDnatEntryTypeDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if d.Get("type").(string) != "Intranet" {
return true
}
return false
}
func sagClientUserPasswordSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if d.Get("user_name").(string) == "" {
return true
}
return false
}
func cmsClientInfoSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
for _, v := range d.Get("escalations_info").([]interface{}) {
mapping := v.(map[string]interface{})
if mapping["statistics"] == "" || mapping["comparison_operator"] == "" || mapping["threshold"] == "" || mapping["times"] == "" {
return true
}
}
return false
}
func cmsClientWarnSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
for _, v := range d.Get("escalations_warn").([]interface{}) {
mapping := v.(map[string]interface{})
if mapping["statistics"] == "" || mapping["comparison_operator"] == "" || mapping["threshold"] == "" || mapping["times"] == "" {
return true
}
}
return false
}
func cmsClientCriticalSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
for _, v := range d.Get("escalations_critical").([]interface{}) {
mapping := v.(map[string]interface{})
if mapping["statistics"] == "" || mapping["comparison_operator"] == "" || mapping["threshold"] == "" || mapping["times"] == "" {
return true
}
}
return false
}
func alikafkaInstanceConfigDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if new == "" {
return true
}
if old == "" {
return false
}
oldMap := make(map[string]string)
err := json.Unmarshal([]byte(old), &oldMap)
if err != nil {
return false
}
newMap := make(map[string]string)
err = json.Unmarshal([]byte(new), &newMap)
if err != nil {
return false
}
// key exist in oldMap && found new value item different with old item
for k, newValueItem := range newMap {
oldValueItem, ok := oldMap[k]
if ok && newValueItem != oldValueItem {
return false
}
}
return true
}
func payTypePostPaidDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
return strings.ToLower(d.Get("pay_type").(string)) == "postpaid"
}
func engineDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
return strings.ToLower(d.Get("engine").(string)) == "bds"
}
func whiteIpListDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
oldArray := strings.Split(old, ",")
newArray := strings.Split(new, ",")
if len(oldArray) != len(newArray) {
return false
}
sort.Strings(oldArray)
sort.Strings(newArray)
for i := range newArray {
if newArray[i] != oldArray[i] {
return false
}
}
return true
}
func sslEnabledDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("ssl_enabled"); ok && v.(int) == 1 {
return false
}
return true
}
func securityIpsDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("security_ips"); ok && len(v.(*schema.Set).List()) > 0 {
return false
}
return true
}
func kernelVersionDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("upgrade_db_instance_kernel_version"); ok && v.(bool) == true {
return false
}
return true
}
func StorageAutoScaleDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("storage_auto_scale"); ok && strings.ToLower(v.(string)) == "enable" {
return false
}
return true
}
package alicloud
import (
"regexp"
"strings"
"github.com/alibabacloud-go/tea/tea"
sls "github.com/aliyun/aliyun-log-go-sdk"
"fmt"
"log"
"runtime"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors"
"github.com/aliyun/aliyun-datahub-sdk-go/datahub"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/aliyun/fc-go-sdk"
"github.com/denverdino/aliyungo/common"
)
const (
// common
NotFound = "NotFound"
ResourceNotfound = "ResourceNotfound"
ServiceUnavailable = "ServiceUnavailable"
InstanceNotFound = "Instance.Notfound"
ForbiddenInstance = "Forbidden.InstanceNotFound"
MessageInstanceNotFound = "instance is not found"
Throttling = "Throttling"
ThrottlingUser = "Throttling.User"
// RAM Instance Not Found
RamInstanceNotFound = "Forbidden.InstanceNotFound"
AliyunGoClientFailure = "AliyunGoClientFailure"
LogClientTimeout = "Client.Timeout exceeded while awaiting headers"
InvalidFileSystemStatus_Ordering = "InvalidFileSystemStatus.Ordering"
)
var SlbIsBusy = []string{"SystemBusy", "OperationBusy", "ServiceIsStopping", "BackendServer.configuring", "ServiceIsConfiguring"}
var EcsNotFound = []string{"InvalidInstanceId.NotFound", "Forbidden.InstanceNotFound"}
var DiskInvalidOperation = []string{"IncorrectDiskStatus", "IncorrectInstanceStatus", "OperationConflict", "InternalError", "InvalidOperation.Conflict", "IncorrectDiskStatus.Initializing"}
var NetworkInterfaceInvalidOperations = []string{"InvalidOperation.InvalidEniState", "InvalidOperation.InvalidEcsState", "OperationConflict", "ServiceUnavailable", "InternalError"}
var OperationDeniedDBStatus = []string{"InstanceConnectTimeoutFault", "OperationDenied.DBStatus", "OperationDenied.DBInstanceStatus", "OperationDenied.DBClusterStatus", "InternalError", "OperationDenied.OutofUsage", "IncorrectDBInstanceState"}
var DBReadInstanceNotReadyStatus = []string{"OperationDenied.ReadDBInstanceStatus", "OperationDenied.MasterDBInstanceState", "ReadDBInstance.Mismatch"}
var NasNotFound = []string{"InvalidMountTarget.NotFound", "InvalidFileSystem.NotFound", "Forbidden.NasNotFound", "InvalidLBid.NotFound", "VolumeUnavailable"}
var SnapshotInvalidOperations = []string{"OperationConflict", "ServiceUnavailable", "InternalError", "SnapshotCreatedDisk", "SnapshotCreatedImage"}
var DiskNotSupportOnlineChangeErrors = []string{"InvalidDiskCategory.NotSupported", "InvalidRegion.NotSupport", "IncorrectInstanceStatus", "IncorrectDiskStatus", "InvalidOperation.InstanceTypeNotSupport"}
// details at: https://help.aliyun.com/document_detail/27300.html
var OtsTableIsTemporarilyUnavailable = []string{"no such host", "OTSServerBusy", "OTSPartitionUnavailable", "OTSInternalServerError",
"OTSTimeout", "OTSServerUnavailable", "OTSRowOperationConflict", "OTSTableNotReady", "OTSNotEnoughCapacityUnit", "Too frequent table operations."}
// An Error represents a custom error for Terraform failure response
type ProviderError struct {
errorCode string
message string
}
func (e *ProviderError) Error() string {
return fmt.Sprintf("[ERROR] Terraform Alicloud Provider Error: Code: %s Message: %s", e.errorCode, e.message)
}
func (err *ProviderError) ErrorCode() string {
return err.errorCode
}
func (err *ProviderError) Message() string {
return err.message
}
func GetNotFoundErrorFromString(str string) error {
return &ProviderError{
errorCode: InstanceNotFound,
message: str,
}
}
func NotFoundError(err error) bool {
if err == nil {
return false
}
if e, ok := err.(*ComplexError); ok {
if e.Err != nil && strings.HasPrefix(e.Err.Error(), ResourceNotfound) {
return true
}
return NotFoundError(e.Cause)
}
if err == nil {
return false
}
if e, ok := err.(*errors.ServerError); ok {
return e.ErrorCode() == InstanceNotFound || e.ErrorCode() == RamInstanceNotFound || e.ErrorCode() == NotFound || strings.Contains(strings.ToLower(e.Message()), MessageInstanceNotFound)
}
if e, ok := err.(*ProviderError); ok {
return e.ErrorCode() == InstanceNotFound || e.ErrorCode() == RamInstanceNotFound || e.ErrorCode() == NotFound || strings.Contains(strings.ToLower(e.Message()), MessageInstanceNotFound)
}
if e, ok := err.(*common.Error); ok {
return e.Code == InstanceNotFound || e.Code == RamInstanceNotFound || e.Code == NotFound || strings.Contains(strings.ToLower(e.Message), MessageInstanceNotFound)
}
if e, ok := err.(oss.ServiceError); ok {
return e.StatusCode == 404 || strings.HasPrefix(e.Code, "NoSuch") || strings.HasPrefix(e.Message, "No Row found")
}
return false
}
func IsExpectedErrors(err error, expectCodes []string) bool {
if err == nil {
return false
}
if e, ok := err.(*ComplexError); ok {
return IsExpectedErrors(e.Cause, expectCodes)
}
if e, ok := err.(*tea.SDKError); ok {
for _, code := range expectCodes {
// The second statement aims to match the tea sdk history bug
if *e.Code == code || strings.HasPrefix(code, *e.Code) || strings.Contains(*e.Data, code) {
return true
}
}
return false
}
if e, ok := err.(*errors.ServerError); ok {
for _, code := range expectCodes {
if e.ErrorCode() == code || strings.Contains(e.Message(), code) {
return true
}
}
return false
}
if e, ok := err.(*ProviderError); ok {
for _, code := range expectCodes {
if e.ErrorCode() == code || strings.Contains(e.Message(), code) {
return true
}
}
return false
}
if e, ok := err.(*common.Error); ok {
for _, code := range expectCodes {
if e.Code == code || strings.Contains(e.Message, code) {
return true
}
}
return false
}
if e, ok := err.(*sls.Error); ok {
for _, code := range expectCodes {
if e.Code == code || strings.Contains(e.Message, code) || strings.Contains(e.String(), code) {
return true
}
}
return false
}
if e, ok := err.(oss.ServiceError); ok {
for _, code := range expectCodes {
if e.Code == code || strings.Contains(e.Message, code) {
return true
}
}
return false
}
if e, ok := err.(*fc.ServiceError); ok {
for _, code := range expectCodes {
if e.ErrorCode == code || strings.Contains(e.ErrorMessage, code) {
return true
}
}
return false
}
if e, ok := err.(*datahub.DatahubClientError); ok {
for _, code := range expectCodes {
if e.Code == code || strings.Contains(e.Message, code) {
return true
}
}
return false
}
for _, code := range expectCodes {
if strings.Contains(err.Error(), code) {
return true
}
}
return false
}
func NeedRetry(err error) bool {
if err == nil {
return false
}
postRegex := regexp.MustCompile("^Post [\"]*https://.*")
if postRegex.MatchString(err.Error()) {
return true
}
throttlingRegex := regexp.MustCompile("^Throttling.*")
codeRegex := regexp.MustCompile("^code: 5[\\d]{2}")
if e, ok := err.(*tea.SDKError); ok {
if strings.Contains(*e.Message, "code: 500, 您已开通过") {
return false
}
if *e.Code == ServiceUnavailable || *e.Code == "Rejected.Throttling" || throttlingRegex.MatchString(*e.Code) || codeRegex.MatchString(*e.Message) {
return true
}
}
if e, ok := err.(*errors.ServerError); ok {
return e.ErrorCode() == ServiceUnavailable || e.ErrorCode() == "Rejected.Throttling" || throttlingRegex.MatchString(e.ErrorCode()) || codeRegex.MatchString(e.Message())
}
if e, ok := err.(*common.Error); ok {
return e.Code == ServiceUnavailable || e.Code == "Rejected.Throttling" || throttlingRegex.MatchString(e.Code) || codeRegex.MatchString(e.Message)
}
return false
}
func IsExpectedErrorCodes(code string, errorCodes []string) bool {
if code == "" {
return false
}
for _, v := range errorCodes {
if v == code {
return true
}
}
return false
}
func IsThrottling(err error) bool {
if err == nil {
return false
}
if e, ok := err.(*errors.ServerError); ok {
if e.ErrorCode() == Throttling {
return true
}
return false
}
if e, ok := err.(*common.Error); ok {
if e.Code == Throttling {
return true
}
return false
}
return false
}
func GetTimeErrorFromString(str string) error {
return &ProviderError{
errorCode: "WaitForTimeout",
message: str,
}
}
func GetNotFoundMessage(product, id string) string {
return fmt.Sprintf("The specified %s %s is not found.", product, id)
}
func GetTimeoutMessage(product, status string) string {
return fmt.Sprintf("Waitting for %s %s is timeout.", product, status)
}
type ErrorSource string
const (
AlibabaCloudSdkGoERROR = ErrorSource("[SDK alibaba-cloud-sdk-go ERROR]")
AliyunLogGoSdkERROR = ErrorSource("[SDK aliyun-log-go-sdk ERROR]")
AliyunDatahubSdkGo = ErrorSource("[SDK aliyun-datahub-sdk-go ERROR]")
AliyunMaxComputeSdkGo = ErrorSource("[SDK aliyun-maxcompute-sdk-go ERROR]")
AliyunOssGoSdk = ErrorSource("[SDK aliyun-oss-go-sdk ERROR]")
FcGoSdk = ErrorSource("[SDK fc-go-sdk ERROR]")
DenverdinoAliyungo = ErrorSource("[SDK denverdino/aliyungo ERROR]")
AliyunTablestoreGoSdk = ErrorSource("[SDK aliyun-tablestore-go-sdk ERROR]")
AliMnsERROR = ErrorSource("[SDK ali_mns ERROR]")
ProviderERROR = ErrorSource("[Provider ERROR]")
)
// ComplexError is a format error which including origin error, extra error message, error occurred file and line
// Cause: a error is a origin error that comes from SDK, some exceptions and so on
// Err: a new error is built from extra message
// Path: the file path of error occurred
// Line: the file line of error occurred
type ComplexError struct {
Cause error
Err error
Path string
Line int
}
func (e ComplexError) Error() string {
if e.Cause == nil {
e.Cause = Error("<nil cause>")
}
if e.Err == nil {
return fmt.Sprintf("\u001B[31m[ERROR]\u001B[0m %s:%d:\n%s", e.Path, e.Line, e.Cause.Error())
}
return fmt.Sprintf("\u001B[31m[ERROR]\u001B[0m %s:%d: %s:\n%s", e.Path, e.Line, e.Err.Error(), e.Cause.Error())
}
func Error(msg string, args ...interface{}) error {
return fmt.Errorf(msg, args...)
}
// Return a ComplexError which including error occurred file and path
func WrapError(cause error) error {
if cause == nil {
return nil
}
_, filepath, line, ok := runtime.Caller(1)
if !ok {
log.Printf("\u001B[31m[ERROR]\u001B[0m runtime.Caller error in WrapError.")
return WrapComplexError(cause, nil, "", -1)
}
parts := strings.Split(filepath, "/")
if len(parts) > 3 {
filepath = strings.Join(parts[len(parts)-3:], "/")
}
return WrapComplexError(cause, nil, filepath, line)
}
// Return a ComplexError which including extra error message, error occurred file and path
func WrapErrorf(cause error, msg string, args ...interface{}) error {
if cause == nil && strings.TrimSpace(msg) == "" {
return nil
}
_, filepath, line, ok := runtime.Caller(1)
if !ok {
log.Printf("\u001B[31m[ERROR]\u001B[0m runtime.Caller error in WrapErrorf.")
return WrapComplexError(cause, Error(msg), "", -1)
}
parts := strings.Split(filepath, "/")
if len(parts) > 3 {
filepath = strings.Join(parts[len(parts)-3:], "/")
}
// The second parameter of args is requestId, if the error message is NotFoundMsg the requestId need to be returned.
if msg == NotFoundMsg && len(args) == 2 {
msg += RequestIdMsg
}
return WrapComplexError(cause, fmt.Errorf(msg, args...), filepath, line)
}
func WrapComplexError(cause, err error, filepath string, fileline int) error {
return &ComplexError{
Cause: cause,
Err: err,
Path: filepath,
Line: fileline,
}
}
// A default message of ComplexError's Err. It is format to Resource <resource-id> <operation> Failed!!! <error source>
const DefaultErrorMsg = "Resource %s %s Failed!!! %s"
const ResponseCodeMsg = "Resource %s %s Failed!!! %v"
const RequestIdMsg = "RequestId: %s"
const NotFoundMsg = ResourceNotfound + "!!! %s"
const NotFoundWithResponse = ResourceNotfound + "!!! Response: %v"
const DefaultTimeoutMsg = "Resource %s %s Timeout!!! %s"
const DeleteTimeoutMsg = "Resource %s Still Exists. %s Timeout!!! %s"
const WaitTimeoutMsg = "Resource %s %s Timeout In %d Seconds. Got: %s Expected: %s !!! %s"
const DataDefaultErrorMsg = "Datasource %s %s Failed!!! %s"
const SweepDefaultErrorMsg = "Sweep %s %s Failed!!!"
const IdMsg = "Resource id:%s "
const FailedGetAttributeMsg = "Getting resource %s attribute by path %s failed!!! Body: %v."
const DefaultDebugMsg = "\n*************** %s Response *************** \n%s\n%s******************************\n\n"
const FailedToReachTargetStatus = "Failed to reach target status. Current status is %s."
const FailedToReachTargetStatusWithResponse = FailedToReachTargetStatus + " Response: %s"
const FailedToReachTargetAttribute = "Failed to reach value for target attribute. Current value is %s."
const RequiredWhenMsg = "attribute '%s' is required when '%s' is %v"
package alicloud
import (
"strings"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
type LifecycleRuleStatus string
const (
ExpirationStatusEnabled = LifecycleRuleStatus("Enabled")
ExpirationStatusDisabled = LifecycleRuleStatus("Disabled")
)
func ossNotFoundError(err error) bool {
if e, ok := err.(oss.ServiceError); ok &&
(e.StatusCode == 404 || strings.HasPrefix(e.Code, "NoSuch") || strings.HasPrefix(e.Message, "No Row found")) {
return true
}
return false
}
package alicloud
type PrimaryKeyTypeString string
const (
IntegerType = PrimaryKeyTypeString("Integer")
StringType = PrimaryKeyTypeString("String")
BinaryType = PrimaryKeyTypeString("Binary")
)
type InstanceAccessedByType string
const (
AnyNetwork = InstanceAccessedByType("Any")
VpcOnly = InstanceAccessedByType("Vpc")
VpcOrConsole = InstanceAccessedByType("ConsoleOrVpc")
)
type OtsInstanceType string
const (
OtsCapacity = OtsInstanceType("Capacity")
OtsHighPerformance = OtsInstanceType("HighPerformance")
)
func convertInstanceAccessedBy(accessed InstanceAccessedByType) string {
switch accessed {
case VpcOnly:
return "VPC"
case VpcOrConsole:
return "VPC_CONSOLE"
default:
return "NORMAL"
}
}
func convertInstanceAccessedByRevert(network string) InstanceAccessedByType {
switch network {
case "VPC":
return VpcOnly
case "VPC_CONSOLE":
return VpcOrConsole
default:
return AnyNetwork
}
}
func convertInstanceType(instanceType OtsInstanceType) string {
switch instanceType {
case OtsHighPerformance:
return "SSD"
default:
return "HYBRID"
}
}
func convertInstanceTypeRevert(instanceType string) OtsInstanceType {
switch instanceType {
case "SSD":
return OtsHighPerformance
default:
return OtsCapacity
}
}
// OTS instance total status: S_RUNNING = 1, S_DISABLED = 2, S_DELETING = 3
func convertOtsInstanceStatus(status Status) int {
switch status {
case Running:
return 1
case DisabledStatus:
return 2
case Deleting:
return 3
default:
return -1
}
}
func convertOtsInstanceStatusConvert(status int) Status {
switch status {
case 1:
return Running
case 2:
return DisabledStatus
case 3:
return Deleting
default:
return ""
}
}
package alicloud
var PvtzThrottlingUserCatcher = Catcher{ThrottlingUser, 30, 2}
var PvtzSystemBusyCatcher = Catcher{"System.Busy", 30, 5}
func PvtzInvoker() Invoker {
i := Invoker{}
i.AddCatcher(PvtzThrottlingUserCatcher)
i.AddCatcher(ServiceBusyCatcher)
i.AddCatcher(PvtzSystemBusyCatcher)
return i
}
package alicloud
import (
"fmt"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type SchedulerType string
const (
WRRScheduler = SchedulerType("wrr")
WLCScheduler = SchedulerType("wlc")
RRScheduler = SchedulerType("rr")
)
type FlagType string
const (
OnFlag = FlagType("on")
OffFlag = FlagType("off")
)
type RsType string
const (
ENI = FlagType("eni")
ECS = FlagType("ecs")
)
type AclType string
const (
AclTypeBlack = AclType("black")
AclTypeWhite = AclType("white")
)
type StickySessionType string
const (
InsertStickySessionType = StickySessionType("insert")
ServerStickySessionType = StickySessionType("server")
)
const BackendServerPort = -520
type HealthCheckHttpCodeType string
const (
HTTP_2XX = HealthCheckHttpCodeType("http_2xx")
HTTP_3XX = HealthCheckHttpCodeType("http_3xx")
HTTP_4XX = HealthCheckHttpCodeType("http_4xx")
HTTP_5XX = HealthCheckHttpCodeType("http_5xx")
)
type HealthCheckType string
const (
TCPHealthCheckType = HealthCheckType("tcp")
HTTPHealthCheckType = HealthCheckType("http")
)
type LoadBalancerSpecType string
const (
S1Small = "slb.s1.small"
S2Small = "slb.s2.small"
S2Medium = "slb.s2.medium"
S3Small = "slb.s3.small"
S3Medium = "slb.s3.medium"
S3Large = "slb.s3.large"
S4Large = "slb.s4.large"
)
type ListenerErr struct {
ErrType string
Err error
}
func (e *ListenerErr) Error() string {
return e.ErrType + " " + e.Err.Error()
}
func expandBackendServersToString(list []interface{}, weight int, serverType string) string {
if len(list) < 1 {
return ""
}
var items []string
for _, id := range list {
items = append(items, fmt.Sprintf("{'ServerId':'%s','Weight':'%d', 'Type': '%s'}", id, weight, strings.Trim(serverType, " ")))
}
return fmt.Sprintf("[%s]", strings.Join(items, COMMA_SEPARATED))
}
func expandBackendServersWithPortToString(items []interface{}) string {
if len(items) < 1 {
return ""
}
var servers []string
for _, server := range items {
s := server.(map[string]interface{})
var serverIds []interface{}
var port, weight int
var serveType, serverId string
if v, ok := s["port"]; ok {
port = v.(int)
}
if v, ok := s["weight"]; ok {
weight = v.(int)
}
if v, ok := s["type"]; ok {
serveType = v.(string)
}
if v, ok := s["server_id"]; ok {
serverId = v.(string)
str := fmt.Sprintf("{'ServerId':'%s','Port':'%d','Weight':'%d', 'Type': '%s'}", strings.Trim(serverId, " "), port, weight, strings.Trim(serveType, " "))
servers = append(servers, str)
}
if v, ok := s["server_ids"]; ok {
serverIds = v.([]interface{})
for _, id := range serverIds {
str := fmt.Sprintf("{'ServerId':'%s','Port':'%d','Weight':'%d', 'Type': '%s'}", strings.Trim(id.(string), " "), port, weight, strings.Trim(serveType, " "))
servers = append(servers, str)
}
}
}
return fmt.Sprintf("[%s]", strings.Join(servers, COMMA_SEPARATED))
}
func expandMasterSlaveBackendServersToString(items []interface{}) string {
if len(items) < 1 {
return ""
}
var servers []string
for _, server := range items {
s := server.(map[string]interface{})
var serverId string
var port, weight, isBackup int
var stype, serveType string
if v, ok := s["server_id"]; ok {
serverId = v.(string)
}
if v, ok := s["port"]; ok {
port = v.(int)
}
if v, ok := s["weight"]; ok {
weight = v.(int)
}
if v, ok := s["type"]; ok {
stype = v.(string)
}
if v, ok := s["server_type"]; ok {
serveType = v.(string)
}
if v, ok := s["is_backup"]; ok {
isBackup = v.(int)
}
str := fmt.Sprintf("{'ServerId':'%s','Port':'%d','Weight':'%d', 'Type': '%s', 'ServerType': '%s', 'IsBackup':'%d'}", strings.Trim(serverId, " "), port, weight, strings.Trim(stype, " "), strings.Trim(serveType, " "), isBackup)
servers = append(servers, str)
}
return fmt.Sprintf("[%s]", strings.Join(servers, COMMA_SEPARATED))
}
func expandBackendServersInfoToString(items []interface{}) string {
if len(items) < 1 {
return ""
}
var servers []string
for _, server := range items {
s := server.(map[string]interface{})
var serverId string
var serverIp string
var weight int
var stype string
if v, ok := s["server_id"]; ok {
serverId = v.(string)
}
if v, ok := s["weight"]; ok {
weight = v.(int)
}
if v, ok := s["type"]; ok {
stype = v.(string)
}
if v, ok := s["server_ip"]; ok {
serverIp = strings.Trim(v.(string), " ")
}
if len(serverIp) > 0 {
str := fmt.Sprintf("{'ServerId':'%s','Weight':'%d', 'Type': '%s', 'ServerIp':'%s'}", strings.Trim(serverId, " "), weight, strings.Trim(stype, " "), serverIp)
servers = append(servers, str)
} else {
str := fmt.Sprintf("{'ServerId':'%s','Weight':'%d', 'Type': '%s'}", strings.Trim(serverId, " "), weight, strings.Trim(stype, " "))
servers = append(servers, str)
}
}
return fmt.Sprintf("[%s]", strings.Join(servers, COMMA_SEPARATED))
}
func expandBackendServersWithTypeToString(items []interface{}) string {
if len(items) < 1 {
return ""
}
var servers []string
for _, server := range items {
s := server.(map[string]interface{})
var serverId string
var weight int
var stype string
if v, ok := s["server_id"]; ok {
serverId = v.(string)
}
if v, ok := s["weight"]; ok {
weight = v.(int)
}
if v, ok := s["type"]; ok {
stype = v.(string)
}
str := fmt.Sprintf("{'ServerId':'%s','Weight':'%d', 'Type': '%s'}", strings.Trim(serverId, " "), weight, strings.Trim(stype, " "))
servers = append(servers, str)
}
return fmt.Sprintf("[%s]", strings.Join(servers, COMMA_SEPARATED))
}
func getIdSetFromServers(items []interface{}) *schema.Set {
rmId := make([]interface{}, 0)
for _, item := range items {
server := item.(map[string]interface{})
rmId = append(rmId, fmt.Sprintf("%s", server["server_id"]))
}
return schema.NewSet(schema.HashString, rmId)
}
func getIdPortSetFromServers(items []interface{}) *schema.Set {
rmIdPort := make([]interface{}, 0)
for _, item := range items {
server := item.(map[string]interface{})
if v, ok := server["server_ids"]; ok {
serverIds := v.([]interface{})
for _, id := range serverIds {
rmIdPort = append(rmIdPort, fmt.Sprintf("%s:%d", id, server["port"]))
}
}
}
return schema.NewSet(schema.HashString, rmIdPort)
}
package alicloud
import (
"github.com/denverdino/aliyungo/common"
"github.com/denverdino/aliyungo/ecs"
)
type Tag struct {
Key string
Value string
}
type JsonTag struct {
TagKey string
TagValue string
}
type AddTagsArgs struct {
ResourceId string
ResourceType ecs.TagResourceType //image, instance, snapshot or disk
RegionId common.Region
Tag []Tag
}
type RemoveTagsArgs struct {
ResourceId string
ResourceType ecs.TagResourceType //image, instance, snapshot or disk
RegionId common.Region
Tag []Tag
}
func AddTags(client *ecs.Client, args *AddTagsArgs) error {
response := ecs.AddTagsResponse{}
err := client.Invoke("AddTags", args, &response)
if err != nil {
return err
}
return err
}
func RemoveTags(client *ecs.Client, args *RemoveTagsArgs) error {
response := ecs.RemoveTagsResponse{}
err := client.Invoke("RemoveTags", args, &response)
if err != nil {
return err
}
return err
}
package alicloud
const (
EcsInstance = "EcsInstance"
SlbInstance = "SlbInstance"
Nat = "Nat"
HaVip = "HaVip"
)
type RouterType string
type Role string
type Spec string
const (
VRouter = RouterType("VRouter")
VBR = RouterType("VBR")
InitiatingSide = Role("InitiatingSide")
AcceptingSide = Role("AcceptingSide")
Mini2 = Spec("Mini.2")
Mini5 = Spec("Mini.5")
Small1 = Spec("Small.1")
Small2 = Spec("Small.2")
Small5 = Spec("Small.5")
Middle1 = Spec("Middle.1")
Middle2 = Spec("Middle.2")
Middle5 = Spec("Middle.5")
Large1 = Spec("Large.1")
Large2 = Spec("Large.2")
Large5 = Spec("Large.5")
Xlarge1 = Spec("Xlarge.1")
Negative = Spec(("Negative"))
)
func GetAllRouterInterfaceSpec() (specifications []string) {
specifications = append(specifications, string(Mini2), string(Mini5),
string(Small1), string(Small2), string(Small5),
string(Middle1), string(Middle2), string(Middle5),
string(Large1), string(Large2), string(Large5), string(Xlarge1),
string(Negative))
return
}
package alicloud
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"runtime"
"strconv"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/sts"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-sdk/helper/hashcode"
"github.com/hashicorp/terraform-plugin-sdk/helper/mutexkv"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/terraform"
"github.com/mitchellh/go-homedir"
)
// Provider returns a schema.Provider for alicloud
func Provider() terraform.ResourceProvider {
return &schema.Provider{
Schema: map[string]*schema.Schema{
"access_key": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ALICLOUD_ACCESS_KEY", os.Getenv("ALICLOUD_ACCESS_KEY")),
Description: descriptions["access_key"],
},
"secret_key": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ALICLOUD_SECRET_KEY", os.Getenv("ALICLOUD_SECRET_KEY")),
Description: descriptions["secret_key"],
},
"security_token": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ALICLOUD_SECURITY_TOKEN", os.Getenv("SECURITY_TOKEN")),
Description: descriptions["security_token"],
},
"ecs_role_name": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ALICLOUD_ECS_ROLE_NAME", os.Getenv("ALICLOUD_ECS_ROLE_NAME")),
Description: descriptions["ecs_role_name"],
},
"region": {
Type: schema.TypeString,
Required: true,
DefaultFunc: schema.EnvDefaultFunc("ALICLOUD_REGION", os.Getenv("ALICLOUD_REGION")),
Description: descriptions["region"],
},
"ots_instance_name": {
Type: schema.TypeString,
Optional: true,
Deprecated: "Field 'ots_instance_name' has been deprecated from provider version 1.10.0. New field 'instance_name' of resource 'alicloud_ots_table' instead.",
},
"log_endpoint": {
Type: schema.TypeString,
Optional: true,
Deprecated: "Field 'log_endpoint' has been deprecated from provider version 1.28.0. New field 'log' which in nested endpoints instead.",
},
"mns_endpoint": {
Type: schema.TypeString,
Optional: true,
Deprecated: "Field 'mns_endpoint' has been deprecated from provider version 1.28.0. New field 'mns' which in nested endpoints instead.",
},
"account_id": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ALICLOUD_ACCOUNT_ID", os.Getenv("ALICLOUD_ACCOUNT_ID")),
Description: descriptions["account_id"],
},
"assume_role": assumeRoleSchema(),
"fc": {
Type: schema.TypeString,
Optional: true,
Deprecated: "Field 'fc' has been deprecated from provider version 1.28.0. New field 'fc' which in nested endpoints instead.",
},
"endpoints": endpointsSchema(),
"shared_credentials_file": {
Type: schema.TypeString,
Optional: true,
Description: descriptions["shared_credentials_file"],
DefaultFunc: schema.EnvDefaultFunc("ALICLOUD_SHARED_CREDENTIALS_FILE", ""),
},
"profile": {
Type: schema.TypeString,
Optional: true,
Description: descriptions["profile"],
DefaultFunc: schema.EnvDefaultFunc("ALICLOUD_PROFILE", ""),
},
"skip_region_validation": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: descriptions["skip_region_validation"],
},
"configuration_source": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["configuration_source"],
ValidateFunc: validation.StringLenBetween(0, 64),
DefaultFunc: schema.EnvDefaultFunc("TF_APPEND_USER_AGENT", ""),
},
"protocol": {
Type: schema.TypeString,
Optional: true,
Default: "HTTPS",
Description: descriptions["protocol"],
ValidateFunc: validation.StringInSlice([]string{"HTTP", "HTTPS"}, false),
},
"client_read_timeout": {
Type: schema.TypeInt,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("CLIENT_READ_TIMEOUT", 60000),
Description: descriptions["client_read_timeout"],
},
"client_connect_timeout": {
Type: schema.TypeInt,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("CLIENT_CONNECT_TIMEOUT", 60000),
Description: descriptions["client_connect_timeout"],
},
"source_ip": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ALICLOUD_SOURCE_IP", os.Getenv("ALICLOUD_SOURCE_IP")),
Description: descriptions["source_ip"],
},
"security_transport": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ALICLOUD_SECURITY_TRANSPORT", os.Getenv("ALICLOUD_SECURITY_TRANSPORT")),
//Deprecated: "It has been deprecated from version 1.136.0 and using new field secure_transport instead.",
},
"secure_transport": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ALICLOUD_SECURE_TRANSPORT", os.Getenv("ALICLOUD_SECURE_TRANSPORT")),
Description: descriptions["secure_transport"],
},
"credentials_uri": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ALICLOUD_CREDENTIALS_URI", os.Getenv("ALICLOUD_CREDENTIALS_URI")),
Description: descriptions["credentials_uri"],
},
},
DataSourcesMap: map[string]*schema.Resource{
"alicloud_account": dataSourceAlicloudAccount(),
"alicloud_caller_identity": dataSourceAlicloudCallerIdentity(),
"alicloud_images": dataSourceAlicloudImages(),
"alicloud_regions": dataSourceAlicloudRegions(),
"alicloud_zones": dataSourceAlicloudZones(),
"alicloud_db_zones": dataSourceAlicloudDBZones(),
"alicloud_instance_type_families": dataSourceAlicloudInstanceTypeFamilies(),
"alicloud_instance_types": dataSourceAlicloudInstanceTypes(),
"alicloud_instances": dataSourceAlicloudInstances(),
"alicloud_disks": dataSourceAlicloudEcsDisks(),
"alicloud_network_interfaces": dataSourceAlicloudEcsNetworkInterfaces(),
"alicloud_snapshots": dataSourceAlicloudEcsSnapshots(),
"alicloud_vpcs": dataSourceAlicloudVpcs(),
"alicloud_vswitches": dataSourceAlicloudVswitches(),
"alicloud_eips": dataSourceAlicloudEipAddresses(),
"alicloud_key_pairs": dataSourceAlicloudEcsKeyPairs(),
"alicloud_kms_keys": dataSourceAlicloudKmsKeys(),
"alicloud_kms_ciphertext": dataSourceAlicloudKmsCiphertext(),
"alicloud_kms_plaintext": dataSourceAlicloudKmsPlaintext(),
"alicloud_dns_resolution_lines": dataSourceAlicloudDnsResolutionLines(),
"alicloud_dns_domains": dataSourceAlicloudAlidnsDomains(),
"alicloud_dns_groups": dataSourceAlicloudDnsGroups(),
"alicloud_dns_records": dataSourceAlicloudDnsRecords(),
// alicloud_dns_domain_groups, alicloud_dns_domain_records have been deprecated.
"alicloud_dns_domain_groups": dataSourceAlicloudDnsGroups(),
"alicloud_dns_domain_records": dataSourceAlicloudDnsRecords(),
// alicloud_ram_account_alias has been deprecated
"alicloud_ram_account_alias": dataSourceAlicloudRamAccountAlias(),
"alicloud_ram_account_aliases": dataSourceAlicloudRamAccountAlias(),
"alicloud_ram_groups": dataSourceAlicloudRamGroups(),
"alicloud_ram_users": dataSourceAlicloudRamUsers(),
"alicloud_ram_roles": dataSourceAlicloudRamRoles(),
"alicloud_ram_policies": dataSourceAlicloudRamPolicies(),
"alicloud_security_groups": dataSourceAlicloudSecurityGroups(),
"alicloud_security_group_rules": dataSourceAlicloudSecurityGroupRules(),
"alicloud_slbs": dataSourceAlicloudSlbLoadBalancers(),
"alicloud_slb_attachments": dataSourceAlicloudSlbAttachments(),
"alicloud_slb_backend_servers": dataSourceAlicloudSlbBackendServers(),
"alicloud_slb_listeners": dataSourceAlicloudSlbListeners(),
"alicloud_slb_rules": dataSourceAlicloudSlbRules(),
"alicloud_slb_server_groups": dataSourceAlicloudSlbServerGroups(),
"alicloud_slb_master_slave_server_groups": dataSourceAlicloudSlbMasterSlaveServerGroups(),
"alicloud_slb_acls": dataSourceAlicloudSlbAcls(),
"alicloud_slb_server_certificates": dataSourceAlicloudSlbServerCertificates(),
"alicloud_slb_ca_certificates": dataSourceAlicloudSlbCaCertificates(),
"alicloud_slb_domain_extensions": dataSourceAlicloudSlbDomainExtensions(),
"alicloud_slb_zones": dataSourceAlicloudSlbZones(),
"alicloud_oss_service": dataSourceAlicloudOssService(),
"alicloud_oss_bucket_objects": dataSourceAlicloudOssBucketObjects(),
"alicloud_oss_buckets": dataSourceAlicloudOssBuckets(),
"alicloud_ons_instances": dataSourceAlicloudOnsInstances(),
"alicloud_ons_topics": dataSourceAlicloudOnsTopics(),
"alicloud_ons_groups": dataSourceAlicloudOnsGroups(),
"alicloud_alikafka_consumer_groups": dataSourceAlicloudAlikafkaConsumerGroups(),
"alicloud_alikafka_instances": dataSourceAlicloudAlikafkaInstances(),
"alicloud_alikafka_topics": dataSourceAlicloudAlikafkaTopics(),
"alicloud_alikafka_sasl_users": dataSourceAlicloudAlikafkaSaslUsers(),
"alicloud_alikafka_sasl_acls": dataSourceAlicloudAlikafkaSaslAcls(),
"alicloud_fc_functions": dataSourceAlicloudFcFunctions(),
"alicloud_file_crc64_checksum": dataSourceAlicloudFileCRC64Checksum(),
"alicloud_fc_services": dataSourceAlicloudFcServices(),
"alicloud_fc_triggers": dataSourceAlicloudFcTriggers(),
"alicloud_fc_custom_domains": dataSourceAlicloudFcCustomDomains(),
"alicloud_fc_zones": dataSourceAlicloudFcZones(),
"alicloud_db_instances": dataSourceAlicloudDBInstances(),
"alicloud_db_instance_engines": dataSourceAlicloudDBInstanceEngines(),
"alicloud_db_instance_classes": dataSourceAlicloudDBInstanceClasses(),
"alicloud_rds_backups": dataSourceAlicloudRdsBackups(),
"alicloud_pvtz_zones": dataSourceAlicloudPvtzZones(),
"alicloud_pvtz_zone_records": dataSourceAlicloudPvtzZoneRecords(),
"alicloud_router_interfaces": dataSourceAlicloudRouterInterfaces(),
"alicloud_vpn_gateways": dataSourceAlicloudVpnGateways(),
"alicloud_vpn_customer_gateways": dataSourceAlicloudVpnCustomerGateways(),
"alicloud_vpn_connections": dataSourceAlicloudVpnConnections(),
"alicloud_ssl_vpn_servers": dataSourceAlicloudSslVpnServers(),
"alicloud_ssl_vpn_client_certs": dataSourceAlicloudSslVpnClientCerts(),
"alicloud_mongo_instances": dataSourceAlicloudMongoDBInstances(),
"alicloud_mongodb_instances": dataSourceAlicloudMongoDBInstances(),
"alicloud_mongodb_zones": dataSourceAlicloudMongoDBZones(),
"alicloud_gpdb_instances": dataSourceAlicloudGpdbInstances(),
"alicloud_gpdb_zones": dataSourceAlicloudGpdbZones(),
"alicloud_kvstore_instances": dataSourceAlicloudKvstoreInstances(),
"alicloud_kvstore_zones": dataSourceAlicloudKVStoreZones(),
"alicloud_kvstore_permission": dataSourceAlicloudKVStorePermission(),
"alicloud_kvstore_instance_classes": dataSourceAlicloudKVStoreInstanceClasses(),
"alicloud_kvstore_instance_engines": dataSourceAlicloudKVStoreInstanceEngines(),
"alicloud_cen_instances": dataSourceAlicloudCenInstances(),
"alicloud_cen_bandwidth_packages": dataSourceAlicloudCenBandwidthPackages(),
"alicloud_cen_bandwidth_limits": dataSourceAlicloudCenBandwidthLimits(),
"alicloud_cen_route_entries": dataSourceAlicloudCenRouteEntries(),
"alicloud_cen_region_route_entries": dataSourceAlicloudCenRegionRouteEntries(),
"alicloud_cen_transit_router_route_entries": dataSourceAlicloudCenTransitRouterRouteEntries(),
"alicloud_cen_transit_router_route_table_associations": dataSourceAlicloudCenTransitRouterRouteTableAssociations(),
"alicloud_cen_transit_router_route_table_propagations": dataSourceAlicloudCenTransitRouterRouteTablePropagations(),
"alicloud_cen_transit_router_route_tables": dataSourceAlicloudCenTransitRouterRouteTables(),
"alicloud_cen_transit_router_vbr_attachments": dataSourceAlicloudCenTransitRouterVbrAttachments(),
"alicloud_cen_transit_router_vpc_attachments": dataSourceAlicloudCenTransitRouterVpcAttachments(),
"alicloud_cen_transit_routers": dataSourceAlicloudCenTransitRouters(),
"alicloud_cs_kubernetes_clusters": dataSourceAlicloudCSKubernetesClusters(),
"alicloud_cs_managed_kubernetes_clusters": dataSourceAlicloudCSManagerKubernetesClusters(),
"alicloud_cs_edge_kubernetes_clusters": dataSourceAlicloudCSEdgeKubernetesClusters(),
"alicloud_cs_serverless_kubernetes_clusters": dataSourceAlicloudCSServerlessKubernetesClusters(),
"alicloud_cs_kubernetes_permissions": dataSourceAlicloudCSKubernetesPermissions(),
"alicloud_cs_kubernetes_addons": dataSourceAlicloudCSKubernetesAddons(),
"alicloud_cr_namespaces": dataSourceAlicloudCRNamespaces(),
"alicloud_cr_repos": dataSourceAlicloudCRRepos(),
"alicloud_cr_ee_instances": dataSourceAlicloudCrEEInstances(),
"alicloud_cr_ee_namespaces": dataSourceAlicloudCrEENamespaces(),
"alicloud_cr_ee_repos": dataSourceAlicloudCrEERepos(),
"alicloud_cr_ee_sync_rules": dataSourceAlicloudCrEESyncRules(),
"alicloud_mns_queues": dataSourceAlicloudMNSQueues(),
"alicloud_mns_topics": dataSourceAlicloudMNSTopics(),
"alicloud_mns_topic_subscriptions": dataSourceAlicloudMNSTopicSubscriptions(),
"alicloud_api_gateway_service": dataSourceAlicloudApiGatewayService(),
"alicloud_api_gateway_apis": dataSourceAlicloudApiGatewayApis(),
"alicloud_api_gateway_groups": dataSourceAlicloudApiGatewayGroups(),
"alicloud_api_gateway_apps": dataSourceAlicloudApiGatewayApps(),
"alicloud_elasticsearch_instances": dataSourceAlicloudElasticsearch(),
"alicloud_elasticsearch_zones": dataSourceAlicloudElaticsearchZones(),
"alicloud_drds_instances": dataSourceAlicloudDRDSInstances(),
"alicloud_nas_service": dataSourceAlicloudNasService(),
"alicloud_nas_access_groups": dataSourceAlicloudNasAccessGroups(),
"alicloud_nas_access_rules": dataSourceAlicloudAccessRules(),
"alicloud_nas_mount_targets": dataSourceAlicloudNasMountTargets(),
"alicloud_nas_file_systems": dataSourceAlicloudFileSystems(),
"alicloud_nas_protocols": dataSourceAlicloudNasProtocols(),
"alicloud_cas_certificates": dataSourceAlicloudSslCertificatesServiceCertificates(),
"alicloud_common_bandwidth_packages": dataSourceAlicloudCommonBandwidthPackages(),
"alicloud_route_tables": dataSourceAlicloudRouteTables(),
"alicloud_route_entries": dataSourceAlicloudRouteEntries(),
"alicloud_nat_gateways": dataSourceAlicloudNatGateways(),
"alicloud_snat_entries": dataSourceAlicloudSnatEntries(),
"alicloud_forward_entries": dataSourceAlicloudForwardEntries(),
"alicloud_ddoscoo_instances": dataSourceAlicloudDdoscooInstances(),
"alicloud_ddosbgp_instances": dataSourceAlicloudDdosbgpInstances(),
"alicloud_ess_alarms": dataSourceAlicloudEssAlarms(),
"alicloud_ess_notifications": dataSourceAlicloudEssNotifications(),
"alicloud_ess_scaling_groups": dataSourceAlicloudEssScalingGroups(),
"alicloud_ess_scaling_rules": dataSourceAlicloudEssScalingRules(),
"alicloud_ess_scaling_configurations": dataSourceAlicloudEssScalingConfigurations(),
"alicloud_ess_lifecycle_hooks": dataSourceAlicloudEssLifecycleHooks(),
"alicloud_ess_scheduled_tasks": dataSourceAlicloudEssScheduledTasks(),
"alicloud_ots_service": dataSourceAlicloudOtsService(),
"alicloud_ots_instances": dataSourceAlicloudOtsInstances(),
"alicloud_ots_instance_attachments": dataSourceAlicloudOtsInstanceAttachments(),
"alicloud_ots_tables": dataSourceAlicloudOtsTables(),
"alicloud_cloud_connect_networks": dataSourceAlicloudCloudConnectNetworks(),
"alicloud_emr_instance_types": dataSourceAlicloudEmrInstanceTypes(),
"alicloud_emr_disk_types": dataSourceAlicloudEmrDiskTypes(),
"alicloud_emr_main_versions": dataSourceAlicloudEmrMainVersions(),
"alicloud_sag_acls": dataSourceAlicloudSagAcls(),
"alicloud_yundun_dbaudit_instance": dataSourceAlicloudDbauditInstances(),
"alicloud_yundun_bastionhost_instances": dataSourceAlicloudBastionhostInstances(),
"alicloud_bastionhost_instances": dataSourceAlicloudBastionhostInstances(),
"alicloud_market_product": dataSourceAlicloudProduct(),
"alicloud_market_products": dataSourceAlicloudProducts(),
"alicloud_polardb_clusters": dataSourceAlicloudPolarDBClusters(),
"alicloud_polardb_node_classes": dataSourceAlicloudPolarDBNodeClasses(),
"alicloud_polardb_endpoints": dataSourceAlicloudPolarDBEndpoints(),
"alicloud_polardb_accounts": dataSourceAlicloudPolarDBAccounts(),
"alicloud_polardb_databases": dataSourceAlicloudPolarDBDatabases(),
"alicloud_polardb_zones": dataSourceAlicloudPolarDBZones(),
"alicloud_hbase_instances": dataSourceAlicloudHBaseInstances(),
"alicloud_hbase_zones": dataSourceAlicloudHBaseZones(),
"alicloud_hbase_instance_types": dataSourceAlicloudHBaseInstanceTypes(),
"alicloud_adb_clusters": dataSourceAlicloudAdbDbClusters(),
"alicloud_adb_zones": dataSourceAlicloudAdbZones(),
"alicloud_cen_flowlogs": dataSourceAlicloudCenFlowlogs(),
"alicloud_kms_aliases": dataSourceAlicloudKmsAliases(),
"alicloud_dns_domain_txt_guid": dataSourceAlicloudDnsDomainTxtGuid(),
"alicloud_edas_service": dataSourceAlicloudEdasService(),
"alicloud_fnf_service": dataSourceAlicloudFnfService(),
"alicloud_kms_service": dataSourceAlicloudKmsService(),
"alicloud_sae_service": dataSourceAlicloudSaeService(),
"alicloud_dataworks_service": dataSourceAlicloudDataWorksService(),
"alicloud_data_works_service": dataSourceAlicloudDataWorksService(),
"alicloud_mns_service": dataSourceAlicloudMnsService(),
"alicloud_cloud_storage_gateway_service": dataSourceAlicloudCloudStorageGatewayService(),
"alicloud_vs_service": dataSourceAlicloudVsService(),
"alicloud_pvtz_service": dataSourceAlicloudPvtzService(),
"alicloud_cms_service": dataSourceAlicloudCmsService(),
"alicloud_maxcompute_service": dataSourceAlicloudMaxcomputeService(),
"alicloud_brain_industrial_service": dataSourceAlicloudBrainIndustrialService(),
"alicloud_iot_service": dataSourceAlicloudIotService(),
"alicloud_ack_service": dataSourceAlicloudAckService(),
"alicloud_cr_service": dataSourceAlicloudCrService(),
"alicloud_dcdn_service": dataSourceAlicloudDcdnService(),
"alicloud_datahub_service": dataSourceAlicloudDatahubService(),
"alicloud_ons_service": dataSourceAlicloudOnsService(),
"alicloud_fc_service": dataSourceAlicloudFcService(),
"alicloud_privatelink_service": dataSourceAlicloudPrivateLinkService(),
"alicloud_edas_applications": dataSourceAlicloudEdasApplications(),
"alicloud_edas_deploy_groups": dataSourceAlicloudEdasDeployGroups(),
"alicloud_edas_clusters": dataSourceAlicloudEdasClusters(),
"alicloud_resource_manager_folders": dataSourceAlicloudResourceManagerFolders(),
"alicloud_dns_instances": dataSourceAlicloudAlidnsInstances(),
"alicloud_resource_manager_policies": dataSourceAlicloudResourceManagerPolicies(),
"alicloud_resource_manager_resource_groups": dataSourceAlicloudResourceManagerResourceGroups(),
"alicloud_resource_manager_roles": dataSourceAlicloudResourceManagerRoles(),
"alicloud_resource_manager_policy_versions": dataSourceAlicloudResourceManagerPolicyVersions(),
"alicloud_alidns_domain_groups": dataSourceAlicloudAlidnsDomainGroups(),
"alicloud_kms_key_versions": dataSourceAlicloudKmsKeyVersions(),
"alicloud_alidns_records": dataSourceAlicloudAlidnsRecords(),
"alicloud_resource_manager_accounts": dataSourceAlicloudResourceManagerAccounts(),
"alicloud_resource_manager_resource_directories": dataSourceAlicloudResourceManagerResourceDirectories(),
"alicloud_resource_manager_handshakes": dataSourceAlicloudResourceManagerHandshakes(),
"alicloud_waf_domains": dataSourceAlicloudWafDomains(),
"alicloud_kms_secrets": dataSourceAlicloudKmsSecrets(),
"alicloud_cen_route_maps": dataSourceAlicloudCenRouteMaps(),
"alicloud_cen_private_zones": dataSourceAlicloudCenPrivateZones(),
"alicloud_dms_enterprise_instances": dataSourceAlicloudDmsEnterpriseInstances(),
"alicloud_cassandra_clusters": dataSourceAlicloudCassandraClusters(),
"alicloud_cassandra_data_centers": dataSourceAlicloudCassandraDataCenters(),
"alicloud_cassandra_zones": dataSourceAlicloudCassandraZones(),
"alicloud_kms_secret_versions": dataSourceAlicloudKmsSecretVersions(),
"alicloud_waf_instances": dataSourceAlicloudWafInstances(),
"alicloud_eci_image_caches": dataSourceAlicloudEciImageCaches(),
"alicloud_dms_enterprise_users": dataSourceAlicloudDmsEnterpriseUsers(),
"alicloud_ecs_dedicated_hosts": dataSourceAlicloudEcsDedicatedHosts(),
"alicloud_oos_templates": dataSourceAlicloudOosTemplates(),
"alicloud_oos_executions": dataSourceAlicloudOosExecutions(),
"alicloud_resource_manager_policy_attachments": dataSourceAlicloudResourceManagerPolicyAttachments(),
"alicloud_dcdn_domains": dataSourceAlicloudDcdnDomains(),
"alicloud_mse_clusters": dataSourceAlicloudMseClusters(),
"alicloud_actiontrail_trails": dataSourceAlicloudActiontrailTrails(),
"alicloud_actiontrails": dataSourceAlicloudActiontrailTrails(),
"alicloud_alidns_instances": dataSourceAlicloudAlidnsInstances(),
"alicloud_alidns_domains": dataSourceAlicloudAlidnsDomains(),
"alicloud_log_service": dataSourceAlicloudLogService(),
"alicloud_cen_instance_attachments": dataSourceAlicloudCenInstanceAttachments(),
"alicloud_cdn_service": dataSourceAlicloudCdnService(),
"alicloud_cen_vbr_health_checks": dataSourceAlicloudCenVbrHealthChecks(),
"alicloud_config_rules": dataSourceAlicloudConfigRules(),
"alicloud_config_configuration_recorders": dataSourceAlicloudConfigConfigurationRecorders(),
"alicloud_config_delivery_channels": dataSourceAlicloudConfigDeliveryChannels(),
"alicloud_cms_alarm_contacts": dataSourceAlicloudCmsAlarmContacts(),
"alicloud_kvstore_connections": dataSourceAlicloudKvstoreConnections(),
"alicloud_cms_alarm_contact_groups": dataSourceAlicloudCmsAlarmContactGroups(),
"alicloud_enhanced_nat_available_zones": dataSourceAlicloudEnhancedNatAvailableZones(),
"alicloud_cen_route_services": dataSourceAlicloudCenRouteServices(),
"alicloud_kvstore_accounts": dataSourceAlicloudKvstoreAccounts(),
"alicloud_cms_group_metric_rules": dataSourceAlicloudCmsGroupMetricRules(),
"alicloud_fnf_flows": dataSourceAlicloudFnfFlows(),
"alicloud_fnf_schedules": dataSourceAlicloudFnfSchedules(),
"alicloud_ros_change_sets": dataSourceAlicloudRosChangeSets(),
"alicloud_ros_stacks": dataSourceAlicloudRosStacks(),
"alicloud_ros_stack_groups": dataSourceAlicloudRosStackGroups(),
"alicloud_ros_templates": dataSourceAlicloudRosTemplates(),
"alicloud_privatelink_vpc_endpoint_services": dataSourceAlicloudPrivatelinkVpcEndpointServices(),
"alicloud_privatelink_vpc_endpoints": dataSourceAlicloudPrivatelinkVpcEndpoints(),
"alicloud_privatelink_vpc_endpoint_connections": dataSourceAlicloudPrivatelinkVpcEndpointConnections(),
"alicloud_privatelink_vpc_endpoint_service_resources": dataSourceAlicloudPrivatelinkVpcEndpointServiceResources(),
"alicloud_privatelink_vpc_endpoint_service_users": dataSourceAlicloudPrivatelinkVpcEndpointServiceUsers(),
"alicloud_resource_manager_resource_shares": dataSourceAlicloudResourceManagerResourceShares(),
"alicloud_privatelink_vpc_endpoint_zones": dataSourceAlicloudPrivatelinkVpcEndpointZones(),
"alicloud_ga_accelerators": dataSourceAlicloudGaAccelerators(),
"alicloud_eci_container_groups": dataSourceAlicloudEciContainerGroups(),
"alicloud_resource_manager_shared_resources": dataSourceAlicloudResourceManagerSharedResources(),
"alicloud_resource_manager_shared_targets": dataSourceAlicloudResourceManagerSharedTargets(),
"alicloud_ga_listeners": dataSourceAlicloudGaListeners(),
"alicloud_tsdb_instances": dataSourceAlicloudTsdbInstances(),
"alicloud_tsdb_zones": dataSourceAlicloudTsdbZones(),
"alicloud_ga_bandwidth_packages": dataSourceAlicloudGaBandwidthPackages(),
"alicloud_ga_endpoint_groups": dataSourceAlicloudGaEndpointGroups(),
"alicloud_brain_industrial_pid_organizations": dataSourceAlicloudBrainIndustrialPidOrganizations(),
"alicloud_ga_ip_sets": dataSourceAlicloudGaIpSets(),
"alicloud_ga_forwarding_rules": dataSourceAlicloudGaForwardingRules(),
"alicloud_eipanycast_anycast_eip_addresses": dataSourceAlicloudEipanycastAnycastEipAddresses(),
"alicloud_brain_industrial_pid_projects": dataSourceAlicloudBrainIndustrialPidProjects(),
"alicloud_cms_monitor_groups": dataSourceAlicloudCmsMonitorGroups(),
"alicloud_ram_saml_providers": dataSourceAlicloudRamSamlProviders(),
"alicloud_quotas_quotas": dataSourceAlicloudQuotasQuotas(),
"alicloud_quotas_application_infos": dataSourceAlicloudQuotasQuotaApplications(),
"alicloud_cms_monitor_group_instanceses": dataSourceAlicloudCmsMonitorGroupInstances(),
"alicloud_cms_monitor_group_instances": dataSourceAlicloudCmsMonitorGroupInstances(),
"alicloud_quotas_quota_alarms": dataSourceAlicloudQuotasQuotaAlarms(),
"alicloud_ecs_commands": dataSourceAlicloudEcsCommands(),
"alicloud_cloud_storage_gateway_storage_bundles": dataSourceAlicloudCloudStorageGatewayStorageBundles(),
"alicloud_ecs_hpc_clusters": dataSourceAlicloudEcsHpcClusters(),
"alicloud_brain_industrial_pid_loops": dataSourceAlicloudBrainIndustrialPidLoops(),
"alicloud_quotas_quota_applications": dataSourceAlicloudQuotasQuotaApplications(),
"alicloud_ecs_auto_snapshot_policies": dataSourceAlicloudEcsAutoSnapshotPolicies(),
"alicloud_rds_parameter_groups": dataSourceAlicloudRdsParameterGroups(),
"alicloud_ecs_launch_templates": dataSourceAlicloudEcsLaunchTemplates(),
"alicloud_resource_manager_control_policies": dataSourceAlicloudResourceManagerControlPolicies(),
"alicloud_resource_manager_control_policy_attachments": dataSourceAlicloudResourceManagerControlPolicyAttachments(),
"alicloud_rds_accounts": dataSourceAlicloudRdsAccounts(),
"alicloud_havips": dataSourceAlicloudHavips(),
"alicloud_ecs_snapshots": dataSourceAlicloudEcsSnapshots(),
"alicloud_ecs_key_pairs": dataSourceAlicloudEcsKeyPairs(),
"alicloud_adb_db_clusters": dataSourceAlicloudAdbDbClusters(),
"alicloud_vpc_flow_logs": dataSourceAlicloudVpcFlowLogs(),
"alicloud_network_acls": dataSourceAlicloudNetworkAcls(),
"alicloud_ecs_disks": dataSourceAlicloudEcsDisks(),
"alicloud_ddoscoo_domain_resources": dataSourceAlicloudDdoscooDomainResources(),
"alicloud_ddoscoo_ports": dataSourceAlicloudDdoscooPorts(),
"alicloud_slb_load_balancers": dataSourceAlicloudSlbLoadBalancers(),
"alicloud_ecs_network_interfaces": dataSourceAlicloudEcsNetworkInterfaces(),
"alicloud_config_aggregators": dataSourceAlicloudConfigAggregators(),
"alicloud_config_aggregate_config_rules": dataSourceAlicloudConfigAggregateConfigRules(),
"alicloud_config_aggregate_compliance_packs": dataSourceAlicloudConfigAggregateCompliancePacks(),
"alicloud_config_compliance_packs": dataSourceAlicloudConfigCompliancePacks(),
"alicloud_eip_addresses": dataSourceAlicloudEipAddresses(),
"alicloud_direct_mail_receiverses": dataSourceAlicloudDirectMailReceiverses(),
"alicloud_log_projects": dataSourceAlicloudLogProjects(),
"alicloud_log_stores": dataSourceAlicloudLogStores(),
"alicloud_event_bridge_service": dataSourceAlicloudEventBridgeService(),
"alicloud_event_bridge_event_buses": dataSourceAlicloudEventBridgeEventBuses(),
"alicloud_amqp_virtual_hosts": dataSourceAlicloudAmqpVirtualHosts(),
"alicloud_amqp_queues": dataSourceAlicloudAmqpQueues(),
"alicloud_amqp_exchanges": dataSourceAlicloudAmqpExchanges(),
"alicloud_cassandra_backup_plans": dataSourceAlicloudCassandraBackupPlans(),
"alicloud_cen_transit_router_peer_attachments": dataSourceAlicloudCenTransitRouterPeerAttachments(),
"alicloud_amqp_instances": dataSourceAlicloudAmqpInstances(),
"alicloud_hbr_vaults": dataSourceAlicloudHbrVaults(),
"alicloud_ssl_certificates_service_certificates": dataSourceAlicloudSslCertificatesServiceCertificates(),
"alicloud_arms_alert_contacts": dataSourceAlicloudArmsAlertContacts(),
"alicloud_event_bridge_rules": dataSourceAlicloudEventBridgeRules(),
"alicloud_cloud_firewall_control_policies": dataSourceAlicloudCloudFirewallControlPolicies(),
"alicloud_sae_namespaces": dataSourceAlicloudSaeNamespaces(),
"alicloud_sae_config_maps": dataSourceAlicloudSaeConfigMaps(),
"alicloud_alb_security_policies": dataSourceAlicloudAlbSecurityPolicies(),
"alicloud_event_bridge_event_sources": dataSourceAlicloudEventBridgeEventSources(),
"alicloud_ecd_policy_groups": dataSourceAlicloudEcdPolicyGroups(),
"alicloud_ecp_key_pairs": dataSourceAlicloudEcpKeyPairs(),
"alicloud_hbr_ecs_backup_plans": dataSourceAlicloudHbrEcsBackupPlans(),
"alicloud_hbr_nas_backup_plans": dataSourceAlicloudHbrNasBackupPlans(),
"alicloud_hbr_oss_backup_plans": dataSourceAlicloudHbrOssBackupPlans(),
"alicloud_scdn_domains": dataSourceAlicloudScdnDomains(),
"alicloud_alb_server_groups": dataSourceAlicloudAlbServerGroups(),
"alicloud_data_works_folders": dataSourceAlicloudDataWorksFolders(),
"alicloud_arms_alert_contact_groups": dataSourceAlicloudArmsAlertContactGroups(),
"alicloud_express_connect_access_points": dataSourceAlicloudExpressConnectAccessPoints(),
"alicloud_cloud_storage_gateway_gateways": dataSourceAlicloudCloudStorageGatewayGateways(),
"alicloud_lindorm_instances": dataSourceAlicloudLindormInstances(),
"alicloud_express_connect_physical_connection_service": dataSourceAlicloudExpressConnectPhysicalConnectionService(),
"alicloud_cddc_dedicated_host_groups": dataSourceAlicloudCddcDedicatedHostGroups(),
"alicloud_hbr_ecs_backup_clients": dataSourceAlicloudHbrEcsBackupClients(),
"alicloud_msc_sub_contacts": dataSourceAlicloudMscSubContacts(),
"alicloud_express_connect_physical_connections": dataSourceAlicloudExpressConnectPhysicalConnections(),
"alicloud_alb_load_balancers": dataSourceAlicloudAlbLoadBalancers(),
"alicloud_alb_zones": dataSourceAlicloudAlbZones(),
"alicloud_sddp_rules": dataSourceAlicloudSddpRules(),
"alicloud_bastionhost_user_groups": dataSourceAlicloudBastionhostUserGroups(),
"alicloud_security_center_groups": dataSourceAlicloudSecurityCenterGroups(),
"alicloud_alb_acls": dataSourceAlicloudAlbAcls(),
"alicloud_hbr_snapshots": dataSourceAlicloudHbrSnapshots(),
"alicloud_bastionhost_users": dataSourceAlicloudBastionhostUsers(),
"alicloud_dfs_access_groups": dataSourceAlicloudDfsAccessGroups(),
"alicloud_ehpc_job_templates": dataSourceAlicloudEhpcJobTemplates(),
"alicloud_sddp_configs": dataSourceAlicloudSddpConfigs(),
"alicloud_hbr_restore_jobs": dataSourceAlicloudHbrRestoreJobs(),
"alicloud_alb_listeners": dataSourceAlicloudAlbListeners(),
"alicloud_ens_key_pairs": dataSourceAlicloudEnsKeyPairs(),
"alicloud_sae_applications": dataSourceAlicloudSaeApplications(),
"alicloud_alb_rules": dataSourceAlicloudAlbRules(),
"alicloud_cms_metric_rule_templates": dataSourceAlicloudCmsMetricRuleTemplates(),
"alicloud_iot_device_groups": dataSourceAlicloudIotDeviceGroups(),
"alicloud_express_connect_virtual_border_routers": dataSourceAlicloudExpressConnectVirtualBorderRouters(),
"alicloud_imm_projects": dataSourceAlicloudImmProjects(),
"alicloud_click_house_db_clusters": dataSourceAlicloudClickHouseDbClusters(),
"alicloud_direct_mail_domains": dataSourceAlicloudDirectMailDomains(),
"alicloud_bastionhost_host_groups": dataSourceAlicloudBastionhostHostGroups(),
"alicloud_vpc_dhcp_options_sets": dataSourceAlicloudVpcDhcpOptionsSets(),
"alicloud_alb_health_check_templates": dataSourceAlicloudAlbHealthCheckTemplates(),
"alicloud_cdn_real_time_log_deliveries": dataSourceAlicloudCdnRealTimeLogDeliveries(),
"alicloud_click_house_accounts": dataSourceAlicloudClickHouseAccounts(),
"alicloud_direct_mail_mail_addresses": dataSourceAlicloudDirectMailMailAddresses(),
"alicloud_database_gateway_gateways": dataSourceAlicloudDatabaseGatewayGateways(),
"alicloud_bastionhost_hosts": dataSourceAlicloudBastionhostHosts(),
"alicloud_amqp_bindings": dataSourceAlicloudAmqpBindings(),
"alicloud_slb_tls_cipher_policies": dataSourceAlicloudSlbTlsCipherPolicies(),
"alicloud_cloud_sso_directories": dataSourceAlicloudCloudSsoDirectories(),
"alicloud_bastionhost_host_accounts": dataSourceAlicloudBastionhostHostAccounts(),
"alicloud_waf_certificates": dataSourceAlicloudWafCertificates(),
"alicloud_simple_application_server_instances": dataSourceAlicloudSimpleApplicationServerInstances(),
"alicloud_simple_application_server_plans": dataSourceAlicloudSimpleApplicationServerPlans(),
"alicloud_simple_application_server_images": dataSourceAlicloudSimpleApplicationServerImages(),
"alicloud_video_surveillance_system_groups": dataSourceAlicloudVideoSurveillanceSystemGroups(),
"alicloud_msc_sub_subscriptions": dataSourceAlicloudMscSubSubscriptions(),
"alicloud_sddp_instances": dataSourceAlicloudSddpInstances(),
"alicloud_vpc_nat_ip_cidrs": dataSourceAlicloudVpcNatIpCidrs(),
"alicloud_vpc_nat_ips": dataSourceAlicloudVpcNatIps(),
"alicloud_quick_bi_users": dataSourceAlicloudQuickBiUsers(),
"alicloud_vod_domains": dataSourceAlicloudVodDomains(),
"alicloud_arms_dispatch_rules": dataSourceAlicloudArmsDispatchRules(),
"alicloud_open_search_app_groups": dataSourceAlicloudOpenSearchAppGroups(),
"alicloud_graph_database_db_instances": dataSourceAlicloudGraphDatabaseDbInstances(),
"alicloud_arms_prometheus_alert_rules": dataSourceAlicloudArmsPrometheusAlertRules(),
"alicloud_dbfs_instances": dataSourceAlicloudDbfsInstances(),
"alicloud_rdc_organizations": dataSourceAlicloudRdcOrganizations(),
"alicloud_eais_instances": dataSourceAlicloudEaisInstances(),
"alicloud_sae_ingresses": dataSourceAlicloudSaeIngresses(),
"alicloud_cloudauth_face_configs": dataSourceAlicloudCloudauthFaceConfigs(),
"alicloud_imp_app_templates": dataSourceAlicloudImpAppTemplates(),
"alicloud_mhub_products": dataSourceAlicloudMhubProducts(),
"alicloud_cloud_sso_scim_server_credentials": dataSourceAlicloudCloudSsoScimServerCredentials(),
"alicloud_dts_subscription_jobs": dataSourceAlicloudDtsSubscriptionJobs(),
"alicloud_service_mesh_service_meshes": dataSourceAlicloudServiceMeshServiceMeshes(),
"alicloud_mhub_apps": dataSourceAlicloudMhubApps(),
"alicloud_cloud_sso_groups": dataSourceAlicloudCloudSsoGroups(),
"alicloud_hbr_backup_jobs": dataSourceAlicloudHbrBackupJobs(),
"alicloud_click_house_regions": dataSourceAlicloudClickHouseRegions(),
"alicloud_dts_synchronization_jobs": dataSourceAlicloudDtsSynchronizationJobs(),
"alicloud_cloud_firewall_instances": dataSourceAlicloudCloudFirewallInstances(),
"alicloud_cr_endpoint_acl_policies": dataSourceAlicloudCrEndpointAclPolicies(),
"alicloud_cr_endpoint_acl_service": dataSourceAlicloudCrEndpointAclService(),
"alicloud_actiontrail_history_delivery_jobs": dataSourceAlicloudActiontrailHistoryDeliveryJobs(),
"alicloud_sae_instance_specifications": dataSourceAlicloudSaeInstanceSpecifications(),
"alicloud_cen_transit_router_service": dataSourceAlicloudCenTransitRouterService(),
"alicloud_ecs_deployment_sets": dataSourceAlicloudEcsDeploymentSets(),
"alicloud_cloud_sso_users": dataSourceAlicloudCloudSsoUsers(),
"alicloud_cloud_sso_access_configurations": dataSourceAlicloudCloudSsoAccessConfigurations(),
"alicloud_dfs_file_systems": dataSourceAlicloudDfsFileSystems(),
"alicloud_dfs_zones": dataSourceAlicloudDfsZones(),
"alicloud_vpc_traffic_mirror_filters": dataSourceAlicloudVpcTrafficMirrorFilters(),
"alicloud_dfs_access_rules": dataSourceAlicloudDfsAccessRules(),
"alicloud_nas_zones": dataSourceAlicloudNasZones(),
"alicloud_dfs_mount_points": dataSourceAlicloudDfsMountPoints(),
"alicloud_vpc_traffic_mirror_filter_egress_rules": dataSourceAlicloudVpcTrafficMirrorFilterEgressRules(),
"alicloud_ecd_simple_office_sites": dataSourceAlicloudEcdSimpleOfficeSites(),
"alicloud_vpc_traffic_mirror_filter_ingress_rules": dataSourceAlicloudVpcTrafficMirrorFilterIngressRules(),
"alicloud_ecd_nas_file_systems": dataSourceAlicloudEcdNasFileSystems(),
"alicloud_vpc_traffic_mirror_service": dataSourceAlicloudVpcTrafficMirrorService(),
"alicloud_msc_sub_webhooks": dataSourceAlicloudMscSubWebhooks(),
"alicloud_ecd_users": dataSourceAlicloudEcdUsers(),
"alicloud_vpc_traffic_mirror_sessions": dataSourceAlicloudVpcTrafficMirrorSessions(),
"alicloud_gpdb_accounts": dataSourceAlicloudGpdbAccounts(),
"alicloud_vpc_ipv6_gateways": dataSourceAlicloudVpcIpv6Gateways(),
"alicloud_vpc_ipv6_egress_rules": dataSourceAlicloudVpcIpv6EgressRules(),
"alicloud_vpc_ipv6_addresses": dataSourceAlicloudVpcIpv6Addresses(),
"alicloud_hbr_server_backup_plans": dataSourceAlicloudHbrServerBackupPlans(),
"alicloud_cms_dynamic_tag_groups": dataSourceAlicloudCmsDynamicTagGroups(),
"alicloud_ecd_network_packages": dataSourceAlicloudEcdNetworkPackages(),
"alicloud_cloud_storage_gateway_gateway_smb_users": dataSourceAlicloudCloudStorageGatewayGatewaySmbUsers(),
"alicloud_vpc_ipv6_internet_bandwidths": dataSourceAlicloudVpcIpv6InternetBandwidths(),
"alicloud_simple_application_server_firewall_rules": dataSourceAlicloudSimpleApplicationServerFirewallRules(),
"alicloud_pvtz_endpoints": dataSourceAlicloudPvtzEndpoints(),
"alicloud_pvtz_resolver_zones": dataSourceAlicloudPvtzResolverZones(),
"alicloud_pvtz_rules": dataSourceAlicloudPvtzRules(),
"alicloud_ecd_bundles": dataSourceAlicloudEcdBundles(),
"alicloud_simple_application_server_disks": dataSourceAlicloudSimpleApplicationServerDisks(),
"alicloud_simple_application_server_snapshots": dataSourceAlicloudSimpleApplicationServerSnapshots(),
"alicloud_simple_application_server_custom_images": dataSourceAlicloudSimpleApplicationServerCustomImages(),
"alicloud_cloud_storage_gateway_stocks": dataSourceAlicloudCloudStorageGatewayStocks(),
"alicloud_cloud_storage_gateway_gateway_cache_disks": dataSourceAlicloudCloudStorageGatewayGatewayCacheDisks(),
"alicloud_cloud_storage_gateway_gateway_block_volumes": dataSourceAlicloudCloudStorageGatewayGatewayBlockVolumes(),
"alicloud_direct_mail_tags": dataSourceAlicloudDirectMailTags(),
"alicloud_cloud_storage_gateway_gateway_file_shares": dataSourceAlicloudCloudStorageGatewayGatewayFileShares(),
"alicloud_ecd_desktops": dataSourceAlicloudEcdDesktops(),
"alicloud_cloud_storage_gateway_express_syncs": dataSourceAlicloudCloudStorageGatewayExpressSyncs(),
"alicloud_oos_applications": dataSourceAlicloudOosApplications(),
"alicloud_eci_virtual_nodes": dataSourceAlicloudEciVirtualNodes(),
"alicloud_eci_zones": dataSourceAlicloudEciZones(),
"alicloud_ros_stack_instances": dataSourceAlicloudRosStackInstances(),
"alicloud_ros_regions": dataSourceAlicloudRosRegions(),
"alicloud_ecs_dedicated_host_clusters": dataSourceAlicloudEcsDedicatedHostClusters(),
"alicloud_oos_application_groups": dataSourceAlicloudOosApplicationGroups(),
"alicloud_dts_consumer_channels": dataSourceAlicloudDtsConsumerChannels(),
"alicloud_emr_clusters": dataSourceAlicloudEmrClusters(),
"alicloud_ecd_images": dataSourceAlicloudEcdImages(),
"alicloud_oos_patch_baselines": dataSourceAlicloudOosPatchBaselines(),
"alicloud_ecd_commands": dataSourceAlicloudEcdCommands(),
"alicloud_cddc_zones": dataSourceAlicloudCddcZones(),
"alicloud_cddc_host_ecs_level_infos": dataSourceAlicloudCddcHostEcsLevelInfos(),
"alicloud_cddc_dedicated_hosts": dataSourceAlicloudCddcDedicatedHosts(),
"alicloud_oos_parameters": dataSourceAlicloudOosParameters(),
"alicloud_oos_state_configurations": dataSourceAlicloudOosStateConfigurations(),
"alicloud_oos_secret_parameters": dataSourceAlicloudOosSecretParameters(),
"alicloud_click_house_backup_policies": dataSourceAlicloudClickHouseBackupPolicies(),
"alicloud_cloud_sso_service": dataSourceAlicloudCloudSsoService(),
"alicloud_mongodb_audit_policies": dataSourceAlicloudMongodbAuditPolicies(),
"alicloud_mongodb_accounts": dataSourceAlicloudMongodbAccounts(),
"alicloud_mongodb_serverless_instances": dataSourceAlicloudMongodbServerlessInstances(),
"alicloud_cddc_dedicated_host_accounts": dataSourceAlicloudCddcDedicatedHostAccounts(),
"alicloud_cr_chart_namespaces": dataSourceAlicloudCrChartNamespaces(),
"alicloud_fnf_executions": dataSourceAlicloudFnFExecutions(),
"alicloud_cr_chart_repositories": dataSourceAlicloudCrChartRepositories(),
"alicloud_mongodb_sharding_network_public_addresses": dataSourceAlicloudMongodbShardingNetworkPublicAddresses(),
"alicloud_ga_acls": dataSourceAlicloudGaAcls(),
"alicloud_ga_additional_certificates": dataSourceAlicloudGaAdditionalCertificates(),
"alicloud_alidns_custom_lines": dataSourceAlicloudAlidnsCustomLines(),
"alicloud_ros_template_scratches": dataSourceAlicloudRosTemplateScratches(),
"alicloud_alidns_gtm_instances": dataSourceAlicloudAlidnsGtmInstances(),
"alicloud_vpc_bgp_groups": dataSourceAlicloudVpcBgpGroups(),
"alicloud_nas_snapshots": dataSourceAlicloudNasSnapshots(),
"alicloud_hbr_replication_vault_regions": dataSourceAlicloudHbrReplicationVaultRegions(),
"alicloud_alidns_address_pools": dataSourceAlicloudAlidnsAddressPools(),
"alicloud_ecs_prefix_lists": dataSourceAlicloudEcsPrefixLists(),
"alicloud_alidns_access_strategies": dataSourceAlicloudAlidnsAccessStrategies(),
"alicloud_vpc_bgp_peers": dataSourceAlicloudVpcBgpPeers(),
"alicloud_nas_filesets": dataSourceAlicloudNasFilesets(),
"alicloud_cdn_ip_info": dataSourceAlicloudCdnIpInfo(),
"alicloud_nas_auto_snapshot_policies": dataSourceAlicloudNasAutoSnapshotPolicies(),
"alicloud_nas_lifecycle_policies": dataSourceAlicloudNasLifecyclePolicies(),
"alicloud_vpc_bgp_networks": dataSourceAlicloudVpcBgpNetworks(),
"alicloud_nas_data_flows": dataSourceAlicloudNasDataFlows(),
},
ResourcesMap: map[string]*schema.Resource{
"alicloud_instance": resourceAliyunInstance(),
"alicloud_image": resourceAliCloudImage(),
"alicloud_reserved_instance": resourceAliCloudReservedInstance(),
"alicloud_copy_image": resourceAliCloudImageCopy(),
"alicloud_image_export": resourceAliCloudImageExport(),
"alicloud_image_copy": resourceAliCloudImageCopy(),
"alicloud_image_import": resourceAliCloudImageImport(),
"alicloud_image_share_permission": resourceAliCloudImageSharePermission(),
"alicloud_ram_role_attachment": resourceAlicloudRamRoleAttachment(),
"alicloud_disk": resourceAlicloudEcsDisk(),
"alicloud_disk_attachment": resourceAlicloudEcsDiskAttachment(),
"alicloud_network_interface": resourceAlicloudEcsNetworkInterface(),
"alicloud_network_interface_attachment": resourceAlicloudEcsNetworkInterfaceAttachment(),
"alicloud_snapshot": resourceAlicloudEcsSnapshot(),
"alicloud_snapshot_policy": resourceAlicloudEcsAutoSnapshotPolicy(),
"alicloud_launch_template": resourceAlicloudEcsLaunchTemplate(),
"alicloud_security_group": resourceAliyunSecurityGroup(),
"alicloud_security_group_rule": resourceAliyunSecurityGroupRule(),
"alicloud_db_database": resourceAlicloudDBDatabase(),
"alicloud_db_account": resourceAlicloudRdsAccount(),
"alicloud_db_account_privilege": resourceAlicloudDBAccountPrivilege(),
"alicloud_db_backup_policy": resourceAlicloudDBBackupPolicy(),
"alicloud_db_connection": resourceAlicloudDBConnection(),
"alicloud_db_read_write_splitting_connection": resourceAlicloudDBReadWriteSplittingConnection(),
"alicloud_db_instance": resourceAlicloudDBInstance(),
"alicloud_rds_backup": resourceAlicloudRdsBackup(),
"alicloud_rds_clone_db_instance": resourceAlicloudRdsCloneDbInstance(),
"alicloud_rds_upgrade_db_instance": resourceAlicloudRdsUpgradeDbInstance(),
"alicloud_mongodb_instance": resourceAlicloudMongoDBInstance(),
"alicloud_mongodb_sharding_instance": resourceAlicloudMongoDBShardingInstance(),
"alicloud_gpdb_instance": resourceAlicloudGpdbInstance(),
"alicloud_gpdb_elastic_instance": resourceAlicloudGpdbElasticInstance(),
"alicloud_gpdb_connection": resourceAlicloudGpdbConnection(),
"alicloud_db_readonly_instance": resourceAlicloudDBReadonlyInstance(),
"alicloud_auto_provisioning_group": resourceAlicloudAutoProvisioningGroup(),
"alicloud_ess_scaling_group": resourceAlicloudEssScalingGroup(),
"alicloud_ess_scaling_configuration": resourceAlicloudEssScalingConfiguration(),
"alicloud_ess_scaling_rule": resourceAlicloudEssScalingRule(),
"alicloud_ess_schedule": resourceAlicloudEssScheduledTask(),
"alicloud_ess_scheduled_task": resourceAlicloudEssScheduledTask(),
"alicloud_ess_attachment": resourceAlicloudEssAttachment(),
"alicloud_ess_lifecycle_hook": resourceAlicloudEssLifecycleHook(),
"alicloud_ess_notification": resourceAlicloudEssNotification(),
"alicloud_ess_alarm": resourceAlicloudEssAlarm(),
"alicloud_ess_scalinggroup_vserver_groups": resourceAlicloudEssScalingGroupVserverGroups(),
"alicloud_vpc": resourceAlicloudVpc(),
"alicloud_nat_gateway": resourceAlicloudNatGateway(),
"alicloud_nas_file_system": resourceAlicloudNasFileSystem(),
"alicloud_nas_mount_target": resourceAlicloudNasMountTarget(),
"alicloud_nas_access_group": resourceAlicloudNasAccessGroup(),
"alicloud_nas_access_rule": resourceAlicloudNasAccessRule(),
// "alicloud_subnet" aims to match aws usage habit.
"alicloud_subnet": resourceAlicloudVswitch(),
"alicloud_vswitch": resourceAlicloudVswitch(),
"alicloud_route_entry": resourceAliyunRouteEntry(),
"alicloud_route_table": resourceAlicloudRouteTable(),
"alicloud_route_table_attachment": resourceAliyunRouteTableAttachment(),
"alicloud_snat_entry": resourceAlicloudSnatEntry(),
"alicloud_forward_entry": resourceAlicloudForwardEntry(),
"alicloud_eip": resourceAlicloudEipAddress(),
"alicloud_eip_association": resourceAliyunEipAssociation(),
"alicloud_slb": resourceAlicloudSlbLoadBalancer(),
"alicloud_slb_listener": resourceAliyunSlbListener(),
"alicloud_slb_attachment": resourceAliyunSlbAttachment(),
"alicloud_slb_backend_server": resourceAliyunSlbBackendServer(),
"alicloud_slb_domain_extension": resourceAlicloudSlbDomainExtension(),
"alicloud_slb_server_group": resourceAliyunSlbServerGroup(),
"alicloud_slb_master_slave_server_group": resourceAliyunSlbMasterSlaveServerGroup(),
"alicloud_slb_rule": resourceAliyunSlbRule(),
"alicloud_slb_acl": resourceAlicloudSlbAcl(),
"alicloud_slb_ca_certificate": resourceAlicloudSlbCaCertificate(),
"alicloud_slb_server_certificate": resourceAlicloudSlbServerCertificate(),
"alicloud_oss_bucket": resourceAlicloudOssBucket(),
"alicloud_oss_bucket_object": resourceAlicloudOssBucketObject(),
"alicloud_ons_instance": resourceAlicloudOnsInstance(),
"alicloud_ons_topic": resourceAlicloudOnsTopic(),
"alicloud_ons_group": resourceAlicloudOnsGroup(),
"alicloud_alikafka_consumer_group": resourceAlicloudAlikafkaConsumerGroup(),
"alicloud_alikafka_instance": resourceAlicloudAlikafkaInstance(),
"alicloud_alikafka_topic": resourceAlicloudAlikafkaTopic(),
"alicloud_alikafka_sasl_user": resourceAlicloudAlikafkaSaslUser(),
"alicloud_alikafka_sasl_acl": resourceAlicloudAlikafkaSaslAcl(),
"alicloud_dns_record": resourceAlicloudDnsRecord(),
"alicloud_dns": resourceAlicloudDns(),
"alicloud_dns_group": resourceAlicloudDnsGroup(),
"alicloud_key_pair": resourceAlicloudEcsKeyPair(),
"alicloud_key_pair_attachment": resourceAlicloudEcsKeyPairAttachment(),
"alicloud_kms_key": resourceAlicloudKmsKey(),
"alicloud_kms_ciphertext": resourceAlicloudKmsCiphertext(),
"alicloud_ram_user": resourceAlicloudRamUser(),
"alicloud_ram_account_password_policy": resourceAlicloudRamAccountPasswordPolicy(),
"alicloud_ram_access_key": resourceAlicloudRamAccessKey(),
"alicloud_ram_login_profile": resourceAlicloudRamLoginProfile(),
"alicloud_ram_group": resourceAlicloudRamGroup(),
"alicloud_ram_role": resourceAlicloudRamRole(),
"alicloud_ram_policy": resourceAlicloudRamPolicy(),
// alicloud_ram_alias has been deprecated
"alicloud_ram_alias": resourceAlicloudRamAccountAlias(),
"alicloud_ram_account_alias": resourceAlicloudRamAccountAlias(),
"alicloud_ram_group_membership": resourceAlicloudRamGroupMembership(),
"alicloud_ram_user_policy_attachment": resourceAlicloudRamUserPolicyAtatchment(),
"alicloud_ram_role_policy_attachment": resourceAlicloudRamRolePolicyAttachment(),
"alicloud_ram_group_policy_attachment": resourceAlicloudRamGroupPolicyAtatchment(),
"alicloud_container_cluster": resourceAlicloudCSSwarm(),
"alicloud_cs_application": resourceAlicloudCSApplication(),
"alicloud_cs_swarm": resourceAlicloudCSSwarm(),
"alicloud_cs_kubernetes": resourceAlicloudCSKubernetes(),
"alicloud_cs_kubernetes_addon": resourceAlicloudCSKubernetesAddon(),
"alicloud_cs_managed_kubernetes": resourceAlicloudCSManagedKubernetes(),
"alicloud_cs_edge_kubernetes": resourceAlicloudCSEdgeKubernetes(),
"alicloud_cs_serverless_kubernetes": resourceAlicloudCSServerlessKubernetes(),
"alicloud_cs_kubernetes_autoscaler": resourceAlicloudCSKubernetesAutoscaler(),
"alicloud_cs_kubernetes_node_pool": resourceAlicloudCSKubernetesNodePool(),
"alicloud_cs_kubernetes_permissions": resourceAlicloudCSKubernetesPermissions(),
"alicloud_cs_autoscaling_config": resourceAlicloudCSAutoscalingConfig(),
"alicloud_cr_namespace": resourceAlicloudCRNamespace(),
"alicloud_cr_repo": resourceAlicloudCRRepo(),
"alicloud_cr_ee_instance": resourceAlicloudCrEEInstance(),
"alicloud_cr_ee_namespace": resourceAlicloudCrEENamespace(),
"alicloud_cr_ee_repo": resourceAlicloudCrEERepo(),
"alicloud_cr_ee_sync_rule": resourceAlicloudCrEESyncRule(),
"alicloud_cdn_domain": resourceAlicloudCdnDomain(),
"alicloud_cdn_domain_new": resourceAlicloudCdnDomainNew(),
"alicloud_cdn_domain_config": resourceAlicloudCdnDomainConfig(),
"alicloud_router_interface": resourceAlicloudRouterInterface(),
"alicloud_router_interface_connection": resourceAlicloudRouterInterfaceConnection(),
"alicloud_ots_table": resourceAlicloudOtsTable(),
"alicloud_ots_instance": resourceAlicloudOtsInstance(),
"alicloud_ots_instance_attachment": resourceAlicloudOtsInstanceAttachment(),
"alicloud_cms_alarm": resourceAlicloudCmsAlarm(),
"alicloud_cms_site_monitor": resourceAlicloudCmsSiteMonitor(),
"alicloud_pvtz_zone": resourceAlicloudPvtzZone(),
"alicloud_pvtz_zone_attachment": resourceAlicloudPvtzZoneAttachment(),
"alicloud_pvtz_zone_record": resourceAlicloudPvtzZoneRecord(),
"alicloud_log_alert": resourceAlicloudLogAlert(),
"alicloud_log_audit": resourceAlicloudLogAudit(),
"alicloud_log_dashboard": resourceAlicloudLogDashboard(),
"alicloud_log_etl": resourceAlicloudLogETL(),
"alicloud_log_machine_group": resourceAlicloudLogMachineGroup(),
"alicloud_log_oss_shipper": resourceAlicloudLogOssShipper(),
"alicloud_log_project": resourceAlicloudLogProject(),
"alicloud_log_store": resourceAlicloudLogStore(),
"alicloud_log_store_index": resourceAlicloudLogStoreIndex(),
"alicloud_logtail_config": resourceAlicloudLogtailConfig(),
"alicloud_logtail_attachment": resourceAlicloudLogtailAttachment(),
"alicloud_fc_service": resourceAlicloudFCService(),
"alicloud_fc_function": resourceAlicloudFCFunction(),
"alicloud_fc_trigger": resourceAlicloudFCTrigger(),
"alicloud_fc_alias": resourceAlicloudFCAlias(),
"alicloud_fc_custom_domain": resourceAlicloudFCCustomDomain(),
"alicloud_fc_function_async_invoke_config": resourceAlicloudFCFunctionAsyncInvokeConfig(),
"alicloud_vpn_gateway": resourceAliyunVpnGateway(),
"alicloud_vpn_customer_gateway": resourceAliyunVpnCustomerGateway(),
"alicloud_vpn_route_entry": resourceAliyunVpnRouteEntry(),
"alicloud_vpn_connection": resourceAliyunVpnConnection(),
"alicloud_ssl_vpn_server": resourceAliyunSslVpnServer(),
"alicloud_ssl_vpn_client_cert": resourceAliyunSslVpnClientCert(),
"alicloud_cen_instance": resourceAlicloudCenInstance(),
"alicloud_cen_instance_attachment": resourceAlicloudCenInstanceAttachment(),
"alicloud_cen_bandwidth_package": resourceAlicloudCenBandwidthPackage(),
"alicloud_cen_bandwidth_package_attachment": resourceAlicloudCenBandwidthPackageAttachment(),
"alicloud_cen_bandwidth_limit": resourceAlicloudCenBandwidthLimit(),
"alicloud_cen_route_entry": resourceAlicloudCenRouteEntry(),
"alicloud_cen_instance_grant": resourceAlicloudCenInstanceGrant(),
"alicloud_cen_transit_router": resourceAlicloudCenTransitRouter(),
"alicloud_cen_transit_router_route_entry": resourceAlicloudCenTransitRouterRouteEntry(),
"alicloud_cen_transit_router_route_table": resourceAlicloudCenTransitRouterRouteTable(),
"alicloud_cen_transit_router_route_table_association": resourceAlicloudCenTransitRouterRouteTableAssociation(),
"alicloud_cen_transit_router_route_table_propagation": resourceAlicloudCenTransitRouterRouteTablePropagation(),
"alicloud_cen_transit_router_vbr_attachment": resourceAlicloudCenTransitRouterVbrAttachment(),
"alicloud_cen_transit_router_vpc_attachment": resourceAlicloudCenTransitRouterVpcAttachment(),
"alicloud_kvstore_instance": resourceAlicloudKvstoreInstance(),
"alicloud_kvstore_backup_policy": resourceAlicloudKVStoreBackupPolicy(),
"alicloud_kvstore_account": resourceAlicloudKvstoreAccount(),
"alicloud_datahub_project": resourceAlicloudDatahubProject(),
"alicloud_datahub_subscription": resourceAlicloudDatahubSubscription(),
"alicloud_datahub_topic": resourceAlicloudDatahubTopic(),
"alicloud_mns_queue": resourceAlicloudMNSQueue(),
"alicloud_mns_topic": resourceAlicloudMNSTopic(),
"alicloud_havip": resourceAlicloudHavip(),
"alicloud_mns_topic_subscription": resourceAlicloudMNSSubscription(),
"alicloud_havip_attachment": resourceAliyunHaVipAttachment(),
"alicloud_api_gateway_api": resourceAliyunApigatewayApi(),
"alicloud_api_gateway_group": resourceAliyunApigatewayGroup(),
"alicloud_api_gateway_app": resourceAliyunApigatewayApp(),
"alicloud_api_gateway_app_attachment": resourceAliyunApigatewayAppAttachment(),
"alicloud_api_gateway_vpc_access": resourceAliyunApigatewayVpc(),
"alicloud_common_bandwidth_package": resourceAlicloudCommonBandwidthPackage(),
"alicloud_common_bandwidth_package_attachment": resourceAliyunCommonBandwidthPackageAttachment(),
"alicloud_drds_instance": resourceAlicloudDRDSInstance(),
"alicloud_elasticsearch_instance": resourceAlicloudElasticsearch(),
"alicloud_cas_certificate": resourceAlicloudSslCertificatesServiceCertificate(),
"alicloud_ddoscoo_instance": resourceAlicloudDdoscooInstance(),
"alicloud_ddosbgp_instance": resourceAlicloudDdosbgpInstance(),
"alicloud_network_acl": resourceAlicloudNetworkAcl(),
"alicloud_network_acl_attachment": resourceAliyunNetworkAclAttachment(),
"alicloud_network_acl_entries": resourceAliyunNetworkAclEntries(),
"alicloud_emr_cluster": resourceAlicloudEmrCluster(),
"alicloud_cloud_connect_network": resourceAlicloudCloudConnectNetwork(),
"alicloud_cloud_connect_network_attachment": resourceAlicloudCloudConnectNetworkAttachment(),
"alicloud_cloud_connect_network_grant": resourceAlicloudCloudConnectNetworkGrant(),
"alicloud_sag_acl": resourceAlicloudSagAcl(),
"alicloud_sag_acl_rule": resourceAlicloudSagAclRule(),
"alicloud_sag_qos": resourceAlicloudSagQos(),
"alicloud_sag_qos_policy": resourceAlicloudSagQosPolicy(),
"alicloud_sag_qos_car": resourceAlicloudSagQosCar(),
"alicloud_sag_snat_entry": resourceAlicloudSagSnatEntry(),
"alicloud_sag_dnat_entry": resourceAlicloudSagDnatEntry(),
"alicloud_sag_client_user": resourceAlicloudSagClientUser(),
"alicloud_yundun_dbaudit_instance": resourceAlicloudDbauditInstance(),
"alicloud_yundun_bastionhost_instance": resourceAlicloudBastionhostInstance(),
"alicloud_bastionhost_instance": resourceAlicloudBastionhostInstance(),
"alicloud_polardb_cluster": resourceAlicloudPolarDBCluster(),
"alicloud_polardb_backup_policy": resourceAlicloudPolarDBBackupPolicy(),
"alicloud_polardb_database": resourceAlicloudPolarDBDatabase(),
"alicloud_polardb_account": resourceAlicloudPolarDBAccount(),
"alicloud_polardb_account_privilege": resourceAlicloudPolarDBAccountPrivilege(),
"alicloud_polardb_endpoint": resourceAlicloudPolarDBEndpoint(),
"alicloud_polardb_endpoint_address": resourceAlicloudPolarDBEndpointAddress(),
"alicloud_hbase_instance": resourceAlicloudHBaseInstance(),
"alicloud_market_order": resourceAlicloudMarketOrder(),
"alicloud_adb_cluster": resourceAlicloudAdbDbCluster(),
"alicloud_adb_backup_policy": resourceAlicloudAdbBackupPolicy(),
"alicloud_adb_account": resourceAlicloudAdbAccount(),
"alicloud_adb_connection": resourceAlicloudAdbConnection(),
"alicloud_cen_flowlog": resourceAlicloudCenFlowlog(),
"alicloud_kms_secret": resourceAlicloudKmsSecret(),
"alicloud_maxcompute_project": resourceAlicloudMaxcomputeProject(),
"alicloud_kms_alias": resourceAlicloudKmsAlias(),
"alicloud_dns_instance": resourceAlicloudAlidnsInstance(),
"alicloud_dns_domain_attachment": resourceAlicloudAlidnsDomainAttachment(),
"alicloud_alidns_domain_attachment": resourceAlicloudAlidnsDomainAttachment(),
"alicloud_edas_application": resourceAlicloudEdasApplication(),
"alicloud_edas_deploy_group": resourceAlicloudEdasDeployGroup(),
"alicloud_edas_application_scale": resourceAlicloudEdasInstanceApplicationAttachment(),
"alicloud_edas_slb_attachment": resourceAlicloudEdasSlbAttachment(),
"alicloud_edas_cluster": resourceAlicloudEdasCluster(),
"alicloud_edas_instance_cluster_attachment": resourceAlicloudEdasInstanceClusterAttachment(),
"alicloud_edas_application_deployment": resourceAlicloudEdasApplicationPackageAttachment(),
"alicloud_dns_domain": resourceAlicloudAlidnsDomain(),
"alicloud_dms_enterprise_instance": resourceAlicloudDmsEnterpriseInstance(),
"alicloud_waf_domain": resourceAlicloudWafDomain(),
"alicloud_cen_route_map": resourceAlicloudCenRouteMap(),
"alicloud_resource_manager_role": resourceAlicloudResourceManagerRole(),
"alicloud_resource_manager_resource_group": resourceAlicloudResourceManagerResourceGroup(),
"alicloud_resource_manager_folder": resourceAlicloudResourceManagerFolder(),
"alicloud_resource_manager_handshake": resourceAlicloudResourceManagerHandshake(),
"alicloud_cen_private_zone": resourceAlicloudCenPrivateZone(),
"alicloud_resource_manager_policy": resourceAlicloudResourceManagerPolicy(),
"alicloud_resource_manager_account": resourceAlicloudResourceManagerAccount(),
"alicloud_waf_instance": resourceAlicloudWafInstance(),
"alicloud_resource_manager_resource_directory": resourceAlicloudResourceManagerResourceDirectory(),
"alicloud_alidns_domain_group": resourceAlicloudAlidnsDomainGroup(),
"alicloud_resource_manager_policy_version": resourceAlicloudResourceManagerPolicyVersion(),
"alicloud_kms_key_version": resourceAlicloudKmsKeyVersion(),
"alicloud_alidns_record": resourceAlicloudAlidnsRecord(),
"alicloud_ddoscoo_scheduler_rule": resourceAlicloudDdoscooSchedulerRule(),
"alicloud_cassandra_cluster": resourceAlicloudCassandraCluster(),
"alicloud_cassandra_data_center": resourceAlicloudCassandraDataCenter(),
"alicloud_cen_vbr_health_check": resourceAlicloudCenVbrHealthCheck(),
"alicloud_eci_openapi_image_cache": resourceAlicloudEciImageCache(),
"alicloud_eci_image_cache": resourceAlicloudEciImageCache(),
"alicloud_dms_enterprise_user": resourceAlicloudDmsEnterpriseUser(),
"alicloud_ecs_dedicated_host": resourceAlicloudEcsDedicatedHost(),
"alicloud_oos_template": resourceAlicloudOosTemplate(),
"alicloud_edas_k8s_cluster": resourceAlicloudEdasK8sCluster(),
"alicloud_oos_execution": resourceAlicloudOosExecution(),
"alicloud_resource_manager_policy_attachment": resourceAlicloudResourceManagerPolicyAttachment(),
"alicloud_dcdn_domain": resourceAlicloudDcdnDomain(),
"alicloud_mse_cluster": resourceAlicloudMseCluster(),
"alicloud_actiontrail_trail": resourceAlicloudActiontrailTrail(),
"alicloud_actiontrail": resourceAlicloudActiontrailTrail(),
"alicloud_alidns_domain": resourceAlicloudAlidnsDomain(),
"alicloud_alidns_instance": resourceAlicloudAlidnsInstance(),
"alicloud_edas_k8s_application": resourceAlicloudEdasK8sApplication(),
"alicloud_config_rule": resourceAlicloudConfigRule(),
"alicloud_config_configuration_recorder": resourceAlicloudConfigConfigurationRecorder(),
"alicloud_config_delivery_channel": resourceAlicloudConfigDeliveryChannel(),
"alicloud_cms_alarm_contact": resourceAlicloudCmsAlarmContact(),
"alicloud_cen_route_service": resourceAlicloudCenRouteService(),
"alicloud_kvstore_connection": resourceAlicloudKvstoreConnection(),
"alicloud_cms_alarm_contact_group": resourceAlicloudCmsAlarmContactGroup(),
"alicloud_cms_group_metric_rule": resourceAlicloudCmsGroupMetricRule(),
"alicloud_fnf_flow": resourceAlicloudFnfFlow(),
"alicloud_fnf_schedule": resourceAlicloudFnfSchedule(),
"alicloud_ros_change_set": resourceAlicloudRosChangeSet(),
"alicloud_ros_stack": resourceAlicloudRosStack(),
"alicloud_ros_stack_group": resourceAlicloudRosStackGroup(),
"alicloud_ros_template": resourceAlicloudRosTemplate(),
"alicloud_privatelink_vpc_endpoint_service": resourceAlicloudPrivatelinkVpcEndpointService(),
"alicloud_privatelink_vpc_endpoint": resourceAlicloudPrivatelinkVpcEndpoint(),
"alicloud_privatelink_vpc_endpoint_connection": resourceAlicloudPrivatelinkVpcEndpointConnection(),
"alicloud_privatelink_vpc_endpoint_service_resource": resourceAlicloudPrivatelinkVpcEndpointServiceResource(),
"alicloud_privatelink_vpc_endpoint_service_user": resourceAlicloudPrivatelinkVpcEndpointServiceUser(),
"alicloud_resource_manager_resource_share": resourceAlicloudResourceManagerResourceShare(),
"alicloud_privatelink_vpc_endpoint_zone": resourceAlicloudPrivatelinkVpcEndpointZone(),
"alicloud_ga_accelerator": resourceAlicloudGaAccelerator(),
"alicloud_eci_container_group": resourceAlicloudEciContainerGroup(),
"alicloud_resource_manager_shared_resource": resourceAlicloudResourceManagerSharedResource(),
"alicloud_resource_manager_shared_target": resourceAlicloudResourceManagerSharedTarget(),
"alicloud_ga_listener": resourceAlicloudGaListener(),
"alicloud_tsdb_instance": resourceAlicloudTsdbInstance(),
"alicloud_ga_bandwidth_package": resourceAlicloudGaBandwidthPackage(),
"alicloud_ga_endpoint_group": resourceAlicloudGaEndpointGroup(),
"alicloud_brain_industrial_pid_organization": resourceAlicloudBrainIndustrialPidOrganization(),
"alicloud_ga_bandwidth_package_attachment": resourceAlicloudGaBandwidthPackageAttachment(),
"alicloud_ga_ip_set": resourceAlicloudGaIpSet(),
"alicloud_ga_forwarding_rule": resourceAlicloudGaForwardingRule(),
"alicloud_eipanycast_anycast_eip_address": resourceAlicloudEipanycastAnycastEipAddress(),
"alicloud_brain_industrial_pid_project": resourceAlicloudBrainIndustrialPidProject(),
"alicloud_cms_monitor_group": resourceAlicloudCmsMonitorGroup(),
"alicloud_eipanycast_anycast_eip_address_attachment": resourceAlicloudEipanycastAnycastEipAddressAttachment(),
"alicloud_ram_saml_provider": resourceAlicloudRamSamlProvider(),
"alicloud_quotas_application_info": resourceAlicloudQuotasQuotaApplication(),
"alicloud_cms_monitor_group_instances": resourceAlicloudCmsMonitorGroupInstances(),
"alicloud_quotas_quota_alarm": resourceAlicloudQuotasQuotaAlarm(),
"alicloud_ecs_command": resourceAlicloudEcsCommand(),
"alicloud_cloud_storage_gateway_storage_bundle": resourceAlicloudCloudStorageGatewayStorageBundle(),
"alicloud_ecs_hpc_cluster": resourceAlicloudEcsHpcCluster(),
"alicloud_vpc_flow_log": resourceAlicloudVpcFlowLog(),
"alicloud_brain_industrial_pid_loop": resourceAlicloudBrainIndustrialPidLoop(),
"alicloud_quotas_quota_application": resourceAlicloudQuotasQuotaApplication(),
"alicloud_ecs_auto_snapshot_policy": resourceAlicloudEcsAutoSnapshotPolicy(),
"alicloud_rds_parameter_group": resourceAlicloudRdsParameterGroup(),
"alicloud_ecs_launch_template": resourceAlicloudEcsLaunchTemplate(),
"alicloud_resource_manager_control_policy": resourceAlicloudResourceManagerControlPolicy(),
"alicloud_resource_manager_control_policy_attachment": resourceAlicloudResourceManagerControlPolicyAttachment(),
"alicloud_rds_account": resourceAlicloudRdsAccount(),
"alicloud_ecs_snapshot": resourceAlicloudEcsSnapshot(),
"alicloud_ecs_key_pair": resourceAlicloudEcsKeyPair(),
"alicloud_ecs_key_pair_attachment": resourceAlicloudEcsKeyPairAttachment(),
"alicloud_adb_db_cluster": resourceAlicloudAdbDbCluster(),
"alicloud_ecs_disk": resourceAlicloudEcsDisk(),
"alicloud_ecs_disk_attachment": resourceAlicloudEcsDiskAttachment(),
"alicloud_ecs_auto_snapshot_policy_attachment": resourceAlicloudEcsAutoSnapshotPolicyAttachment(),
"alicloud_ddoscoo_domain_resource": resourceAlicloudDdoscooDomainResource(),
"alicloud_ddoscoo_port": resourceAlicloudDdoscooPort(),
"alicloud_slb_load_balancer": resourceAlicloudSlbLoadBalancer(),
"alicloud_ecs_network_interface": resourceAlicloudEcsNetworkInterface(),
"alicloud_ecs_network_interface_attachment": resourceAlicloudEcsNetworkInterfaceAttachment(),
"alicloud_config_aggregator": resourceAlicloudConfigAggregator(),
"alicloud_config_aggregate_config_rule": resourceAlicloudConfigAggregateConfigRule(),
"alicloud_config_aggregate_compliance_pack": resourceAlicloudConfigAggregateCompliancePack(),
"alicloud_config_compliance_pack": resourceAlicloudConfigCompliancePack(),
"alicloud_direct_mail_receivers": resourceAlicloudDirectMailReceivers(),
"alicloud_eip_address": resourceAlicloudEipAddress(),
"alicloud_event_bridge_event_bus": resourceAlicloudEventBridgeEventBus(),
"alicloud_amqp_virtual_host": resourceAlicloudAmqpVirtualHost(),
"alicloud_amqp_queue": resourceAlicloudAmqpQueue(),
"alicloud_amqp_exchange": resourceAlicloudAmqpExchange(),
"alicloud_cassandra_backup_plan": resourceAlicloudCassandraBackupPlan(),
"alicloud_cen_transit_router_peer_attachment": resourceAlicloudCenTransitRouterPeerAttachment(),
"alicloud_amqp_instance": resourceAlicloudAmqpInstance(),
"alicloud_hbr_vault": resourceAlicloudHbrVault(),
"alicloud_ssl_certificates_service_certificate": resourceAlicloudSslCertificatesServiceCertificate(),
"alicloud_arms_alert_contact": resourceAlicloudArmsAlertContact(),
"alicloud_event_bridge_slr": resourceAlicloudEventBridgeServiceLinkedRole(),
"alicloud_event_bridge_rule": resourceAlicloudEventBridgeRule(),
"alicloud_cloud_firewall_control_policy": resourceAlicloudCloudFirewallControlPolicy(),
"alicloud_sae_namespace": resourceAlicloudSaeNamespace(),
"alicloud_sae_config_map": resourceAlicloudSaeConfigMap(),
"alicloud_alb_security_policy": resourceAlicloudAlbSecurityPolicy(),
"alicloud_kvstore_audit_log_config": resourceAlicloudKvstoreAuditLogConfig(),
"alicloud_event_bridge_event_source": resourceAlicloudEventBridgeEventSource(),
"alicloud_cloud_firewall_control_policy_order": resourceAlicloudCloudFirewallControlPolicyOrder(),
"alicloud_ecd_policy_group": resourceAlicloudEcdPolicyGroup(),
"alicloud_ecp_key_pair": resourceAlicloudEcpKeyPair(),
"alicloud_hbr_ecs_backup_plan": resourceAlicloudHbrEcsBackupPlan(),
"alicloud_hbr_nas_backup_plan": resourceAlicloudHbrNasBackupPlan(),
"alicloud_hbr_oss_backup_plan": resourceAlicloudHbrOssBackupPlan(),
"alicloud_scdn_domain": resourceAlicloudScdnDomain(),
"alicloud_alb_server_group": resourceAlicloudAlbServerGroup(),
"alicloud_data_works_folder": resourceAlicloudDataWorksFolder(),
"alicloud_arms_alert_contact_group": resourceAlicloudArmsAlertContactGroup(),
"alicloud_dcdn_domain_config": resourceAlicloudDcdnDomainConfig(),
"alicloud_scdn_domain_config": resourceAlicloudScdnDomainConfig(),
"alicloud_cloud_storage_gateway_gateway": resourceAlicloudCloudStorageGatewayGateway(),
"alicloud_lindorm_instance": resourceAlicloudLindormInstance(),
"alicloud_cddc_dedicated_host_group": resourceAlicloudCddcDedicatedHostGroup(),
"alicloud_hbr_ecs_backup_client": resourceAlicloudHbrEcsBackupClient(),
"alicloud_msc_sub_contact": resourceAlicloudMscSubContact(),
"alicloud_express_connect_physical_connection": resourceAlicloudExpressConnectPhysicalConnection(),
"alicloud_alb_load_balancer": resourceAlicloudAlbLoadBalancer(),
"alicloud_sddp_rule": resourceAlicloudSddpRule(),
"alicloud_bastionhost_user_group": resourceAlicloudBastionhostUserGroup(),
"alicloud_security_center_group": resourceAlicloudSecurityCenterGroup(),
"alicloud_alb_acl": resourceAlicloudAlbAcl(),
"alicloud_bastionhost_user": resourceAlicloudBastionhostUser(),
"alicloud_dfs_access_group": resourceAlicloudDfsAccessGroup(),
"alicloud_ehpc_job_template": resourceAlicloudEhpcJobTemplate(),
"alicloud_sddp_config": resourceAlicloudSddpConfig(),
"alicloud_hbr_restore_job": resourceAlicloudHbrRestoreJob(),
"alicloud_alb_listener": resourceAlicloudAlbListener(),
"alicloud_ens_key_pair": resourceAlicloudEnsKeyPair(),
"alicloud_sae_application": resourceAlicloudSaeApplication(),
"alicloud_alb_rule": resourceAlicloudAlbRule(),
"alicloud_cms_metric_rule_template": resourceAlicloudCmsMetricRuleTemplate(),
"alicloud_iot_device_group": resourceAlicloudIotDeviceGroup(),
"alicloud_express_connect_virtual_border_router": resourceAlicloudExpressConnectVirtualBorderRouter(),
"alicloud_imm_project": resourceAlicloudImmProject(),
"alicloud_click_house_db_cluster": resourceAlicloudClickHouseDbCluster(),
"alicloud_direct_mail_domain": resourceAlicloudDirectMailDomain(),
"alicloud_bastionhost_host_group": resourceAlicloudBastionhostHostGroup(),
"alicloud_vpc_dhcp_options_set": resourceAlicloudVpcDhcpOptionsSet(),
"alicloud_alb_health_check_template": resourceAlicloudAlbHealthCheckTemplate(),
"alicloud_cdn_real_time_log_delivery": resourceAlicloudCdnRealTimeLogDelivery(),
"alicloud_click_house_account": resourceAlicloudClickHouseAccount(),
"alicloud_bastionhost_user_attachment": resourceAlicloudBastionhostUserAttachment(),
"alicloud_direct_mail_mail_address": resourceAlicloudDirectMailMailAddress(),
"alicloud_dts_job_monitor_rule": resourceAlicloudDtsJobMonitorRule(),
"alicloud_database_gateway_gateway": resourceAlicloudDatabaseGatewayGateway(),
"alicloud_bastionhost_host": resourceAlicloudBastionhostHost(),
"alicloud_amqp_binding": resourceAlicloudAmqpBinding(),
"alicloud_slb_tls_cipher_policy": resourceAlicloudSlbTlsCipherPolicy(),
"alicloud_cloud_sso_directory": resourceAlicloudCloudSsoDirectory(),
"alicloud_bastionhost_host_account": resourceAlicloudBastionhostHostAccount(),
"alicloud_bastionhost_host_attachment": resourceAlicloudBastionhostHostAttachment(),
"alicloud_bastionhost_host_account_user_group_attachment": resourceAlicloudBastionhostHostAccountUserGroupAttachment(),
"alicloud_bastionhost_host_account_user_attachment": resourceAlicloudBastionhostHostAccountUserAttachment(),
"alicloud_bastionhost_host_group_account_user_attachment": resourceAlicloudBastionhostHostGroupAccountUserAttachment(),
"alicloud_bastionhost_host_group_account_user_group_attachment": resourceAlicloudBastionhostHostGroupAccountUserGroupAttachment(),
"alicloud_waf_certificate": resourceAlicloudWafCertificate(),
"alicloud_simple_application_server_instance": resourceAlicloudSimpleApplicationServerInstance(),
"alicloud_video_surveillance_system_group": resourceAlicloudVideoSurveillanceSystemGroup(),
"alicloud_msc_sub_subscription": resourceAlicloudMscSubSubscription(),
"alicloud_sddp_instance": resourceAlicloudSddpInstance(),
"alicloud_vpc_nat_ip_cidr": resourceAlicloudVpcNatIpCidr(),
"alicloud_vpc_nat_ip": resourceAlicloudVpcNatIp(),
"alicloud_quick_bi_user": resourceAlicloudQuickBiUser(),
"alicloud_vod_domain": resourceAlicloudVodDomain(),
"alicloud_arms_dispatch_rule": resourceAlicloudArmsDispatchRule(),
"alicloud_open_search_app_group": resourceAlicloudOpenSearchAppGroup(),
"alicloud_graph_database_db_instance": resourceAlicloudGraphDatabaseDbInstance(),
"alicloud_arms_prometheus_alert_rule": resourceAlicloudArmsPrometheusAlertRule(),
"alicloud_dbfs_instance": resourceAlicloudDbfsInstance(),
"alicloud_rdc_organization": resourceAlicloudRdcOrganization(),
"alicloud_eais_instance": resourceAlicloudEaisInstance(),
"alicloud_sae_ingress": resourceAlicloudSaeIngress(),
"alicloud_cloudauth_face_config": resourceAlicloudCloudauthFaceConfig(),
"alicloud_imp_app_template": resourceAlicloudImpAppTemplate(),
"alicloud_pvtz_user_vpc_authorization": resourceAlicloudPvtzUserVpcAuthorization(),
"alicloud_mhub_product": resourceAlicloudMhubProduct(),
"alicloud_cloud_sso_scim_server_credential": resourceAlicloudCloudSsoScimServerCredential(),
"alicloud_dts_subscription_job": resourceAlicloudDtsSubscriptionJob(),
"alicloud_service_mesh_service_mesh": resourceAlicloudServiceMeshServiceMesh(),
"alicloud_mhub_app": resourceAlicloudMhubApp(),
"alicloud_cloud_sso_group": resourceAlicloudCloudSsoGroup(),
"alicloud_dts_synchronization_instance": resourceAlicloudDtsSynchronizationInstance(),
"alicloud_dts_synchronization_job": resourceAlicloudDtsSynchronizationJob(),
"alicloud_cloud_firewall_instance": resourceAlicloudCloudFirewallInstance(),
"alicloud_cr_endpoint_acl_policy": resourceAlicloudCrEndpointAclPolicy(),
"alicloud_actiontrail_history_delivery_job": resourceAlicloudActiontrailHistoryDeliveryJob(),
"alicloud_ecs_deployment_set": resourceAlicloudEcsDeploymentSet(),
"alicloud_cloud_sso_user": resourceAlicloudCloudSsoUser(),
"alicloud_cloud_sso_access_configuration": resourceAlicloudCloudSsoAccessConfiguration(),
"alicloud_dfs_file_system": resourceAlicloudDfsFileSystem(),
"alicloud_vpc_traffic_mirror_filter": resourceAlicloudVpcTrafficMirrorFilter(),
"alicloud_dfs_access_rule": resourceAlicloudDfsAccessRule(),
"alicloud_vpc_traffic_mirror_filter_egress_rule": resourceAlicloudVpcTrafficMirrorFilterEgressRule(),
"alicloud_dfs_mount_point": resourceAlicloudDfsMountPoint(),
"alicloud_ecd_simple_office_site": resourceAlicloudEcdSimpleOfficeSite(),
"alicloud_vpc_traffic_mirror_filter_ingress_rule": resourceAlicloudVpcTrafficMirrorFilterIngressRule(),
"alicloud_ecd_nas_file_system": resourceAlicloudEcdNasFileSystem(),
"alicloud_cloud_sso_user_attachment": resourceAlicloudCloudSsoUserAttachment(),
"alicloud_cloud_sso_access_assignment": resourceAlicloudCloudSsoAccessAssignment(),
"alicloud_msc_sub_webhook": resourceAlicloudMscSubWebhook(),
"alicloud_waf_protection_module": resourceAlicloudWafProtectionModule(),
"alicloud_ecd_user": resourceAlicloudEcdUser(),
"alicloud_vpc_traffic_mirror_session": resourceAlicloudVpcTrafficMirrorSession(),
"alicloud_gpdb_account": resourceAlicloudGpdbAccount(),
"alicloud_security_center_service_linked_role": resourceAlicloudSecurityCenterServiceLinkedRole(),
"alicloud_event_bridge_service_linked_role": resourceAlicloudEventBridgeServiceLinkedRole(),
"alicloud_vpc_ipv6_gateway": resourceAlicloudVpcIpv6Gateway(),
"alicloud_vpc_ipv6_egress_rule": resourceAlicloudVpcIpv6EgressRule(),
"alicloud_hbr_server_backup_plan": resourceAlicloudHbrServerBackupPlan(),
"alicloud_cms_dynamic_tag_group": resourceAlicloudCmsDynamicTagGroup(),
"alicloud_ecd_network_package": resourceAlicloudEcdNetworkPackage(),
"alicloud_cloud_storage_gateway_gateway_smb_user": resourceAlicloudCloudStorageGatewayGatewaySmbUser(),
"alicloud_vpc_ipv6_internet_bandwidth": resourceAlicloudVpcIpv6InternetBandwidth(),
"alicloud_simple_application_server_firewall_rule": resourceAlicloudSimpleApplicationServerFirewallRule(),
"alicloud_pvtz_endpoint": resourceAlicloudPvtzEndpoint(),
"alicloud_pvtz_rule": resourceAlicloudPvtzRule(),
"alicloud_pvtz_rule_attachment": resourceAlicloudPvtzRuleAttachment(),
"alicloud_simple_application_server_snapshot": resourceAlicloudSimpleApplicationServerSnapshot(),
"alicloud_simple_application_server_custom_image": resourceAlicloudSimpleApplicationServerCustomImage(),
"alicloud_cloud_storage_gateway_gateway_cache_disk": resourceAlicloudCloudStorageGatewayGatewayCacheDisk(),
"alicloud_cloud_storage_gateway_gateway_logging": resourceAlicloudCloudStorageGatewayGatewayLogging(),
"alicloud_cloud_storage_gateway_gateway_block_volume": resourceAlicloudCloudStorageGatewayGatewayBlockVolume(),
"alicloud_direct_mail_tag": resourceAlicloudDirectMailTag(),
"alicloud_cloud_storage_gateway_gateway_file_share": resourceAlicloudCloudStorageGatewayGatewayFileShare(),
"alicloud_ecd_desktop": resourceAlicloudEcdDesktop(),
"alicloud_cloud_storage_gateway_express_sync": resourceAlicloudCloudStorageGatewayExpressSync(),
"alicloud_cloud_storage_gateway_express_sync_share_attachment": resourceAlicloudCloudStorageGatewayExpressSyncShareAttachment(),
"alicloud_oos_application": resourceAlicloudOosApplication(),
"alicloud_eci_virtual_node": resourceAlicloudEciVirtualNode(),
"alicloud_ros_stack_instance": resourceAlicloudRosStackInstance(),
"alicloud_ecs_dedicated_host_cluster": resourceAlicloudEcsDedicatedHostCluster(),
"alicloud_oos_application_group": resourceAlicloudOosApplicationGroup(),
"alicloud_dts_consumer_channel": resourceAlicloudDtsConsumerChannel(),
"alicloud_ecd_image": resourceAlicloudEcdImage(),
"alicloud_oos_patch_baseline": resourceAlicloudOosPatchBaseline(),
"alicloud_ecd_command": resourceAlicloudEcdCommand(),
"alicloud_cddc_dedicated_host": resourceAlicloudCddcDedicatedHost(),
"alicloud_oos_service_setting": resourceAlicloudOosServiceSetting(),
"alicloud_oos_parameter": resourceAlicloudOosParameter(),
"alicloud_oos_state_configuration": resourceAlicloudOosStateConfiguration(),
"alicloud_oos_secret_parameter": resourceAlicloudOosSecretParameter(),
"alicloud_click_house_backup_policy": resourceAlicloudClickHouseBackupPolicy(),
"alicloud_mongodb_audit_policy": resourceAlicloudMongodbAuditPolicy(),
"alicloud_cloud_sso_access_configuration_provisioning": resourceAlicloudCloudSsoAccessConfigurationProvisioning(),
"alicloud_mongodb_account": resourceAlicloudMongodbAccount(),
"alicloud_mongodb_serverless_instance": resourceAlicloudMongodbServerlessInstance(),
"alicloud_ecs_session_manager_status": resourceAlicloudEcsSessionManagerStatus(),
"alicloud_cddc_dedicated_host_account": resourceAlicloudCddcDedicatedHostAccount(),
"alicloud_cr_chart_namespace": resourceAlicloudCrChartNamespace(),
"alicloud_fnf_execution": resourceAlicloudFnFExecution(),
"alicloud_cr_chart_repository": resourceAlicloudCrChartRepository(),
"alicloud_mongodb_sharding_network_public_address": resourceAlicloudMongodbShardingNetworkPublicAddress(),
"alicloud_ga_acl": resourceAlicloudGaAcl(),
"alicloud_ga_acl_attachment": resourceAlicloudGaAclAttachment(),
"alicloud_ga_additional_certificate": resourceAlicloudGaAdditionalCertificate(),
"alicloud_alidns_custom_line": resourceAlicloudAlidnsCustomLine(),
"alicloud_vpc_vbr_ha": resourceAlicloudVpcVbrHa(),
"alicloud_ros_template_scratch": resourceAlicloudRosTemplateScratch(),
"alicloud_alidns_gtm_instance": resourceAlicloudAlidnsGtmInstance(),
"alicloud_vpc_bgp_group": resourceAlicloudVpcBgpGroup(),
"alicloud_ram_security_preference": resourceAlicloudRamSecurityPreference(),
"alicloud_nas_snapshot": resourceAlicloudNasSnapshot(),
"alicloud_hbr_replication_vault": resourceAlicloudHbrReplicationVault(),
"alicloud_alidns_address_pool": resourceAlicloudAlidnsAddressPool(),
"alicloud_ecs_prefix_list": resourceAlicloudEcsPrefixList(),
"alicloud_alidns_access_strategy": resourceAlicloudAlidnsAccessStrategy(),
"alicloud_alidns_monitor_config": resourceAlicloudAlidnsMonitorConfig(),
"alicloud_vpc_dhcp_options_set_attachment": resourceAlicloudVpcDhcpOptionsSetAttachement(),
"alicloud_vpc_bgp_peer": resourceAlicloudVpcBgpPeer(),
"alicloud_nas_fileset": resourceAlicloudNasFileset(),
"alicloud_nas_auto_snapshot_policy": resourceAlicloudNasAutoSnapshotPolicy(),
"alicloud_nas_lifecycle_policy": resourceAlicloudNasLifecyclePolicy(),
"alicloud_vpc_bgp_network": resourceAlicloudVpcBgpNetwork(),
"alicloud_nas_data_flow": resourceAlicloudNasDataFlow(),
},
ConfigureFunc: providerConfigure,
}
}
var providerConfig map[string]interface{}
func providerConfigure(d *schema.ResourceData) (interface{}, error) {
var getProviderConfig = func(str string, key string) string {
if str == "" {
value, err := getConfigFromProfile(d, key)
if err == nil && value != nil {
str = value.(string)
}
}
return str
}
accessKey := getProviderConfig(d.Get("access_key").(string), "access_key_id")
secretKey := getProviderConfig(d.Get("secret_key").(string), "access_key_secret")
region := getProviderConfig(d.Get("region").(string), "region_id")
if region == "" {
region = DEFAULT_REGION
}
securityToken := getProviderConfig(d.Get("security_token").(string), "sts_token")
ecsRoleName := getProviderConfig(d.Get("ecs_role_name").(string), "ram_role_name")
if accessKey == "" || secretKey == "" {
if v, ok := d.GetOk("credentials_uri"); ok && v.(string) != "" {
credentialsURIResp, err := getClientByCredentialsURI(v.(string))
if err != nil {
return nil, err
}
accessKey = credentialsURIResp.AccessKeyId
secretKey = credentialsURIResp.AccessKeySecret
securityToken = credentialsURIResp.SecurityToken
}
}
config := &connectivity.Config{
AccessKey: strings.TrimSpace(accessKey),
SecretKey: strings.TrimSpace(secretKey),
EcsRoleName: strings.TrimSpace(ecsRoleName),
Region: connectivity.Region(strings.TrimSpace(region)),
RegionId: strings.TrimSpace(region),
SkipRegionValidation: d.Get("skip_region_validation").(bool),
ConfigurationSource: d.Get("configuration_source").(string),
Protocol: d.Get("protocol").(string),
ClientReadTimeout: d.Get("client_read_timeout").(int),
ClientConnectTimeout: d.Get("client_connect_timeout").(int),
SourceIp: strings.TrimSpace(d.Get("source_ip").(string)),
SecureTransport: strings.TrimSpace(d.Get("secure_transport").(string)),
}
if v, ok := d.GetOk("security_transport"); config.SecureTransport == "" && ok && v.(string) != "" {
config.SecureTransport = v.(string)
}
config.SecurityToken = strings.TrimSpace(securityToken)
config.RamRoleArn = getProviderConfig("", "ram_role_arn")
config.RamRoleSessionName = getProviderConfig("", "ram_session_name")
expiredSeconds, err := getConfigFromProfile(d, "expired_seconds")
if err == nil && expiredSeconds != nil {
config.RamRoleSessionExpiration = (int)(expiredSeconds.(float64))
}
assumeRoleList := d.Get("assume_role").(*schema.Set).List()
if len(assumeRoleList) == 1 {
assumeRole := assumeRoleList[0].(map[string]interface{})
if assumeRole["role_arn"].(string) != "" {
config.RamRoleArn = assumeRole["role_arn"].(string)
}
if assumeRole["session_name"].(string) != "" {
config.RamRoleSessionName = assumeRole["session_name"].(string)
}
if config.RamRoleSessionName == "" {
config.RamRoleSessionName = "terraform"
}
config.RamRolePolicy = assumeRole["policy"].(string)
if assumeRole["session_expiration"].(int) == 0 {
if v := os.Getenv("ALICLOUD_ASSUME_ROLE_SESSION_EXPIRATION"); v != "" {
if expiredSeconds, err := strconv.Atoi(v); err == nil {
config.RamRoleSessionExpiration = expiredSeconds
}
}
if config.RamRoleSessionExpiration == 0 {
config.RamRoleSessionExpiration = 3600
}
} else {
config.RamRoleSessionExpiration = assumeRole["session_expiration"].(int)
}
log.Printf("[INFO] assume_role configuration set: (RamRoleArn: %q, RamRoleSessionName: %q, RamRolePolicy: %q, RamRoleSessionExpiration: %d)",
config.RamRoleArn, config.RamRoleSessionName, config.RamRolePolicy, config.RamRoleSessionExpiration)
}
if err := config.MakeConfigByEcsRoleName(); err != nil {
return nil, err
}
endpointsSet := d.Get("endpoints").(*schema.Set)
endpointInit := make(map[string]interface{})
config.Endpoints = endpointInit
for _, endpointsSetI := range endpointsSet.List() {
endpoints := endpointsSetI.(map[string]interface{})
config.Endpoints = endpoints
config.EcsEndpoint = strings.TrimSpace(endpoints["ecs"].(string))
config.RdsEndpoint = strings.TrimSpace(endpoints["rds"].(string))
config.SlbEndpoint = strings.TrimSpace(endpoints["slb"].(string))
config.VpcEndpoint = strings.TrimSpace(endpoints["vpc"].(string))
config.EssEndpoint = strings.TrimSpace(endpoints["ess"].(string))
config.OssEndpoint = strings.TrimSpace(endpoints["oss"].(string))
config.OnsEndpoint = strings.TrimSpace(endpoints["ons"].(string))
config.AlikafkaEndpoint = strings.TrimSpace(endpoints["alikafka"].(string))
config.DnsEndpoint = strings.TrimSpace(endpoints["dns"].(string))
config.RamEndpoint = strings.TrimSpace(endpoints["ram"].(string))
config.CsEndpoint = strings.TrimSpace(endpoints["cs"].(string))
config.CrEndpoint = strings.TrimSpace(endpoints["cr"].(string))
config.CdnEndpoint = strings.TrimSpace(endpoints["cdn"].(string))
config.KmsEndpoint = strings.TrimSpace(endpoints["kms"].(string))
config.OtsEndpoint = strings.TrimSpace(endpoints["ots"].(string))
config.CmsEndpoint = strings.TrimSpace(endpoints["cms"].(string))
config.PvtzEndpoint = strings.TrimSpace(endpoints["pvtz"].(string))
config.StsEndpoint = strings.TrimSpace(endpoints["sts"].(string))
config.LogEndpoint = strings.TrimSpace(endpoints["log"].(string))
config.DrdsEndpoint = strings.TrimSpace(endpoints["drds"].(string))
config.DdsEndpoint = strings.TrimSpace(endpoints["dds"].(string))
config.GpdbEnpoint = strings.TrimSpace(endpoints["gpdb"].(string))
config.KVStoreEndpoint = strings.TrimSpace(endpoints["kvstore"].(string))
config.PolarDBEndpoint = strings.TrimSpace(endpoints["polardb"].(string))
config.FcEndpoint = strings.TrimSpace(endpoints["fc"].(string))
config.ApigatewayEndpoint = strings.TrimSpace(endpoints["apigateway"].(string))
config.DatahubEndpoint = strings.TrimSpace(endpoints["datahub"].(string))
config.MnsEndpoint = strings.TrimSpace(endpoints["mns"].(string))
config.LocationEndpoint = strings.TrimSpace(endpoints["location"].(string))
config.ElasticsearchEndpoint = strings.TrimSpace(endpoints["elasticsearch"].(string))
config.NasEndpoint = strings.TrimSpace(endpoints["nas"].(string))
config.ActiontrailEndpoint = strings.TrimSpace(endpoints["actiontrail"].(string))
config.BssOpenApiEndpoint = strings.TrimSpace(endpoints["bssopenapi"].(string))
config.DdoscooEndpoint = strings.TrimSpace(endpoints["ddoscoo"].(string))
config.DdosbgpEndpoint = strings.TrimSpace(endpoints["ddosbgp"].(string))
config.EmrEndpoint = strings.TrimSpace(endpoints["emr"].(string))
config.CasEndpoint = strings.TrimSpace(endpoints["cas"].(string))
config.MarketEndpoint = strings.TrimSpace(endpoints["market"].(string))
config.AdbEndpoint = strings.TrimSpace(endpoints["adb"].(string))
config.CbnEndpoint = strings.TrimSpace(endpoints["cbn"].(string))
config.MaxComputeEndpoint = strings.TrimSpace(endpoints["maxcompute"].(string))
config.DmsEnterpriseEndpoint = strings.TrimSpace(endpoints["dms_enterprise"].(string))
config.WafOpenapiEndpoint = strings.TrimSpace(endpoints["waf_openapi"].(string))
config.ResourcemanagerEndpoint = strings.TrimSpace(endpoints["resourcemanager"].(string))
config.EciEndpoint = strings.TrimSpace(endpoints["eci"].(string))
config.OosEndpoint = strings.TrimSpace(endpoints["oos"].(string))
config.DcdnEndpoint = strings.TrimSpace(endpoints["dcdn"].(string))
config.MseEndpoint = strings.TrimSpace(endpoints["mse"].(string))
config.ConfigEndpoint = strings.TrimSpace(endpoints["config"].(string))
config.RKvstoreEndpoint = strings.TrimSpace(endpoints["r_kvstore"].(string))
config.FnfEndpoint = strings.TrimSpace(endpoints["fnf"].(string))
config.RosEndpoint = strings.TrimSpace(endpoints["ros"].(string))
config.PrivatelinkEndpoint = strings.TrimSpace(endpoints["privatelink"].(string))
config.ResourcesharingEndpoint = strings.TrimSpace(endpoints["resourcesharing"].(string))
config.GaEndpoint = strings.TrimSpace(endpoints["ga"].(string))
config.HitsdbEndpoint = strings.TrimSpace(endpoints["hitsdb"].(string))
config.BrainIndustrialEndpoint = strings.TrimSpace(endpoints["brain_industrial"].(string))
config.EipanycastEndpoint = strings.TrimSpace(endpoints["eipanycast"].(string))
config.ImsEndpoint = strings.TrimSpace(endpoints["ims"].(string))
config.QuotasEndpoint = strings.TrimSpace(endpoints["quotas"].(string))
config.SgwEndpoint = strings.TrimSpace(endpoints["sgw"].(string))
config.DmEndpoint = strings.TrimSpace(endpoints["dm"].(string))
config.EventbridgeEndpoint = strings.TrimSpace(endpoints["eventbridge"].(string))
config.OnsproxyEndpoint = strings.TrimSpace(endpoints["onsproxy"].(string))
config.CdsEndpoint = strings.TrimSpace(endpoints["cds"].(string))
config.HbrEndpoint = strings.TrimSpace(endpoints["hbr"].(string))
config.ArmsEndpoint = strings.TrimSpace(endpoints["arms"].(string))
config.ServerlessEndpoint = strings.TrimSpace(endpoints["serverless"].(string))
config.AlbEndpoint = strings.TrimSpace(endpoints["alb"].(string))
config.RedisaEndpoint = strings.TrimSpace(endpoints["redisa"].(string))
config.GwsecdEndpoint = strings.TrimSpace(endpoints["gwsecd"].(string))
config.CloudphoneEndpoint = strings.TrimSpace(endpoints["cloudphone"].(string))
config.ScdnEndpoint = strings.TrimSpace(endpoints["scdn"].(string))
config.DataworkspublicEndpoint = strings.TrimSpace(endpoints["dataworkspublic"].(string))
config.HcsSgwEndpoint = strings.TrimSpace(endpoints["hcs_sgw"].(string))
config.CddcEndpoint = strings.TrimSpace(endpoints["cddc"].(string))
config.MscopensubscriptionEndpoint = strings.TrimSpace(endpoints["mscopensubscription"].(string))
config.SddpEndpoint = strings.TrimSpace(endpoints["sddp"].(string))
config.BastionhostEndpoint = strings.TrimSpace(endpoints["bastionhost"].(string))
config.SasEndpoint = strings.TrimSpace(endpoints["sas"].(string))
config.AlidfsEndpoint = strings.TrimSpace(endpoints["alidfs"].(string))
config.EhpcEndpoint = strings.TrimSpace(endpoints["ehpc"].(string))
config.EnsEndpoint = strings.TrimSpace(endpoints["ens"].(string))
config.IotEndpoint = strings.TrimSpace(endpoints["iot"].(string))
config.ImmEndpoint = strings.TrimSpace(endpoints["imm"].(string))
config.ClickhouseEndpoint = strings.TrimSpace(endpoints["clickhouse"].(string))
config.DtsEndpoint = strings.TrimSpace(endpoints["dts"].(string))
config.DgEndpoint = strings.TrimSpace(endpoints["dg"].(string))
config.CloudssoEndpoint = strings.TrimSpace(endpoints["cloudsso"].(string))
config.WafEndpoint = strings.TrimSpace(endpoints["waf"].(string))
config.SwasEndpoint = strings.TrimSpace(endpoints["swas"].(string))
config.VsEndpoint = strings.TrimSpace(endpoints["vs"].(string))
config.QuickbiEndpoint = strings.TrimSpace(endpoints["quickbi"].(string))
config.VodEndpoint = strings.TrimSpace(endpoints["vod"].(string))
config.OpensearchEndpoint = strings.TrimSpace(endpoints["opensearch"].(string))
config.GdsEndpoint = strings.TrimSpace(endpoints["gds"].(string))
config.DbfsEndpoint = strings.TrimSpace(endpoints["dbfs"].(string))
config.DevopsrdcEndpoint = strings.TrimSpace(endpoints["devopsrdc"].(string))
config.EaisEndpoint = strings.TrimSpace(endpoints["eais"].(string))
config.CloudauthEndpoint = strings.TrimSpace(endpoints["cloudauth"].(string))
config.ImpEndpoint = strings.TrimSpace(endpoints["imp"].(string))
config.MhubEndpoint = strings.TrimSpace(endpoints["mhub"].(string))
config.ServicemeshEndpoint = strings.TrimSpace(endpoints["servicemesh"].(string))
config.AcrEndpoint = strings.TrimSpace(endpoints["acr"].(string))
config.EdsuserEndpoint = strings.TrimSpace(endpoints["edsuser"].(string))
config.GaplusEndpoint = strings.TrimSpace(endpoints["gaplus"].(string))
if endpoint, ok := endpoints["alidns"]; ok {
config.AlidnsEndpoint = strings.TrimSpace(endpoint.(string))
} else {
config.AlidnsEndpoint = strings.TrimSpace(endpoints["dns"].(string))
}
config.CassandraEndpoint = strings.TrimSpace(endpoints["cassandra"].(string))
}
if config.RamRoleArn != "" {
config.AccessKey, config.SecretKey, config.SecurityToken, err = getAssumeRoleAK(config.AccessKey, config.SecretKey, config.SecurityToken, region, config.RamRoleArn, config.RamRoleSessionName, config.RamRolePolicy, config.RamRoleSessionExpiration, config.StsEndpoint)
if err != nil {
return nil, err
}
}
if ots_instance_name, ok := d.GetOk("ots_instance_name"); ok && ots_instance_name.(string) != "" {
config.OtsInstanceName = strings.TrimSpace(ots_instance_name.(string))
}
if logEndpoint, ok := d.GetOk("log_endpoint"); ok && logEndpoint.(string) != "" {
config.LogEndpoint = strings.TrimSpace(logEndpoint.(string))
}
if mnsEndpoint, ok := d.GetOk("mns_endpoint"); ok && mnsEndpoint.(string) != "" {
config.MnsEndpoint = strings.TrimSpace(mnsEndpoint.(string))
}
if account, ok := d.GetOk("account_id"); ok && account.(string) != "" {
config.AccountId = strings.TrimSpace(account.(string))
}
if fcEndpoint, ok := d.GetOk("fc"); ok && fcEndpoint.(string) != "" {
config.FcEndpoint = strings.TrimSpace(fcEndpoint.(string))
}
if config.ConfigurationSource == "" {
sourceAccessKey := config.AccessKey
if len(sourceAccessKey) > 25 {
sourceAccessKey = sourceAccessKey[:25]
}
sourceName := fmt.Sprintf("Default/%s:%s", sourceAccessKey, strings.Trim(uuid.New().String(), "-"))
if len(sourceName) > 64 {
sourceName = sourceName[:64]
}
config.ConfigurationSource = sourceName
}
client, err := config.Client()
if err != nil {
return nil, err
}
return client, nil
}
// This is a global MutexKV for use within this plugin.
var alicloudMutexKV = mutexkv.NewMutexKV()
var descriptions map[string]string
func init() {
descriptions = map[string]string{
"access_key": "The access key for API operations. You can retrieve this from the 'Security Management' section of the Alibaba Cloud console.",
"secret_key": "The secret key for API operations. You can retrieve this from the 'Security Management' section of the Alibaba Cloud console.",
"ecs_role_name": "The RAM Role Name attached on a ECS instance for API operations. You can retrieve this from the 'Access Control' section of the Alibaba Cloud console.",
"region": "The region where Alibaba Cloud operations will take place. Examples are cn-beijing, cn-hangzhou, eu-central-1, etc.",
"security_token": "security token. A security token is only required if you are using Security Token Service.",
"account_id": "The account ID for some service API operations. You can retrieve this from the 'Security Settings' section of the Alibaba Cloud console.",
"profile": "The profile for API operations. If not set, the default profile created with `aliyun configure` will be used.",
"shared_credentials_file": "The path to the shared credentials file. If not set this defaults to ~/.aliyun/config.json",
"assume_role_role_arn": "The ARN of a RAM role to assume prior to making API calls.",
"assume_role_session_name": "The session name to use when assuming the role. If omitted, `terraform` is passed to the AssumeRole call as session name.",
"assume_role_policy": "The permissions applied when assuming a role. You cannot use, this policy to grant further permissions that are in excess to those of the, role that is being assumed.",
"assume_role_session_expiration": "The time after which the established session for assuming role expires. Valid value range: [900-3600] seconds. Default to 0 (in this case Alicloud use own default value).",
"skip_region_validation": "Skip static validation of region ID. Used by users of alternative AlibabaCloud-like APIs or users w/ access to regions that are not public (yet).",
"configuration_source": "Use this to mark a terraform configuration file source.",
"client_read_timeout": "The maximum timeout of the client read request.",
"client_connect_timeout": "The maximum timeout of the client connection server.",
"source_ip": "The source ip for the assume role invoking.",
"secure_transport": "The security transport for the assume role invoking.",
"credentials_uri": "The URI of sidecar credentials service.",
"ecs_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom ECS endpoints.",
"rds_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom RDS endpoints.",
"slb_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom SLB endpoints.",
"vpc_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom VPC and VPN endpoints.",
"ess_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom Autoscaling endpoints.",
"oss_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom OSS endpoints.",
"ons_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom ONS endpoints.",
"alikafka_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom ALIKAFKA endpoints.",
"dns_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom DNS endpoints.",
"ram_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom RAM endpoints.",
"cs_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom Container Service endpoints.",
"cr_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom Container Registry endpoints.",
"cdn_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom CDN endpoints.",
"kms_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom KMS endpoints.",
"ots_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom Table Store endpoints.",
"cms_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom Cloud Monitor endpoints.",
"pvtz_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom Private Zone endpoints.",
"sts_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom STS endpoints.",
"log_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom Log Service endpoints.",
"drds_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom DRDS endpoints.",
"dds_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom MongoDB endpoints.",
"polardb_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom PolarDB endpoints.",
"gpdb_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom GPDB endpoints.",
"kvstore_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom R-KVStore endpoints.",
"fc_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom Function Computing endpoints.",
"apigateway_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom Api Gateway endpoints.",
"datahub_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom Datahub endpoints.",
"mns_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom MNS endpoints.",
"location_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom Location Service endpoints.",
"elasticsearch_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom Elasticsearch endpoints.",
"nas_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom NAS endpoints.",
"actiontrail_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom Actiontrail endpoints.",
"cas_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom CAS endpoints.",
"bssopenapi_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom BSSOPENAPI endpoints.",
"ddoscoo_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom DDOSCOO endpoints.",
"ddosbgp_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom DDOSBGP endpoints.",
"emr_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom EMR endpoints.",
"market_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom Market Place endpoints.",
"hbase_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom HBase endpoints.",
"adb_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom AnalyticDB endpoints.",
"cbn_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom cbn endpoints.",
"maxcompute_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom MaxCompute endpoints.",
"dms_enterprise_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom dms_enterprise endpoints.",
"waf_openapi_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom waf_openapi endpoints.",
"resourcemanager_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom resourcemanager endpoints.",
"alidns_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom alidns endpoints.",
"cassandra_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom cassandra endpoints.",
"eci_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom eci endpoints.",
"oos_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom oos endpoints.",
"dcdn_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom dcdn endpoints.",
"mse_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom mse endpoints.",
"config_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom config endpoints.",
"r_kvstore_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom r_kvstore endpoints.",
"fnf_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom fnf endpoints.",
"ros_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom ros endpoints.",
"privatelink_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom privatelink endpoints.",
"resourcesharing_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom resourcesharing endpoints.",
"ga_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom ga endpoints.",
"hitsdb_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom hitsdb endpoints.",
"brain_industrial_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom brain_industrial endpoints.",
"eipanycast_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom eipanycast endpoints.",
"ims_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom ims endpoints.",
"quotas_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom quotas endpoints.",
"sgw_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom sgw endpoints.",
"dm_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom dm endpoints.",
"eventbridge_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom eventbridge_share endpoints.",
"onsproxy_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom onsproxy endpoints.",
"cds_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom cds endpoints.",
"hbr_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom hbr endpoints.",
"arms_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom arms endpoints.",
"serverless_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom serverless endpoints.",
"alb_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom alb endpoints.",
"redisa_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom redisa endpoints.",
"gwsecd_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom gwsecd endpoints.",
"cloudphone_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom cloudphone endpoints.",
"scdn_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom scdn endpoints.",
"dataworkspublic_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom dataworkspublic endpoints.",
"hcs_sgw_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom hcs_sgw endpoints.",
"cddc_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom cddc endpoints.",
"mscopensubscription_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom mscopensubscription endpoints.",
"sddp_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom sddp endpoints.",
"bastionhost_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom bastionhost endpoints.",
"sas_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom sas endpoints.",
"alidfs_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom alidfs endpoints.",
"ehpc_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom ehpc endpoints.",
"ens_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom ens endpoints.",
"iot_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom iot endpoints.",
"imm_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom imm endpoints.",
"clickhouse_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom clickhouse endpoints.",
"dts_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom dts endpoints.",
"dg_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom dg endpoints.",
"cloudsso_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom cloudsso endpoints.",
"waf_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom waf endpoints.",
"swas_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom swas endpoints.",
"vs_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom vs endpoints.",
"quickbi_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom quickbi endpoints.",
"vod_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom vod endpoints.",
"opensearch_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom opensearch endpoints.",
"gds_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom gds endpoints.",
"dbfs_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom dbfs endpoints.",
"devopsrdc_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom devopsrdc endpoints.",
"eais_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom eais endpoints.",
"cloudauth_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom cloudauth endpoints.",
"imp_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom imp endpoints.",
"mhub_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom mhub endpoints.",
"servicemesh_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom servicemesh endpoints.",
"acr_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom acr endpoints.",
"edsuser_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom edsuser endpoints.",
"gaplus_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom gaplus endpoints.",
}
}
func assumeRoleSchema() *schema.Schema {
return &schema.Schema{
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"role_arn": {
Type: schema.TypeString,
Required: true,
Description: descriptions["assume_role_role_arn"],
DefaultFunc: schema.EnvDefaultFunc("ALICLOUD_ASSUME_ROLE_ARN", ""),
},
"session_name": {
Type: schema.TypeString,
Optional: true,
Description: descriptions["assume_role_session_name"],
DefaultFunc: schema.EnvDefaultFunc("ALICLOUD_ASSUME_ROLE_SESSION_NAME", ""),
},
"policy": {
Type: schema.TypeString,
Optional: true,
Description: descriptions["assume_role_policy"],
},
"session_expiration": {
Type: schema.TypeInt,
Optional: true,
Description: descriptions["assume_role_session_expiration"],
ValidateFunc: intBetween(900, 3600),
},
},
},
}
}
func endpointsSchema() *schema.Schema {
return &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"gaplus": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["gaplus_endpoint"],
},
"edsuser": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["edsuser_endpoint"],
},
"acr": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["acr_endpoint"],
},
"imp": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["imp_endpoint"],
},
"eais": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["eais_endpoint"],
},
"cloudauth": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["cloudauth_endpoint"],
},
"mhub": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["mhub_endpoint"],
},
"servicemesh": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["servicemesh_endpoint"],
},
"quickbi": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["quickbi_endpoint"],
},
"vod": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["vod_endpoint"],
},
"opensearch": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["opensearch_endpoint"],
},
"gds": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["gds_endpoint"],
},
"dbfs": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["dbfs_endpoint"],
},
"devopsrdc": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["devopsrdc_endpoint"],
},
"dg": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["dg_endpoint"],
},
"waf": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["waf_endpoint"],
},
"vs": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["vs_endpoint"],
},
"dts": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["dts_endpoint"],
},
"cloudsso": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["cloudsso_endpoint"],
},
"iot": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["iot_endpoint"],
},
"swas": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["swas_endpoint"],
},
"imm": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["imm_endpoint"],
},
"clickhouse": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["clickhouse_endpoint"],
},
"alidfs": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["alidfs_endpoint"],
},
"ens": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["ens_endpoint"],
},
"bastionhost": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["bastionhost_endpoint"],
},
"cddc": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["cddc_endpoint"],
},
"sddp": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["sddp_endpoint"],
},
"mscopensubscription": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["mscopensubscription_endpoint"],
},
"sas": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["sas_endpoint"],
},
"ehpc": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["ehpc_endpoint"],
},
"dataworkspublic": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["dataworkspublic_endpoint"],
},
"hcs_sgw": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["hcs_sgw_endpoint"],
},
"cloudphone": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["cloudphone_endpoint"],
},
"alb": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["alb_endpoint"],
},
"redisa": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["redisa_endpoint"],
},
"gwsecd": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["gwsecd_endpoint"],
},
"scdn": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["scdn_endpoint"],
},
"arms": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["arms_endpoint"],
},
"serverless": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["serverless_endpoint"],
},
"hbr": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["hbr_endpoint"],
},
"onsproxy": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["onsproxy_endpoint"],
},
"cds": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["cds_endpoint"],
},
"dm": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["dm_endpoint"],
},
"eventbridge": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["eventbridge_endpoint"],
},
"sgw": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["sgw_endpoint"],
},
"quotas": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["quotas_endpoint"],
},
"ims": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["ims_endpoint"],
},
"brain_industrial": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["brain_industrial_endpoint"],
},
"resourcesharing": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["resourcesharing_endpoint"],
},
"ga": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["ga_endpoint"],
},
"hitsdb": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["hitsdb_endpoint"],
},
"privatelink": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["privatelink_endpoint"],
},
"eipanycast": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["eipanycast_endpoint"],
},
"fnf": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["fnf_endpoint"],
},
"ros": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["ros_endpoint"],
},
"r_kvstore": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["r_kvstore_endpoint"],
},
"config": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["config_endpoint"],
},
"dcdn": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["dcdn_endpoint"],
},
"mse": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["mse_endpoint"],
},
"oos": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["oos_endpoint"],
},
"eci": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["eci_endpoint"],
},
"alidns": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["alidns_endpoint"],
},
"resourcemanager": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["resourcemanager_endpoint"],
},
"waf_openapi": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["waf_openapi_endpoint"],
},
"dms_enterprise": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["dms_enterprise_endpoint"],
},
"cassandra": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["cassandra_endpoint"],
},
"cbn": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["cbn_endpoint"],
},
"ecs": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["ecs_endpoint"],
},
"rds": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["rds_endpoint"],
},
"slb": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["slb_endpoint"],
},
"vpc": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["vpc_endpoint"],
},
"ess": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["ess_endpoint"],
},
"oss": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["oss_endpoint"],
},
"ons": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["ons_endpoint"],
},
"alikafka": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["alikafka_endpoint"],
},
"dns": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["dns_endpoint"],
},
"ram": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["ram_endpoint"],
},
"cs": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["cs_endpoint"],
},
"cr": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["cr_endpoint"],
},
"cdn": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["cdn_endpoint"],
},
"kms": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["kms_endpoint"],
},
"ots": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["ots_endpoint"],
},
"cms": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["cms_endpoint"],
},
"pvtz": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["pvtz_endpoint"],
},
"sts": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["sts_endpoint"],
},
// log service is sls service
"log": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["log_endpoint"],
},
"drds": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["drds_endpoint"],
},
"dds": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["dds_endpoint"],
},
"polardb": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["polardb_endpoint"],
},
"gpdb": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["gpdb_endpoint"],
},
"kvstore": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["kvstore_endpoint"],
},
"fc": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["fc_endpoint"],
},
"apigateway": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["apigateway_endpoint"],
},
"datahub": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["datahub_endpoint"],
},
"mns": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["mns_endpoint"],
},
"location": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["location_endpoint"],
},
"elasticsearch": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["elasticsearch_endpoint"],
},
"nas": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["nas_endpoint"],
},
"actiontrail": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["actiontrail_endpoint"],
},
"cas": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["cas_endpoint"],
},
"bssopenapi": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["bssopenapi_endpoint"],
},
"ddoscoo": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["ddoscoo_endpoint"],
},
"ddosbgp": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["ddosbgp_endpoint"],
},
"emr": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["emr_endpoint"],
},
"market": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["market_endpoint"],
},
"adb": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["adb_endpoint"],
},
"maxcompute": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: descriptions["maxcompute_endpoint"],
},
},
},
Set: endpointsToHash,
}
}
func endpointsToHash(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%s-", m["ecs"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["rds"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["slb"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["vpc"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["ess"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["oss"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["ons"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["alikafka"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["dns"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["ram"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["cs"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["cdn"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["kms"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["ots"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["cms"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["pvtz"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["sts"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["log"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["drds"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["dds"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["gpdb"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["kvstore"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["polardb"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["fc"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["apigateway"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["datahub"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["mns"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["location"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["elasticsearch"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["nas"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["actiontrail"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["cas"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["bssopenapi"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["ddoscoo"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["ddosbgp"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["emr"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["market"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["adb"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["cbn"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["maxcompute"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["dms_enterprise"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["waf_openapi"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["resourcemanager"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["alidns"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["cassandra"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["eci"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["oos"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["dcdn"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["mse"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["config"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["r_kvstore"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["fnf"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["ros"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["privatelink"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["resourcesharing"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["ga"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["hitsdb"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["brain_industrial"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["eipanycast"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["ims"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["quotas"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["sgw"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["dm"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["eventbridge"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["onsproxy"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["cds"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["hbr"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["arms"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["serverless"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["alb"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["redisa"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["gwsecd"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["cloudphone"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["scdn"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["dataworkspublic"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["hcs_sgw"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["cddc"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["mscopensubscription"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["sddp"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["bastionhost"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["sas"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["alidfs"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["ehpc"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["ens"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["iot"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["imm"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["clickhouse"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["dts"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["dg"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["cloudsso"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["waf"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["swas"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["vs"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["quickbi"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["vod"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["opensearch"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["gds"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["dbfs"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["devopsrdc"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["eais"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["cloudauth"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["imp"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["mhub"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["servicemesh"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["acr"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["edsuser"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["gaplus"].(string)))
return hashcode.String(buf.String())
}
func getConfigFromProfile(d *schema.ResourceData, ProfileKey string) (interface{}, error) {
if providerConfig == nil {
if v, ok := d.GetOk("profile"); !ok && v.(string) == "" {
return nil, nil
}
current := d.Get("profile").(string)
// Set CredsFilename, expanding home directory
profilePath, err := homedir.Expand(d.Get("shared_credentials_file").(string))
if err != nil {
return nil, WrapError(err)
}
if profilePath == "" {
profilePath = fmt.Sprintf("%s/.aliyun/config.json", os.Getenv("HOME"))
if runtime.GOOS == "windows" {
profilePath = fmt.Sprintf("%s/.aliyun/config.json", os.Getenv("USERPROFILE"))
}
}
providerConfig = make(map[string]interface{})
_, err = os.Stat(profilePath)
if !os.IsNotExist(err) {
data, err := ioutil.ReadFile(profilePath)
if err != nil {
return nil, WrapError(err)
}
config := map[string]interface{}{}
err = json.Unmarshal(data, &config)
if err != nil {
return nil, WrapError(err)
}
for _, v := range config["profiles"].([]interface{}) {
if current == v.(map[string]interface{})["name"] {
providerConfig = v.(map[string]interface{})
}
}
}
}
mode := ""
if v, ok := providerConfig["mode"]; ok {
mode = v.(string)
} else {
return v, nil
}
switch ProfileKey {
case "access_key_id", "access_key_secret":
if mode == "EcsRamRole" {
return "", nil
}
case "ram_role_name":
if mode != "EcsRamRole" {
return "", nil
}
case "sts_token":
if mode != "StsToken" {
return "", nil
}
case "ram_role_arn", "ram_session_name":
if mode != "RamRoleArn" {
return "", nil
}
case "expired_seconds":
if mode != "RamRoleArn" {
return float64(0), nil
}
}
return providerConfig[ProfileKey], nil
}
func getAssumeRoleAK(accessKey, secretKey, stsToken, region, roleArn, sessionName, policy string, sessionExpiration int, stsEndpoint string) (string, string, string, error) {
request := sts.CreateAssumeRoleRequest()
request.RoleArn = roleArn
request.RoleSessionName = sessionName
request.DurationSeconds = requests.NewInteger(sessionExpiration)
request.Policy = policy
request.Scheme = "https"
request.Domain = stsEndpoint
var client *sts.Client
var err error
if stsToken == "" {
client, err = sts.NewClientWithAccessKey(region, accessKey, secretKey)
} else {
client, err = sts.NewClientWithStsToken(region, accessKey, secretKey, stsToken)
}
if err != nil {
return "", "", "", err
}
response, err := client.AssumeRole(request)
if err != nil {
return "", "", "", err
}
return response.Credentials.AccessKeyId, response.Credentials.AccessKeySecret, response.Credentials.SecurityToken, nil
}
type CredentialsURIResponse struct {
Code string
AccessKeyId string
AccessKeySecret string
SecurityToken string
Expiration string
}
func getClientByCredentialsURI(credentialsURI string) (*CredentialsURIResponse, error) {
res, err := http.Get(credentialsURI)
if err != nil {
return nil, err
}
if res.StatusCode != 200 {
return nil, fmt.Errorf("get Credentials from %s failed, status code %d", credentialsURI, res.StatusCode)
}
body, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
return nil, err
}
var response CredentialsURIResponse
err = json.Unmarshal(body, &response)
if err != nil {
return nil, fmt.Errorf("unmarshal credentials failed, the body %s", string(body))
}
if response.Code != "Success" {
return nil, fmt.Errorf("fetching sts token from %s got an error and its Code is not Success", credentialsURI)
}
return &response, nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudActiontrailHistoryDeliveryJob() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudActiontrailHistoryDeliveryJobCreate,
Read: resourceAlicloudActiontrailHistoryDeliveryJobRead,
Delete: resourceAlicloudActiontrailHistoryDeliveryJobDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
Delete: schema.DefaultTimeout(2 * time.Minute),
},
Schema: map[string]*schema.Schema{
"status": {
Type: schema.TypeInt,
Computed: true,
},
"trail_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudActiontrailHistoryDeliveryJobCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateDeliveryHistoryJob"
request := make(map[string]interface{})
conn, err := client.NewActiontrailClient()
if err != nil {
return WrapError(err)
}
request["TrailName"] = d.Get("trail_name")
request["ClientToken"] = buildClientToken("CreateDeliveryHistoryJob")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-07-06"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_actiontrail_history_delivery_job", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(formatInt(response["JobId"])))
actiontrailService := ActiontrailService{client}
stateConf := BuildStateConf([]string{}, []string{"2", "3"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, actiontrailService.ActiontrailHistoryDeliveryJobStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudActiontrailHistoryDeliveryJobRead(d, meta)
}
func resourceAlicloudActiontrailHistoryDeliveryJobRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
actiontrailService := ActiontrailService{client}
object, err := actiontrailService.DescribeActiontrailHistoryDeliveryJob(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_actiontrail_history_delivery_job actiontrailService.DescribeActiontrailHistoryDeliveryJob Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("status", formatInt(object["JobStatus"]))
d.Set("trail_name", object["TrailName"])
return nil
}
func resourceAlicloudActiontrailHistoryDeliveryJobDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteDeliveryHistoryJob"
var response map[string]interface{}
conn, err := client.NewActiontrailClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"JobId": d.Id(),
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-07-06"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudActiontrailTrail() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudActiontrailTrailCreate,
Read: resourceAlicloudActiontrailTrailRead,
Update: resourceAlicloudActiontrailTrailUpdate,
Delete: resourceAlicloudActiontrailTrailDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"event_rw": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"All", "Read", "Write"}, false),
Default: "Write",
},
"is_organization_trail": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"mns_topic_arn": {
Type: schema.TypeString,
Optional: true,
Deprecated: "Field 'mns_topic_arn' has been deprecated from version 1.118.0",
},
"oss_bucket_name": {
Type: schema.TypeString,
Optional: true,
},
"oss_key_prefix": {
Type: schema.TypeString,
Optional: true,
},
"role_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Field 'role_name' has been deprecated from version 1.118.0",
},
"oss_write_role_arn": {
Type: schema.TypeString,
Optional: true,
},
"sls_project_arn": {
Type: schema.TypeString,
Optional: true,
},
"sls_write_role_arn": {
Type: schema.TypeString,
Optional: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Enable", "Disable"}, false),
Default: "Enable",
},
"trail_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"name"},
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Deprecated: "Field 'name' has been deprecated from version 1.95.0. Use 'trail_name' instead.",
ConflictsWith: []string{"trail_name"},
},
"trail_region": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"All", "cn-beijing", "cn-hangzhou"}, false),
Default: "All",
},
},
}
}
func resourceAlicloudActiontrailTrailCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
actiontrailService := ActiontrailService{client}
var response map[string]interface{}
action := "CreateTrail"
request := make(map[string]interface{})
conn, err := client.NewActiontrailClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("event_rw"); ok {
request["EventRW"] = v
}
if v, ok := d.GetOkExists("is_organization_trail"); ok {
request["IsOrganizationTrail"] = v
}
if v, ok := d.GetOk("oss_bucket_name"); ok {
request["OssBucketName"] = v
}
if v, ok := d.GetOk("oss_key_prefix"); ok {
request["OssKeyPrefix"] = v
}
if v, ok := d.GetOk("oss_write_role_arn"); ok {
request["OssWriteRoleArn"] = v
}
if v, ok := d.GetOk("sls_project_arn"); ok {
request["SlsProjectArn"] = v
}
if v, ok := d.GetOk("sls_write_role_arn"); ok {
request["SlsWriteRoleArn"] = v
}
if v, ok := d.GetOk("trail_name"); ok {
request["Name"] = v
} else if v, ok := d.GetOk("name"); ok {
request["Name"] = v
} else {
return WrapError(Error(`[ERROR] Argument "name" or "trail_name" must be set one!`))
}
if v, ok := d.GetOk("trail_region"); ok {
request["TrailRegion"] = v
}
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-07-06"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"InsufficientBucketPolicyException"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_actiontrail_trail", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["Name"]))
stateConf := BuildStateConf([]string{}, []string{"Fresh"}, d.Timeout(schema.TimeoutCreate), 10*time.Second, actiontrailService.ActiontrailTrailStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudActiontrailTrailUpdate(d, meta)
}
func resourceAlicloudActiontrailTrailRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
actiontrailService := ActiontrailService{client}
object, err := actiontrailService.DescribeActiontrailTrail(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_actiontrail_trail actiontrailService.DescribeActiontrailTrail Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("trail_name", d.Id())
d.Set("name", d.Id())
d.Set("event_rw", object["EventRW"])
d.Set("is_organization_trail", object["IsOrganizationTrail"])
d.Set("oss_bucket_name", object["OssBucketName"])
d.Set("oss_key_prefix", object["OssKeyPrefix"])
d.Set("oss_write_role_arn", object["OssWriteRoleArn"])
d.Set("sls_project_arn", object["SlsProjectArn"])
d.Set("sls_write_role_arn", object["SlsWriteRoleArn"])
d.Set("status", object["Status"])
d.Set("trail_region", object["TrailRegion"])
return nil
}
func resourceAlicloudActiontrailTrailUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
actiontrailService := ActiontrailService{client}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"Name": d.Id(),
}
if !d.IsNewResource() && d.HasChange("event_rw") {
update = true
request["EventRW"] = d.Get("event_rw")
}
if !d.IsNewResource() && d.HasChange("oss_bucket_name") {
update = true
request["OssBucketName"] = d.Get("oss_bucket_name")
}
if !d.IsNewResource() && d.HasChange("oss_key_prefix") {
update = true
request["OssKeyPrefix"] = d.Get("oss_key_prefix")
}
if !d.IsNewResource() && d.HasChange("oss_write_role_arn") {
update = true
request["OssWriteRoleArn"] = d.Get("oss_write_role_arn")
}
request["RegionId"] = client.RegionId
if !d.IsNewResource() && d.HasChange("sls_project_arn") {
update = true
request["SlsProjectArn"] = d.Get("sls_project_arn")
}
if !d.IsNewResource() && d.HasChange("sls_write_role_arn") {
update = true
request["SlsWriteRoleArn"] = d.Get("sls_write_role_arn")
}
if !d.IsNewResource() && d.HasChange("trail_region") {
update = true
request["TrailRegion"] = d.Get("trail_region")
}
if update {
if v, ok := d.GetOk("sls_project_arn"); ok {
request["SlsProjectArn"] = v
}
if v, ok := d.GetOk("sls_write_role_arn"); ok {
request["SlsWriteRoleArn"] = v
}
if v, ok := d.GetOk("oss_bucket_name"); ok {
request["OssBucketName"] = v
}
if v, ok := d.GetOk("oss_write_role_arn"); ok {
request["OssWriteRoleArn"] = v
}
action := "UpdateTrail"
conn, err := client.NewActiontrailClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-07-06"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"InsufficientBucketPolicyException"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("event_rw")
d.SetPartial("oss_bucket_name")
d.SetPartial("oss_key_prefix")
d.SetPartial("oss_write_role_arn")
d.SetPartial("sls_project_arn")
d.SetPartial("sls_write_role_arn")
d.SetPartial("trail_region")
}
if d.HasChange("status") {
object, err := actiontrailService.DescribeActiontrailTrail(d.Id())
if err != nil {
return WrapError(err)
}
target := d.Get("status").(string)
if object["Status"].(string) != target {
if target == "Disable" {
request := map[string]interface{}{
"Name": d.Id(),
}
action := "StopLogging"
conn, err := client.NewActiontrailClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2020-07-06"), StringPointer("AK"), request, nil, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"InsufficientBucketPolicyException"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Disable"}, d.Timeout(schema.TimeoutUpdate), 10*time.Second, actiontrailService.ActiontrailTrailStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if target == "Enable" {
request := map[string]interface{}{
"Name": d.Id(),
}
action := "StartLogging"
conn, err := client.NewActiontrailClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-07-06"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"InsufficientBucketPolicyException"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Enable"}, d.Timeout(schema.TimeoutUpdate), 10*time.Second, actiontrailService.ActiontrailTrailStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.SetPartial("status")
}
}
d.Partial(false)
return resourceAlicloudActiontrailTrailRead(d, meta)
}
func resourceAlicloudActiontrailTrailDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteTrail"
var response map[string]interface{}
conn, err := client.NewActiontrailClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"Name": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-07-06"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"TrailNotFoundException"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/adb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudAdbAccount() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAdbAccountCreate,
Read: resourceAlicloudAdbAccountRead,
Update: resourceAlicloudAdbAccountUpdate,
Delete: resourceAlicloudAdbAccountDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"db_cluster_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"account_name": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"account_password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"kms_encrypted_password": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: kmsDiffSuppressFunc,
},
"kms_encryption_context": {
Type: schema.TypeMap,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("kms_encrypted_password").(string) == ""
},
Elem: schema.TypeString,
},
"account_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{string("Super")}, false),
Default: "Super",
ForceNew: true,
Removed: "Field 'account_type' has been removed from provider version 1.81.0.",
},
"account_description": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudAdbAccountCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
adbService := AdbService{client}
request := adb.CreateCreateAccountRequest()
request.RegionId = client.RegionId
request.DBClusterId = d.Get("db_cluster_id").(string)
request.AccountName = d.Get("account_name").(string)
password := d.Get("account_password").(string)
kmsPassword := d.Get("kms_encrypted_password").(string)
if password == "" && kmsPassword == "" {
return WrapError(Error("One of the 'password' and 'kms_encrypted_password' should be set."))
}
if password != "" {
request.AccountPassword = password
} else {
kmsService := KmsService{client}
decryptResp, err := kmsService.Decrypt(kmsPassword, d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request.AccountPassword = decryptResp
}
// Description will not be set when account type is normal and it is a API bug
if v, ok := d.GetOk("account_description"); ok && v.(string) != "" {
request.AccountDescription = v.(string)
}
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithAdbClient(func(adbClient *adb.Client) (interface{}, error) {
return adbClient.CreateAccount(request)
})
if err != nil {
if IsExpectedErrors(err, OperationDeniedDBStatus) {
time.Sleep(5 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_adb_account", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprintf("%s%s%s", request.DBClusterId, COLON_SEPARATED, request.AccountName))
if err := adbService.WaitForAdbAccount(d.Id(), Available, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
return resourceAlicloudAdbAccountRead(d, meta)
}
func resourceAlicloudAdbAccountRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
adbService := AdbService{client}
object, err := adbService.DescribeAdbAccount(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("db_cluster_id", parts[0])
d.Set("account_name", object.AccountName)
d.Set("account_description", object.AccountDescription)
return nil
}
func resourceAlicloudAdbAccountUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
adbService := AdbService{client}
d.Partial(true)
parts := strings.Split(d.Id(), COLON_SEPARATED)
instanceId := parts[0]
accountName := parts[1]
if d.HasChange("account_description") {
if err := adbService.WaitForAdbAccount(d.Id(), Available, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
request := adb.CreateModifyAccountDescriptionRequest()
request.RegionId = client.RegionId
request.DBClusterId = instanceId
request.AccountName = accountName
request.AccountDescription = d.Get("account_description").(string)
raw, err := client.WithAdbClient(func(adbClient *adb.Client) (interface{}, error) {
return adbClient.ModifyAccountDescription(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("account_description")
}
if d.HasChange("account_password") || d.HasChange("kms_encrypted_password") {
if err := adbService.WaitForAdbAccount(d.Id(), Available, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
request := adb.CreateResetAccountPasswordRequest()
request.RegionId = client.RegionId
request.DBClusterId = instanceId
request.AccountName = accountName
password := d.Get("account_password").(string)
kmsPassword := d.Get("kms_encrypted_password").(string)
if password == "" && kmsPassword == "" {
return WrapError(Error("One of the 'password' and 'kms_encrypted_password' should be set."))
}
if password != "" {
request.AccountPassword = password
} else {
kmsService := KmsService{meta.(*connectivity.AliyunClient)}
decryptResp, err := kmsService.Decrypt(kmsPassword, d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request.AccountPassword = decryptResp
}
raw, err := client.WithAdbClient(func(adbClient *adb.Client) (interface{}, error) {
return adbClient.ResetAccountPassword(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("account_password")
}
d.Partial(false)
return resourceAlicloudAdbAccountRead(d, meta)
}
func resourceAlicloudAdbAccountDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
adbService := AdbService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request := adb.CreateDeleteAccountRequest()
request.RegionId = client.RegionId
request.DBClusterId = parts[0]
request.AccountName = parts[1]
raw, err := client.WithAdbClient(func(adbClient *adb.Client) (interface{}, error) {
return adbClient.DeleteAccount(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidAccountName.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return adbService.WaitForAdbAccount(d.Id(), Deleted, DefaultTimeoutMedium)
}
package alicloud
import (
"fmt"
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/adb"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudAdbBackupPolicy() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAdbBackupPolicyCreate,
Read: resourceAlicloudAdbBackupPolicyRead,
Update: resourceAlicloudAdbBackupPolicyUpdate,
Delete: resourceAlicloudAdbBackupPolicyDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"db_cluster_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"preferred_backup_period": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
// terraform does not support ValidateFunc of TypeList attr
// ValidateFunc: validateAllowedStringValue([]string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}),
Required: true,
},
"preferred_backup_time": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice(BACKUP_TIME, false),
Required: true,
},
"backup_retention_period": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudAdbBackupPolicyCreate(d *schema.ResourceData, meta interface{}) error {
d.SetId(d.Get("db_cluster_id").(string))
return resourceAlicloudAdbBackupPolicyUpdate(d, meta)
}
func resourceAlicloudAdbBackupPolicyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
adbService := AdbService{client}
object, err := adbService.DescribeAdbBackupPolicy(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("db_cluster_id", d.Id())
d.Set("backup_retention_period", object.BackupRetentionPeriod)
d.Set("preferred_backup_period", strings.Split(object.PreferredBackupPeriod, ","))
d.Set("preferred_backup_time", object.PreferredBackupTime)
return nil
}
func resourceAlicloudAdbBackupPolicyUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
adbService := AdbService{client}
if d.HasChange("preferred_backup_period") || d.HasChange("preferred_backup_time") {
periodList := expandStringList(d.Get("preferred_backup_period").(*schema.Set).List())
preferredBackupPeriod := fmt.Sprintf("%s", strings.Join(periodList[:], COMMA_SEPARATED))
preferredBackupTime := d.Get("preferred_backup_time").(string)
// wait instance running before modifying
if err := adbService.WaitForCluster(d.Id(), Running, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
if err := resource.Retry(5*time.Minute, func() *resource.RetryError {
if err := adbService.ModifyAdbBackupPolicy(d.Id(), preferredBackupTime, preferredBackupPeriod); err != nil {
if IsExpectedErrors(err, OperationDeniedDBStatus) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
}); err != nil {
return WrapError(err)
}
}
return resourceAlicloudAdbBackupPolicyRead(d, meta)
}
func resourceAlicloudAdbBackupPolicyDelete(d *schema.ResourceData, meta interface{}) error {
// In case of a delete we are resetting to default values which is Tuesday,Friday each 1am-2am
client := meta.(*connectivity.AliyunClient)
request := adb.CreateModifyBackupPolicyRequest()
request.RegionId = client.RegionId
request.DBClusterId = d.Id()
request.PreferredBackupTime = "01:00Z-02:00Z"
request.PreferredBackupPeriod = "Tuesday,Friday"
raw, err := client.WithAdbClient(func(adbClient *adb.Client) (interface{}, error) {
return adbClient.ModifyBackupPolicy(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}
package alicloud
import (
"fmt"
"regexp"
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/adb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudAdbConnection() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAdbConnectionCreate,
Read: resourceAlicloudAdbConnectionRead,
Delete: resourceAlicloudAdbConnectionDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"db_cluster_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"connection_prefix": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-z][a-z0-9\\-]{4,28}[a-z0-9]$`), "The prefix must be 6 to 30 characters in length, and can contain lowercase letters, digits, and hyphens (-), must start with a letter and end with a digit or letter."),
},
"port": {
Type: schema.TypeString,
Computed: true,
},
"connection_string": {
Type: schema.TypeString,
Computed: true,
},
"ip_address": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudAdbConnectionCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
adbService := AdbService{client}
dbClusterId := d.Get("db_cluster_id").(string)
prefix := d.Get("connection_prefix").(string)
if prefix == "" {
prefix = fmt.Sprintf("%stf", dbClusterId)
}
request := adb.CreateAllocateClusterPublicConnectionRequest()
request.RegionId = client.RegionId
request.DBClusterId = dbClusterId
request.ConnectionStringPrefix = prefix
var raw interface{}
var err error
err = resource.Retry(8*time.Minute, func() *resource.RetryError {
raw, err = client.WithAdbClient(func(adbClient *adb.Client) (interface{}, error) {
return adbClient.AllocateClusterPublicConnection(request)
})
if err != nil {
if IsExpectedErrors(err, OperationDeniedDBStatus) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_adb_connection", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprintf("%s%s%s", dbClusterId, COLON_SEPARATED, request.ConnectionStringPrefix))
if err := adbService.WaitForAdbConnection(d.Id(), Available, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
// wait instance running after allocating
if err := adbService.WaitForCluster(dbClusterId, Running, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
return resourceAlicloudAdbConnectionRead(d, meta)
}
func resourceAlicloudAdbConnectionRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
adbService := AdbService{client}
object, err := adbService.DescribeAdbConnection(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("db_cluster_id", parts[0])
d.Set("connection_prefix", parts[1])
d.Set("port", object.Port)
d.Set("connection_string", object.ConnectionString)
d.Set("ip_address", object.IPAddress)
return nil
}
func resourceAlicloudAdbConnectionDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
adbService := AdbService{client}
split := strings.Split(d.Id(), COLON_SEPARATED)
request := adb.CreateReleaseClusterPublicConnectionRequest()
request.RegionId = client.RegionId
request.DBClusterId = split[0]
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
var raw interface{}
raw, err := client.WithAdbClient(func(adbClient *adb.Client) (interface{}, error) {
return adbClient.ReleaseClusterPublicConnection(request)
})
if err != nil {
if IsExpectedErrors(err, OperationDeniedDBStatus) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return adbService.WaitForAdbConnection(d.Id(), Deleted, DefaultTimeoutMedium)
}
package alicloud
import (
"encoding/json"
"fmt"
"log"
"strconv"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudAdbDbCluster() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAdbDbClusterCreate,
Read: resourceAlicloudAdbDbClusterRead,
Update: resourceAlicloudAdbDbClusterUpdate,
Delete: resourceAlicloudAdbDbClusterDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(50 * time.Minute),
Delete: schema.DefaultTimeout(50 * time.Minute),
Update: schema.DefaultTimeout(72 * time.Minute),
},
Schema: map[string]*schema.Schema{
"auto_renew_period": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 6, 12, 24, 36}),
Default: 1,
DiffSuppressFunc: adbPostPaidAndRenewDiffSuppressFunc,
},
"compute_resource": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("mode"); ok && v.(string) == "reserver" {
return true
}
return false
},
},
"connection_string": {
Type: schema.TypeString,
Computed: true,
},
"db_cluster_category": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"Basic", "Cluster", "MixedStorage"}, false),
},
"db_cluster_class": {
Type: schema.TypeString,
Optional: true,
Deprecated: "It duplicates with attribute db_node_class and is deprecated from 1.121.2.",
},
"db_cluster_version": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"3.0"}, false),
Default: "3.0",
},
"db_node_class": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"db_node_count": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"db_node_storage": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"elastic_io_resource": {
Type: schema.TypeInt,
Optional: true,
Default: 0,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("mode"); ok && v.(string) == "reserver" {
return true
}
return false
},
},
"maintain_time": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"mode": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"reserver", "flexible"}, false),
},
"modify_type": {
Type: schema.TypeString,
Optional: true,
},
"payment_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo", "Subscription"}, false),
ConflictsWith: []string{"pay_type"},
},
"pay_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PostPaid", "PrePaid"}, false),
ConflictsWith: []string{"payment_type"},
},
"period": {
Type: schema.TypeInt,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 24, 36}),
DiffSuppressFunc: adbPostPaidDiffSuppressFunc,
Optional: true,
},
"renewal_status": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"AutoRenewal", "Normal", "NotRenewal"}, false),
Default: "NotRenewal",
DiffSuppressFunc: adbPostPaidDiffSuppressFunc,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"security_ips": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudAdbDbClusterCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
adbService := AdbService{client}
var response map[string]interface{}
action := "CreateDBCluster"
request := make(map[string]interface{})
conn, err := client.NewAdsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("compute_resource"); ok {
request["ComputeResource"] = v
}
request["DBClusterCategory"] = d.Get("db_cluster_category")
if v, ok := d.GetOk("db_node_class"); ok {
request["DBClusterClass"] = v
} else if v, ok := d.GetOk("db_cluster_class"); ok {
request["DBClusterClass"] = v
}
request["DBClusterVersion"] = d.Get("db_cluster_version")
if v, ok := d.GetOk("db_node_count"); ok {
request["DBNodeGroupCount"] = v
}
if v, ok := d.GetOk("db_node_storage"); ok {
request["DBNodeStorage"] = v
}
if v, ok := d.GetOk("description"); ok {
request["DBClusterDescription"] = v
}
if v, ok := d.GetOk("mode"); ok {
request["Mode"] = v
}
if v, ok := d.GetOk("payment_type"); ok {
request["PayType"] = convertAdbDBClusterPaymentTypeRequest(v.(string))
if request["PayType"] != string(Postpaid) {
request["PayType"] = string(Prepaid)
period := d.Get("period").(int)
request["UsedTime"] = strconv.Itoa(period)
request["Period"] = string(Month)
if period > 9 {
request["UsedTime"] = strconv.Itoa(period / 12)
request["Period"] = string(Year)
}
}
} else if v, ok := d.GetOk("pay_type"); ok {
request["PayType"] = convertAdbDbClusterDBClusterPayTypeRequest(v.(string))
if request["PayType"] != string(Postpaid) {
request["PayType"] = string(Prepaid)
period := d.Get("period").(int)
request["UsedTime"] = strconv.Itoa(period)
request["Period"] = string(Month)
if period > 9 {
request["UsedTime"] = strconv.Itoa(period / 12)
request["Period"] = string(Year)
}
}
} else {
request["PayType"] = "Postpaid"
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("zone_id"); ok {
request["ZoneId"] = v
}
vswitchId := Trim(d.Get("vswitch_id").(string))
if vswitchId != "" {
vpcService := VpcService{client}
vsw, err := vpcService.DescribeVSwitchWithTeadsl(vswitchId)
if err != nil {
return WrapError(err)
}
request["DBClusterNetworkType"] = "VPC"
request["VPCId"] = vsw["VpcId"]
request["VSwitchId"] = vswitchId
if v, ok := request["ZoneId"].(string); !ok || v == "" {
request["ZoneId"] = vsw["ZoneId"]
}
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("CreateDBCluster")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_adb_db_cluster", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetId(fmt.Sprint(response["DBClusterId"]))
stateConf := BuildStateConf([]string{"Preparing", "Creating"}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 900*time.Second, adbService.AdbDbClusterStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudAdbDbClusterUpdate(d, meta)
}
func resourceAlicloudAdbDbClusterRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
adbService := AdbService{client}
object, err := adbService.DescribeAdbDbCluster(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_analyticdb_for_mysql3.0_db_cluster adbService.DescribeAdbDbCluster Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("compute_resource", object["ComputeResource"])
d.Set("connection_string", object["ConnectionString"])
d.Set("db_cluster_category", convertAdbDBClusterCategoryResponse(object["Category"].(string)))
d.Set("db_node_class", object["DBNodeClass"])
d.Set("db_node_count", object["DBNodeCount"])
d.Set("db_node_storage", object["DBNodeStorage"])
d.Set("description", object["DBClusterDescription"])
d.Set("elastic_io_resource", formatInt(object["ElasticIOResource"]))
d.Set("maintain_time", object["MaintainTime"])
d.Set("mode", object["Mode"])
d.Set("payment_type", convertAdbDBClusterPaymentTypeResponse(object["PayType"].(string)))
d.Set("pay_type", convertAdbDbClusterDBClusterPayTypeResponse(object["PayType"].(string)))
d.Set("resource_group_id", object["ResourceGroupId"])
d.Set("status", object["DBClusterStatus"])
d.Set("tags", tagsToMap(object["Tags"].(map[string]interface{})["Tag"]))
d.Set("vswitch_id", object["VSwitchId"])
d.Set("zone_id", object["ZoneId"])
if object["PayType"].(string) == string(Prepaid) {
describeAutoRenewAttributeObject, err := adbService.DescribeAutoRenewAttribute(d.Id())
if err != nil {
return WrapError(err)
}
renewPeriod := 1
if describeAutoRenewAttributeObject != nil {
renewPeriod = formatInt(describeAutoRenewAttributeObject["Duration"])
}
if describeAutoRenewAttributeObject != nil && describeAutoRenewAttributeObject["PeriodUnit"] == string(Year) {
renewPeriod = renewPeriod * 12
}
d.Set("auto_renew_period", renewPeriod)
//period, err := computePeriodByUnit(object["CreationTime"], object["ExpireTime"], d.Get("period").(int), "Month")
//if err != nil {
// return WrapError(err)
//}
//d.Set("period", period)
d.Set("renewal_status", describeAutoRenewAttributeObject["RenewalStatus"])
}
describeDBClusterAccessWhiteListObject, err := adbService.DescribeDBClusterAccessWhiteList(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("security_ips", strings.Split(describeDBClusterAccessWhiteListObject["SecurityIPList"].(string), ","))
describeDBClustersObject, err := adbService.DescribeDBClusters(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("db_cluster_version", describeDBClustersObject["DBVersion"])
return nil
}
func resourceAlicloudAdbDbClusterUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
adbService := AdbService{client}
var response map[string]interface{}
d.Partial(true)
if d.HasChange("tags") {
if err := adbService.SetResourceTags(d, "ALIYUN::ADB::CLUSTER"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
if !d.IsNewResource() && d.HasChange("description") {
request := map[string]interface{}{
"DBClusterId": d.Id(),
}
request["DBClusterDescription"] = d.Get("description")
action := "ModifyDBClusterDescription"
conn, err := client.NewAdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("description")
}
if d.HasChange("maintain_time") {
request := map[string]interface{}{
"DBClusterId": d.Id(),
}
request["MaintainTime"] = d.Get("maintain_time")
action := "ModifyDBClusterMaintainTime"
conn, err := client.NewAdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("maintain_time")
}
if !d.IsNewResource() && d.HasChange("resource_group_id") {
request := map[string]interface{}{
"DBClusterId": d.Id(),
}
request["NewResourceGroupId"] = d.Get("resource_group_id")
action := "ModifyDBClusterResourceGroup"
conn, err := client.NewAdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("resource_group_id")
}
update := false
request := map[string]interface{}{
"DBClusterId": d.Id(),
}
request["RegionId"] = client.RegionId
if d.Get("pay_type").(string) == string(PrePaid) || d.Get("payment_type").(string) == "Subscription" && d.HasChange("auto_renew_period") {
update = true
if d.Get("renewal_status").(string) == string(RenewAutoRenewal) {
period := d.Get("auto_renew_period").(int)
request["Duration"] = strconv.Itoa(period)
request["PeriodUnit"] = string(Month)
if period > 9 {
request["Duration"] = strconv.Itoa(period / 12)
request["PeriodUnit"] = string(Year)
}
}
}
if d.Get("pay_type").(string) == string(PrePaid) || d.Get("payment_type").(string) == "Subscription" && d.HasChange("renewal_status") {
update = true
request["RenewalStatus"] = d.Get("renewal_status")
}
if update {
action := "ModifyAutoRenewAttribute"
conn, err := client.NewAdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("auto_renew_period")
d.SetPartial("renewal_status")
}
update = false
modifyDBClusterAccessWhiteListReq := map[string]interface{}{
"DBClusterId": d.Id(),
}
if d.HasChange("security_ips") {
update = true
}
modifyDBClusterAccessWhiteListReq["SecurityIps"] = convertListToCommaSeparate(d.Get("security_ips").(*schema.Set).List())
if update {
action := "ModifyDBClusterAccessWhiteList"
conn, err := client.NewAdsClient()
if err != nil {
return WrapError(err)
}
if modifyDBClusterAccessWhiteListReq["SecurityIps"].(string) == "" {
modifyDBClusterAccessWhiteListReq["SecurityIps"] = LOCAL_HOST_IP
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-15"), StringPointer("AK"), nil, modifyDBClusterAccessWhiteListReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, modifyDBClusterAccessWhiteListReq)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("security_ips")
}
update = false
modifyDBClusterReq := map[string]interface{}{
"DBClusterId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("compute_resource") {
update = true
modifyDBClusterReq["ComputeResource"] = d.Get("compute_resource")
}
if !d.IsNewResource() && d.HasChange("db_cluster_category") {
update = true
modifyDBClusterReq["DBClusterCategory"] = d.Get("db_cluster_category")
}
if !d.IsNewResource() && d.HasChange("db_node_class") {
update = true
modifyDBClusterReq["DBNodeClass"] = d.Get("db_node_class")
}
if !d.IsNewResource() && d.HasChange("db_node_count") {
update = true
modifyDBClusterReq["DBNodeGroupCount"] = d.Get("db_node_count")
}
if !d.IsNewResource() && d.HasChange("db_node_storage") {
update = true
modifyDBClusterReq["DBNodeStorage"] = d.Get("db_node_storage")
}
if d.HasChange("elastic_io_resource") {
update = true
modifyDBClusterReq["ElasticIOResource"] = d.Get("elastic_io_resource")
}
modifyDBClusterReq["RegionId"] = client.RegionId
if update {
if _, ok := d.GetOk("mode"); ok {
modifyDBClusterReq["Mode"] = d.Get("mode")
}
if _, ok := d.GetOk("modify_type"); ok {
modifyDBClusterReq["ModifyType"] = d.Get("modify_type")
}
action := "ModifyDBCluster"
conn, err := client.NewAdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-15"), StringPointer("AK"), nil, modifyDBClusterReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, modifyDBClusterReq)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"ClassChanging"}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 900*time.Second, adbService.AdbDbClusterStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("compute_resource")
d.SetPartial("db_cluster_category")
d.SetPartial("db_node_class")
d.SetPartial("db_node_count")
d.SetPartial("db_node_storage")
d.SetPartial("elastic_io_resource")
}
d.Partial(false)
return resourceAlicloudAdbDbClusterRead(d, meta)
}
func resourceAlicloudAdbDbClusterDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
adbService := AdbService{client}
action := "DeleteDBCluster"
var response map[string]interface{}
conn, err := client.NewAdsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DBClusterId": d.Id(),
}
var taskId string
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
taskId = response["TaskId"].(json.Number).String()
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBCluster.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"Waiting", "Running", "Failed", "Retry", "Pause", "Stop"}, []string{"Finished", "Closed", "Cancel"}, d.Timeout(schema.TimeoutDelete), 10*time.Minute, adbService.AdbTaskStateRefreshFunc(d.Id(), taskId))
if _, err = stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
func convertAdbDbClusterDBClusterPayTypeRequest(source string) string {
switch source {
case "PostPaid":
return "Postpaid"
case "PrePaid":
return "Prepaid"
}
return source
}
func convertAdbDbClusterDBClusterPayTypeResponse(source string) string {
switch source {
case "Postpaid":
return "PostPaid"
case "Prepaid":
return "PrePaid"
}
return source
}
func convertAdbDBClusterPaymentTypeRequest(source string) string {
switch source {
case "PayAsYouGo":
return "Postpaid"
case "Subscription":
return "Prepaid"
}
return source
}
func convertAdbDBClusterPaymentTypeResponse(source string) string {
switch source {
case "Postpaid":
return "PayAsYouGo"
case "Prepaid":
return "Subscription"
}
return source
}
func convertAdbDBClusterCategoryResponse(source string) string {
switch source {
case "MIXED_STORAGE":
return "MixedStorage"
}
return source
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudAlbAcl() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAlbAclCreate,
Read: resourceAlicloudAlbAclRead,
Update: resourceAlicloudAlbAclUpdate,
Delete: resourceAlicloudAlbAclDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(16 * time.Minute),
Delete: schema.DefaultTimeout(16 * time.Minute),
Update: schema.DefaultTimeout(16 * time.Minute),
},
Schema: map[string]*schema.Schema{
"acl_entries": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(1, 256),
},
"entry": {
Type: schema.TypeString,
Optional: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"acl_name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-zA-Z][A-Za-z0-9._-]{2,128}$`), "The name must be `2` to `128` characters in length, and can contain letters, digits, hyphens (-) and underscores (_). It must start with a letter."),
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
},
}
}
func resourceAlicloudAlbAclCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateAcl"
request := make(map[string]interface{})
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("acl_name"); ok {
request["AclName"] = v
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
request["ClientToken"] = buildClientToken("CreateAcl")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"OperationFailed.ResourceGroupStatusCheckFail", "SystemBusy", "Throttling"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_alb_acl", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["AclId"]))
albService := AlbService{client}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, albService.AlbAclStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudAlbAclUpdate(d, meta)
}
func resourceAlicloudAlbAclRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
albService := AlbService{client}
object, err := albService.DescribeAlbAcl(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_alb_acl albService.DescribeAlbAcl Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("acl_name", object["AclName"])
d.Set("resource_group_id", object["ResourceGroupId"])
d.Set("status", object["AclStatus"])
listAclEntriesObject, err := albService.ListAclEntries(d.Id())
if err != nil {
return WrapError(err)
}
aclEntriesMaps := make([]map[string]interface{}, 0)
for _, aclEntriesListItem := range listAclEntriesObject {
aclEntriesArg := make(map[string]interface{}, 0)
aclEntriesArg["description"] = aclEntriesListItem["Description"]
aclEntriesArg["entry"] = aclEntriesListItem["Entry"]
aclEntriesArg["status"] = aclEntriesListItem["Status"]
aclEntriesMaps = append(aclEntriesMaps, aclEntriesArg)
}
d.Set("acl_entries", aclEntriesMaps)
listTagResourcesObject, err := albService.ListTagResources(d.Id(), "acl")
d.Set("tags", tagsToMap(listTagResourcesObject))
return nil
}
func resourceAlicloudAlbAclUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
albService := AlbService{client}
var response map[string]interface{}
d.Partial(true)
if d.HasChange("tags") {
if err := albService.SetResourceTags(d, "acl"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
update := false
request := map[string]interface{}{
"ResourceId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("resource_group_id") {
update = true
}
if v, ok := d.GetOk("resource_group_id"); ok {
request["NewResourceGroupId"] = v
}
request["ResourceType"] = "acl"
if update {
action := "MoveResourceGroup"
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"NotExist.ResourceGroup"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("resource_group_id")
}
update = false
updateAclAttributeReq := map[string]interface{}{
"AclId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("acl_name") {
update = true
}
if v, ok := d.GetOk("acl_name"); ok {
updateAclAttributeReq["AclName"] = v
}
if update {
if v, ok := d.GetOkExists("dry_run"); ok {
updateAclAttributeReq["DryRun"] = v
}
action := "UpdateAclAttribute"
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("UpdateAclAttribute")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, updateAclAttributeReq, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"OperationFailed.ResourceGroupStatusCheckFail", "SystemBusy", "Throttling"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, updateAclAttributeReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, albService.AlbAclStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("acl_name")
}
update = false
if d.HasChange("acl_entries") {
oraw, nraw := d.GetChange("acl_entries")
remove := oraw.(*schema.Set).Difference(nraw.(*schema.Set)).List()
create := nraw.(*schema.Set).Difference(oraw.(*schema.Set)).List()
if len(remove) > 0 {
removeList := SplitSlice(remove, 20)
for _, item := range removeList {
removeEntriesFromAclReq := map[string]interface{}{
"AclId": d.Id(),
}
aclEntriesMaps := make([]string, 0)
for _, aclEntries := range item {
aclEntriesArg := aclEntries.(map[string]interface{})
aclEntriesMaps = append(aclEntriesMaps, aclEntriesArg["entry"].(string))
}
removeEntriesFromAclReq["Entries"] = aclEntriesMaps
if v, ok := d.GetOkExists("dry_run"); ok {
removeEntriesFromAclReq["DryRun"] = v
}
action := "RemoveEntriesFromAcl"
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("RemoveEntriesFromAcl")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, removeEntriesFromAclReq, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectStatus.Acl", "OperationFailed.ResourceGroupStatusCheckFail", "SystemBusy", "Throttling"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, removeEntriesFromAclReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, albService.AlbAclStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
}
if len(create) > 0 {
createList := SplitSlice(create, 20)
for _, item := range createList {
addEntriesToAclReq := map[string]interface{}{
"AclId": d.Id(),
}
aclEntriesMaps := make([]map[string]interface{}, 0)
for _, aclEntries := range item {
aclEntriesArg := aclEntries.(map[string]interface{})
aclEntriesMap := map[string]interface{}{}
aclEntriesMap["Description"] = aclEntriesArg["description"]
aclEntriesMap["Entry"] = aclEntriesArg["entry"]
aclEntriesMaps = append(aclEntriesMaps, aclEntriesMap)
}
addEntriesToAclReq["AclEntries"] = aclEntriesMaps
if v, ok := d.GetOkExists("dry_run"); ok {
addEntriesToAclReq["DryRun"] = v
}
action := "AddEntriesToAcl"
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("AddEntriesToAcl")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, addEntriesToAclReq, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"OperationFailed.ResourceGroupStatusCheckFail", "SystemBusy", "Throttling"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, addEntriesToAclReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, albService.AlbAclStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
}
d.SetPartial("acl_entries")
}
d.Partial(false)
return resourceAlicloudAlbAclRead(d, meta)
}
func resourceAlicloudAlbAclDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteAcl"
var response map[string]interface{}
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AclId": d.Id(),
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["ClientToken"] = buildClientToken("DeleteAcl")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"OperationFailed.ResourceGroupStatusCheckFail", "SystemBusy", "ResourceInUse.Acl", "IncorrectStatus.Acl"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ResourceNotFound.Acl"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudAlbHealthCheckTemplate() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAlbHealthCheckTemplateCreate,
Read: resourceAlicloudAlbHealthCheckTemplateRead,
Update: resourceAlicloudAlbHealthCheckTemplateUpdate,
Delete: resourceAlicloudAlbHealthCheckTemplateDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(2 * time.Minute),
Delete: schema.DefaultTimeout(2 * time.Minute),
Update: schema.DefaultTimeout(2 * time.Minute),
},
Schema: map[string]*schema.Schema{
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"health_check_codes": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("health_check_protocol"); ok && v.(string) == "HTTP" {
return false
}
return true
},
},
"health_check_connect_port": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(0, 65535),
},
"health_check_host": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringLenBetween(1, 80),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("health_check_protocol"); ok && v.(string) == "HTTP" {
return false
}
return true
},
},
"health_check_http_version": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"HTTP1.0", "HTTP1.1"}, false),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("health_check_protocol"); ok && v.(string) == "HTTP" {
return false
}
return true
},
},
"health_check_interval": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(1, 50),
},
"health_check_method": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"GET", "HEAD"}, false),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("health_check_protocol"); ok && v.(string) == "HTTP" {
return false
}
return true
},
},
"health_check_path": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^\/[A-Za-z0-9\$\-_\.\+\/\&\~\@\:\$\^\'\,]{1,79}$`), "The URL must be 1 to 80 characters in length, and can contain letters, digits, hyphens (-), forward slashes (/), periods (.), percent signs (%), question marks (?), number signs (#), and ampersands (&). "),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("health_check_protocol"); ok && v.(string) == "HTTP" {
return false
}
return true
},
},
"health_check_protocol": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"HTTP", "TCP"}, false),
},
"health_check_template_name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[A-Za-z][A-Za-z0-9\\_\\.\\-]{1,127}$`), "The name must be 2 to 128 characters in length, and can contain letters, digits, periods (.), underscores (_), and hyphens (-). The name must start with a letter."),
},
"health_check_timeout": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(1, 300),
},
"healthy_threshold": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(2, 10),
},
"unhealthy_threshold": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(2, 10),
},
},
}
}
func resourceAlicloudAlbHealthCheckTemplateCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateHealthCheckTemplate"
request := make(map[string]interface{})
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
if m, ok := d.GetOk("health_check_codes"); ok {
for k, v := range m.([]interface{}) {
request[fmt.Sprintf("HealthCheckCodes.%d", k+1)] = v.(string)
}
}
if v, ok := d.GetOk("health_check_connect_port"); ok {
request["HealthCheckConnectPort"] = v
}
if v, ok := d.GetOk("health_check_host"); ok {
request["HealthCheckHost"] = v
}
if v, ok := d.GetOk("health_check_http_version"); ok {
request["HealthCheckHttpVersion"] = v
}
if v, ok := d.GetOk("health_check_interval"); ok {
request["HealthCheckInterval"] = v
}
if v, ok := d.GetOk("health_check_method"); ok {
request["HealthCheckMethod"] = v
}
if v, ok := d.GetOk("health_check_path"); ok {
request["HealthCheckPath"] = v
}
if v, ok := d.GetOk("health_check_protocol"); ok {
request["HealthCheckProtocol"] = v
}
request["HealthCheckTemplateName"] = d.Get("health_check_template_name")
if v, ok := d.GetOk("health_check_timeout"); ok {
request["HealthCheckTimeout"] = v
}
if v, ok := d.GetOk("healthy_threshold"); ok {
request["HealthyThreshold"] = v
}
if v, ok := d.GetOk("unhealthy_threshold"); ok {
request["UnhealthyThreshold"] = v
}
request["ClientToken"] = buildClientToken("CreateHealthCheckTemplate")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IdempotenceProcessing", "QuotaExceeded.HealthCheckTemplatesNum", "SystemBusy"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_alb_health_check_template", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["HealthCheckTemplateId"]))
return resourceAlicloudAlbHealthCheckTemplateRead(d, meta)
}
func resourceAlicloudAlbHealthCheckTemplateRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
albService := AlbService{client}
object, err := albService.DescribeAlbHealthCheckTemplate(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_alb_health_check_template albService.DescribeAlbHealthCheckTemplate Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
if healthCheckCodes, ok := object["HealthCheckCodes"]; ok {
d.Set("health_check_codes", healthCheckCodes)
}
if v, ok := object["HealthCheckConnectPort"]; ok {
d.Set("health_check_connect_port", formatInt(v))
}
if v, ok := object["HealthCheckInterval"]; ok && fmt.Sprint(v) != "0" {
d.Set("health_check_interval", formatInt(v))
}
d.Set("health_check_protocol", object["HealthCheckProtocol"])
if v, ok := object["HealthCheckProtocol"]; ok && fmt.Sprint(v) == "HTTP" {
d.Set("health_check_method", object["HealthCheckMethod"])
d.Set("health_check_path", object["HealthCheckPath"])
d.Set("health_check_host", object["HealthCheckHost"])
d.Set("health_check_http_version", object["HealthCheckHttpVersion"])
}
d.Set("health_check_template_name", object["HealthCheckTemplateName"])
if v, ok := object["HealthCheckTimeout"]; ok && fmt.Sprint(v) != "0" {
d.Set("health_check_timeout", formatInt(v))
}
if v, ok := object["HealthyThreshold"]; ok && fmt.Sprint(v) != "0" {
d.Set("healthy_threshold", formatInt(v))
}
if v, ok := object["UnhealthyThreshold"]; ok && fmt.Sprint(v) != "0" {
d.Set("unhealthy_threshold", formatInt(v))
}
return nil
}
func resourceAlicloudAlbHealthCheckTemplateUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
update := false
request := map[string]interface{}{
"HealthCheckTemplateId": d.Id(),
}
if d.HasChange("health_check_codes") {
update = true
if m, ok := d.GetOk("health_check_codes"); ok {
for k, v := range m.([]interface{}) {
request[fmt.Sprintf("HealthCheckCodes.%d", k+1)] = v.(string)
}
}
}
if d.HasChange("health_check_connect_port") {
update = true
if v, ok := d.GetOkExists("health_check_connect_port"); ok {
request["HealthCheckConnectPort"] = v
}
}
if d.HasChange("health_check_host") {
update = true
if v, ok := d.GetOk("health_check_host"); ok {
request["HealthCheckHost"] = v
}
}
if d.HasChange("health_check_http_version") {
update = true
if v, ok := d.GetOk("health_check_http_version"); ok {
request["HealthCheckHttpVersion"] = v
}
}
if d.HasChange("health_check_interval") {
update = true
if v, ok := d.GetOk("health_check_interval"); ok {
request["HealthCheckInterval"] = v
}
}
if d.HasChange("health_check_method") {
update = true
if v, ok := d.GetOk("health_check_method"); ok {
request["HealthCheckMethod"] = v
}
}
if d.HasChange("health_check_path") {
update = true
if v, ok := d.GetOk("health_check_path"); ok {
request["HealthCheckPath"] = v
}
}
if d.HasChange("health_check_protocol") {
update = true
if v, ok := d.GetOk("health_check_protocol"); ok {
request["HealthCheckProtocol"] = v
}
}
if d.HasChange("health_check_template_name") {
update = true
request["HealthCheckTemplateName"] = d.Get("health_check_template_name")
}
if d.HasChange("health_check_timeout") {
update = true
if v, ok := d.GetOk("health_check_timeout"); ok {
request["HealthCheckTimeout"] = v
}
}
if d.HasChange("healthy_threshold") {
update = true
if v, ok := d.GetOk("healthy_threshold"); ok {
request["HealthyThreshold"] = v
}
}
if d.HasChange("unhealthy_threshold") {
update = true
if v, ok := d.GetOk("unhealthy_threshold"); ok {
request["UnhealthyThreshold"] = v
}
}
if update {
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
action := "UpdateHealthCheckTemplateAttribute"
request["ClientToken"] = buildClientToken("UpdateHealthCheckTemplateAttribute")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IdempotenceProcessing", "IncorrectStatus.HealthCheckTemplate", "SystemBusy"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudAlbHealthCheckTemplateRead(d, meta)
}
func resourceAlicloudAlbHealthCheckTemplateDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteHealthCheckTemplates"
var response map[string]interface{}
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"HealthCheckTemplateIds.1": d.Id(),
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["ClientToken"] = buildClientToken("DeleteHealthCheckTemplates")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IdempotenceProcessing", "IncorrectStatus.HealthCheckTemplate", "SystemBusy"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudAlbListener() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAlbListenerCreate,
Read: resourceAlicloudAlbListenerRead,
Update: resourceAlicloudAlbListenerUpdate,
Delete: resourceAlicloudAlbListenerDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(2 * time.Minute),
Delete: schema.DefaultTimeout(2 * time.Minute),
Update: schema.DefaultTimeout(2 * time.Minute),
},
Schema: map[string]*schema.Schema{
"access_log_record_customized_headers_enabled": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"certificates": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"certificate_id": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"access_log_tracing_config": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"tracing_enabled": {
Type: schema.TypeBool,
Optional: true,
},
"tracing_sample": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(1, 10000),
},
"tracing_type": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"acl_config": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"acl_relations": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"acl_id": {
Type: schema.TypeString,
Optional: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"acl_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"White", "Black"}, false),
},
},
},
},
"default_actions": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"type": {
Type: schema.TypeString,
Required: true,
},
"forward_group_config": {
Type: schema.TypeSet,
Required: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"server_group_tuples": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"server_group_id": {
Type: schema.TypeString,
Required: true,
},
},
},
},
},
},
},
},
},
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"gzip_enabled": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"http2_enabled": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("listener_protocol"); ok && v.(string) == "HTTPS" {
return false
}
return true
},
},
"idle_timeout": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(1, 60),
},
"listener_description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^([^\x00-\xff]|[\w.,;/@-]){2,256}$`), "\t\nThe description of the listener.\n\nThe description must be 2 to 256 characters in length. The name can contain only the characters in the following string: /^([^\\x00-\\xff]|[\\w.,;/@-]){2,256}$/."),
},
"listener_port": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
ValidateFunc: validation.IntBetween(1, 65535),
},
"listener_protocol": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"HTTP", "HTTPS", "QUIC"}, false),
},
"load_balancer_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"quic_config": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"quic_listener_id": {
Type: schema.TypeString,
Optional: true,
},
"quic_upgrade_enabled": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("listener_protocol"); ok && v.(string) == "HTTPS" {
return false
}
return true
},
},
},
},
},
"request_timeout": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(1, 180),
},
"security_policy_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("listener_protocol"); ok && v.(string) == "HTTPS" {
return false
}
return true
},
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Running", "Stopped"}, false),
},
"xforwarded_for_config": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
MaxItems: 1,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("listener_protocol"); ok && v.(string) == "HTTPS" {
return false
}
return true
},
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"xforwardedforclientcert_issuerdnalias": {
Type: schema.TypeString,
Optional: true,
},
"xforwardedforclientcert_issuerdnenabled": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"xforwardedforclientcertclientverifyalias": {
Type: schema.TypeString,
Optional: true,
},
"xforwardedforclientcertclientverifyenabled": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"xforwardedforclientcertfingerprintalias": {
Type: schema.TypeString,
Optional: true,
},
"xforwardedforclientcertfingerprintenabled": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"xforwardedforclientcertsubjectdnalias": {
Type: schema.TypeString,
Optional: true,
},
"xforwardedforclientcertsubjectdnenabled": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"xforwardedforclientsrcportenabled": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"xforwardedforenabled": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"xforwardedforprotoenabled": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"xforwardedforslbidenabled": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"xforwardedforslbportenabled": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
},
},
},
},
}
}
func resourceAlicloudAlbListenerCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateListener"
request := make(map[string]interface{})
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("certificates"); ok {
certificatesMaps := make([]map[string]interface{}, 0)
for _, certificates := range v.(*schema.Set).List() {
certificatesArg := certificates.(map[string]interface{})
certificatesMap := map[string]interface{}{}
certificatesMap["CertificateId"] = certificatesArg["certificate_id"]
certificatesMaps = append(certificatesMaps, certificatesMap)
}
request["Certificates"] = certificatesMaps
}
defaultActionsMaps := make([]map[string]interface{}, 0)
for _, defaultActions := range d.Get("default_actions").(*schema.Set).List() {
defaultActionsArg := defaultActions.(map[string]interface{})
defaultActionsMap := map[string]interface{}{}
defaultActionsMap["Type"] = defaultActionsArg["type"]
forwardGroupConfigMap := map[string]interface{}{}
for _, forwardGroupConfig := range defaultActionsArg["forward_group_config"].(*schema.Set).List() {
forwardGroupConfigArg := forwardGroupConfig.(map[string]interface{})
serverGroupTuplesMaps := make([]map[string]interface{}, 0)
for _, serverGroupTuples := range forwardGroupConfigArg["server_group_tuples"].(*schema.Set).List() {
serverGroupTuplesArg := serverGroupTuples.(map[string]interface{})
serverGroupTuplesMap := map[string]interface{}{}
serverGroupTuplesMap["ServerGroupId"] = serverGroupTuplesArg["server_group_id"]
serverGroupTuplesMaps = append(serverGroupTuplesMaps, serverGroupTuplesMap)
}
forwardGroupConfigMap["ServerGroupTuples"] = serverGroupTuplesMaps
}
defaultActionsMap["ForwardGroupConfig"] = forwardGroupConfigMap
defaultActionsMaps = append(defaultActionsMaps, defaultActionsMap)
}
request["DefaultActions"] = defaultActionsMaps
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
if v, ok := d.GetOkExists("gzip_enabled"); ok {
request["GzipEnabled"] = v
}
if v, ok := d.GetOkExists("http2_enabled"); ok {
request["Http2Enabled"] = v
}
if v, ok := d.GetOk("idle_timeout"); ok {
request["IdleTimeout"] = v
}
if v, ok := d.GetOk("listener_description"); ok {
request["ListenerDescription"] = v
}
request["ListenerPort"] = d.Get("listener_port")
request["ListenerProtocol"] = d.Get("listener_protocol")
request["LoadBalancerId"] = d.Get("load_balancer_id")
if v, ok := d.GetOk("request_timeout"); ok {
request["RequestTimeout"] = v
}
if v, ok := d.GetOk("security_policy_id"); ok {
request["SecurityPolicyId"] = v
}
if v, ok := d.GetOk("xforwarded_for_config"); ok {
xforwardedForConfigMap := map[string]interface{}{}
for _, xforwardedForConfig := range v.(*schema.Set).List() {
xforwardedForConfigArg := xforwardedForConfig.(map[string]interface{})
xforwardedForConfigMap["XForwardedForClientCertIssuerDNAlias"] = xforwardedForConfigArg["xforwardedforclientcert_issuerdnalias"]
xforwardedForConfigMap["XForwardedForClientCertIssuerDNEnabled"] = xforwardedForConfigArg["xforwardedforclientcert_issuerdnenabled"]
xforwardedForConfigMap["XForwardedForClientCertClientVerifyAlias"] = xforwardedForConfigArg["xforwardedforclientcertclientverifyalias"]
xforwardedForConfigMap["XForwardedForClientCertClientVerifyEnabled"] = xforwardedForConfigArg["xforwardedforclientcertclientverifyenabled"]
xforwardedForConfigMap["XForwardedForClientCertFingerprintAlias"] = xforwardedForConfigArg["xforwardedforclientcertfingerprintalias"]
xforwardedForConfigMap["XForwardedForClientCertFingerprintEnabled"] = xforwardedForConfigArg["xforwardedforclientcertfingerprintenabled"]
xforwardedForConfigMap["XForwardedForClientCertSubjectDNAlias"] = xforwardedForConfigArg["xforwardedforclientcertsubjectdnalias"]
xforwardedForConfigMap["XForwardedForClientCertSubjectDNEnabled"] = xforwardedForConfigArg["xforwardedforclientcertsubjectdnenabled"]
xforwardedForConfigMap["XForwardedForClientSrcPortEnabled"] = xforwardedForConfigArg["xforwardedforclientsrcportenabled"]
xforwardedForConfigMap["XForwardedForEnabled"] = xforwardedForConfigArg["xforwardedforenabled"]
xforwardedForConfigMap["XForwardedForProtoEnabled"] = xforwardedForConfigArg["xforwardedforprotoenabled"]
xforwardedForConfigMap["XForwardedForSLBIdEnabled"] = xforwardedForConfigArg["xforwardedforslbidenabled"]
xforwardedForConfigMap["XForwardedForSLBPortEnabled"] = xforwardedForConfigArg["xforwardedforslbportenabled"]
}
request["XForwardedForConfig"] = xforwardedForConfigMap
}
request["ClientToken"] = buildClientToken("CreateListener")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IdempotenceProcessing", "IncorrectBusinessStatus.LoadBalancer", "SystemBusy", "Throttling"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_alb_listener", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["ListenerId"]))
albService := AlbService{client}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, albService.AlbListenerStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudAlbListenerUpdate(d, meta)
}
func resourceAlicloudAlbListenerRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
albService := AlbService{client}
object, err := albService.DescribeAlbListener(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_alb_listener albService.DescribeAlbListener Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("access_log_record_customized_headers_enabled", object["LogConfig"].(map[string]interface{})["AccessLogRecordCustomizedHeadersEnabled"])
accessLogTracingConfigSli := make([]map[string]interface{}, 0)
if accessLogTracingConfig, ok := object["LogConfig"].(map[string]interface{})["AccessLogTracingConfig"]; ok && len(accessLogTracingConfig.(map[string]interface{})) > 0 {
accessLogTracingConfigMap := make(map[string]interface{})
accessLogTracingConfigMap["tracing_enabled"] = accessLogTracingConfig.(map[string]interface{})["TracingEnabled"]
accessLogTracingConfigMap["tracing_sample"] = accessLogTracingConfig.(map[string]interface{})["TracingSample"]
accessLogTracingConfigMap["tracing_type"] = accessLogTracingConfig.(map[string]interface{})["TracingType"]
accessLogTracingConfigSli = append(accessLogTracingConfigSli, accessLogTracingConfigMap)
}
d.Set("access_log_tracing_config", accessLogTracingConfigSli)
aclConfigSli := make([]map[string]interface{}, 0)
if aclConfig, ok := object["AclConfig"]; ok && len(aclConfig.(map[string]interface{})) > 0 {
aclConfigMap := make(map[string]interface{})
aclRelationsSli := make([]map[string]interface{}, 0)
if v, ok := aclConfig.(map[string]interface{})["AclRelations"]; ok && len(v.([]interface{})) > 0 {
for _, aclRelations := range v.([]interface{}) {
aclRelationsMap := make(map[string]interface{})
aclRelationsMap["acl_id"] = aclRelations.(map[string]interface{})["AclId"]
aclRelationsMap["status"] = aclRelations.(map[string]interface{})["Status"]
aclRelationsSli = append(aclRelationsSli, aclRelationsMap)
}
}
aclConfigMap["acl_relations"] = aclRelationsSli
aclConfigMap["acl_type"] = aclConfig.(map[string]interface{})["AclType"]
aclConfigSli = append(aclConfigSli, aclConfigMap)
}
d.Set("acl_config", aclConfigSli)
if certificatesList, ok := object["Certificates"]; ok && certificatesList != nil {
certificatesMaps := make([]map[string]interface{}, 0)
for _, certificatesListItem := range certificatesList.([]interface{}) {
if certificatesListItemArg, ok := certificatesListItem.(map[string]interface{}); ok {
certificatesListItemMap := map[string]interface{}{}
certificatesListItemMap["certificate_id"] = certificatesListItemArg["CertificateId"]
certificatesMaps = append(certificatesMaps, certificatesListItemMap)
}
}
d.Set("certificates", certificatesMaps)
}
if defaultActionsList, ok := object["DefaultActions"]; ok && defaultActionsList != nil {
defaultActionsMaps := make([]map[string]interface{}, 0)
for _, defaultActions := range defaultActionsList.([]interface{}) {
defaultActionsArg := defaultActions.(map[string]interface{})
defaultActionsMap := map[string]interface{}{}
defaultActionsMap["type"] = defaultActionsArg["Type"]
forwardGroupConfig := defaultActionsArg["ForwardGroupConfig"]
forwardGroupConfigArg := forwardGroupConfig.(map[string]interface{})
serverGroupTuplesMaps := make([]map[string]interface{}, 0)
for _, serverGroupTuples := range forwardGroupConfigArg["ServerGroupTuples"].([]interface{}) {
serverGroupTuplesArg := serverGroupTuples.(map[string]interface{})
serverGroupTuplesMap := map[string]interface{}{}
serverGroupTuplesMap["server_group_id"] = serverGroupTuplesArg["ServerGroupId"]
serverGroupTuplesMaps = append(serverGroupTuplesMaps, serverGroupTuplesMap)
}
forwardGroupConfigMaps := make([]map[string]interface{}, 0)
forwardGroupConfigMap := map[string]interface{}{}
forwardGroupConfigMap["server_group_tuples"] = serverGroupTuplesMaps
forwardGroupConfigMaps = append(forwardGroupConfigMaps, forwardGroupConfigMap)
defaultActionsMap["forward_group_config"] = forwardGroupConfigMaps
defaultActionsMaps = append(defaultActionsMaps, defaultActionsMap)
}
d.Set("default_actions", defaultActionsMaps)
}
d.Set("gzip_enabled", object["GzipEnabled"])
d.Set("http2_enabled", object["Http2Enabled"])
if v, ok := object["IdleTimeout"]; ok && fmt.Sprint(v) != "0" {
d.Set("idle_timeout", formatInt(v))
}
d.Set("listener_description", object["ListenerDescription"])
if v, ok := object["ListenerPort"]; ok && fmt.Sprint(v) != "0" {
d.Set("listener_port", formatInt(v))
}
d.Set("listener_protocol", object["ListenerProtocol"])
d.Set("load_balancer_id", object["LoadBalancerId"])
d.Set("status", object["ListenerStatus"])
if quicConfig, ok := object["QuicConfig"]; ok {
quicConfigSli := make([]map[string]interface{}, 0)
if len(quicConfig.(map[string]interface{})) > 0 {
quicConfigMap := make(map[string]interface{})
quicConfigMap["quic_listener_id"] = quicConfig.(map[string]interface{})["QuicListenerId"]
quicConfigMap["quic_upgrade_enabled"] = quicConfig.(map[string]interface{})["QuicUpgradeEnabled"]
quicConfigSli = append(quicConfigSli, quicConfigMap)
}
d.Set("quic_config", quicConfigSli)
}
if v, ok := object["RequestTimeout"]; ok && fmt.Sprint(v) != "0" {
d.Set("request_timeout", formatInt(v))
}
d.Set("security_policy_id", object["SecurityPolicyId"])
if xforwardedForConfig, ok := object["XForwardedForConfig"]; ok && len(xforwardedForConfig.(map[string]interface{})) > 0 {
xforwardedForConfigSli := make([]map[string]interface{}, 0)
xforwardedForConfigMap := make(map[string]interface{})
xforwardedForConfigMap["xforwardedforclientcert_issuerdnalias"] = xforwardedForConfig.(map[string]interface{})["XForwardedForClientCertIssuerDNAlias"]
xforwardedForConfigMap["xforwardedforclientcert_issuerdnenabled"] = xforwardedForConfig.(map[string]interface{})["XForwardedForClientCertIssuerDNEnabled"]
xforwardedForConfigMap["xforwardedforclientcertclientverifyalias"] = xforwardedForConfig.(map[string]interface{})["XForwardedForClientCertClientVerifyAlias"]
xforwardedForConfigMap["xforwardedforclientcertclientverifyenabled"] = xforwardedForConfig.(map[string]interface{})["XForwardedForClientCertClientVerifyEnabled"]
xforwardedForConfigMap["xforwardedforclientcertfingerprintalias"] = xforwardedForConfig.(map[string]interface{})["XForwardedForClientCertFingerprintAlias"]
xforwardedForConfigMap["xforwardedforclientcertfingerprintenabled"] = xforwardedForConfig.(map[string]interface{})["XForwardedForClientCertFingerprintEnabled"]
xforwardedForConfigMap["xforwardedforclientcertsubjectdnalias"] = xforwardedForConfig.(map[string]interface{})["XForwardedForClientCertSubjectDNAlias"]
xforwardedForConfigMap["xforwardedforclientcertsubjectdnenabled"] = xforwardedForConfig.(map[string]interface{})["XForwardedForClientCertSubjectDNEnabled"]
xforwardedForConfigMap["xforwardedforclientsrcportenabled"] = xforwardedForConfig.(map[string]interface{})["XForwardedForClientSrcPortEnabled"]
xforwardedForConfigMap["xforwardedforenabled"] = xforwardedForConfig.(map[string]interface{})["XForwardedForEnabled"]
xforwardedForConfigMap["xforwardedforprotoenabled"] = xforwardedForConfig.(map[string]interface{})["XForwardedForProtoEnabled"]
xforwardedForConfigMap["xforwardedforslbidenabled"] = xforwardedForConfig.(map[string]interface{})["XForwardedForSLBIdEnabled"]
xforwardedForConfigMap["xforwardedforslbportenabled"] = xforwardedForConfig.(map[string]interface{})["XForwardedForSLBPortEnabled"]
xforwardedForConfigSli = append(xforwardedForConfigSli, xforwardedForConfigMap)
d.Set("xforwarded_for_config", xforwardedForConfigSli)
}
return nil
}
func resourceAlicloudAlbListenerUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
albService := AlbService{client}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"ListenerId": d.Id(),
}
if d.HasChange("access_log_record_customized_headers_enabled") || d.IsNewResource() {
if v, ok := d.GetOkExists("access_log_record_customized_headers_enabled"); ok {
update = true
request["AccessLogRecordCustomizedHeadersEnabled"] = v
}
}
if d.HasChange("access_log_tracing_config") {
if v, ok := d.GetOk("access_log_tracing_config"); ok {
update = true
accessLogTracingConfigMap := map[string]interface{}{}
for _, certificates := range v.(*schema.Set).List() {
certificatesArg := certificates.(map[string]interface{})
accessLogTracingConfigMap["TracingEnabled"] = certificatesArg["tracing_enabled"]
accessLogTracingConfigMap["TracingSample"] = certificatesArg["tracing_sample"]
accessLogTracingConfigMap["TracingType"] = certificatesArg["tracing_type"]
}
request["AccessLogTracingConfig"] = accessLogTracingConfigMap
}
}
if update {
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
action := "UpdateListenerLogConfig"
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("UpdateListenerLogConfig")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IdempotenceProcessing", "IncorrectBusinessStatus.LoadBalancer", "SystemBusy", "Throttling"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, albService.AlbListenerStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("access_log_record_customized_headers_enabled")
d.SetPartial("access_log_tracing_config")
}
update = false
updateListenerAttributeReq := map[string]interface{}{
"ListenerId": d.Id(),
}
if d.HasChange("certificates") {
update = true
if v, ok := d.GetOk("certificates"); ok {
certificatesMaps := make([]map[string]interface{}, 0)
for _, certificates := range v.(*schema.Set).List() {
certificatesArg := certificates.(map[string]interface{})
certificatesMap := map[string]interface{}{}
certificatesMap["CertificateId"] = certificatesArg["certificate_id"]
certificatesMaps = append(certificatesMaps, certificatesMap)
}
updateListenerAttributeReq["Certificates"] = certificatesMaps
}
}
if !d.IsNewResource() && d.HasChange("default_actions") {
update = true
defaultActionsMaps := make([]map[string]interface{}, 0)
for _, defaultActions := range d.Get("default_actions").(*schema.Set).List() {
defaultActionsArg := defaultActions.(map[string]interface{})
defaultActionsMap := map[string]interface{}{}
defaultActionsMap["Type"] = defaultActionsArg["type"]
forwardGroupConfigMap := map[string]interface{}{}
for _, forwardGroupConfig := range defaultActionsArg["forward_group_config"].(*schema.Set).List() {
forwardGroupConfigArg := forwardGroupConfig.(map[string]interface{})
serverGroupTuplesMaps := make([]map[string]interface{}, 0)
for _, serverGroupTuples := range forwardGroupConfigArg["server_group_tuples"].(*schema.Set).List() {
serverGroupTuplesArg := serverGroupTuples.(map[string]interface{})
serverGroupTuplesMap := map[string]interface{}{}
serverGroupTuplesMap["ServerGroupId"] = serverGroupTuplesArg["server_group_id"]
serverGroupTuplesMaps = append(serverGroupTuplesMaps, serverGroupTuplesMap)
}
forwardGroupConfigMap["ServerGroupTuples"] = serverGroupTuplesMaps
}
defaultActionsMap["ForwardGroupConfig"] = forwardGroupConfigMap
defaultActionsMaps = append(defaultActionsMaps, defaultActionsMap)
}
updateListenerAttributeReq["DefaultActions"] = defaultActionsMaps
}
if !d.IsNewResource() && d.HasChange("server_group_id") {
update = true
updateListenerAttributeReq["DefaultActions.*.ForwardGroupConfig.ServerGroupTuples.*.ServerGroupId"] = d.Get("server_group_id")
}
if !d.IsNewResource() && d.HasChange("type") {
update = true
updateListenerAttributeReq["DefaultActions.*.Type"] = d.Get("type")
}
if !d.IsNewResource() && d.HasChange("gzip_enabled") {
update = true
if v, ok := d.GetOkExists("gzip_enabled"); ok {
updateListenerAttributeReq["GzipEnabled"] = v
}
}
if !d.IsNewResource() && d.HasChange("http2_enabled") {
update = true
if v, ok := d.GetOkExists("http2_enabled"); ok {
updateListenerAttributeReq["Http2Enabled"] = v
}
}
if !d.IsNewResource() && d.HasChange("idle_timeout") {
update = true
if v, ok := d.GetOk("idle_timeout"); ok {
updateListenerAttributeReq["IdleTimeout"] = v
}
}
if !d.IsNewResource() && d.HasChange("listener_description") {
update = true
if v, ok := d.GetOk("listener_description"); ok {
updateListenerAttributeReq["ListenerDescription"] = v
}
}
if d.HasChange("quic_config") {
if v, ok := d.GetOk("quic_config"); ok {
update = true
quicConfigMap := map[string]interface{}{}
for _, quicConfig := range v.(*schema.Set).List() {
quicConfigArg := quicConfig.(map[string]interface{})
quicConfigMap["QuicListenerId"] = quicConfigArg["quic_listener_id"]
quicConfigMap["QuicUpgradeEnabled"] = quicConfigArg["quic_upgrade_enabled"]
}
updateListenerAttributeReq["QuicConfig"] = quicConfigMap
}
}
if !d.IsNewResource() && d.HasChange("request_timeout") {
update = true
if v, ok := d.GetOk("request_timeout"); ok {
updateListenerAttributeReq["RequestTimeout"] = v
}
}
if !d.IsNewResource() && d.HasChange("security_policy_id") {
update = true
if v, ok := d.GetOk("security_policy_id"); ok {
updateListenerAttributeReq["SecurityPolicyId"] = v
}
}
if !d.IsNewResource() && d.HasChange("xforwarded_for_config") {
update = true
if v, ok := d.GetOk("xforwarded_for_config"); ok {
xforwardedForConfigMap := map[string]interface{}{}
for _, xforwardedForConfig := range v.(*schema.Set).List() {
xforwardedForConfigArg := xforwardedForConfig.(map[string]interface{})
xforwardedForConfigMap["XForwardedForClientCertIssuerDNAlias"] = xforwardedForConfigArg["xforwardedforclientcert_issuerdnalias"]
xforwardedForConfigMap["XForwardedForClientCertIssuerDNEnabled"] = xforwardedForConfigArg["xforwardedforclientcert_issuerdnenabled"]
xforwardedForConfigMap["XForwardedForClientCertClientVerifyAlias"] = xforwardedForConfigArg["xforwardedforclientcertclientverifyalias"]
xforwardedForConfigMap["XForwardedForClientCertClientVerifyEnabled"] = xforwardedForConfigArg["xforwardedforclientcertclientverifyenabled"]
xforwardedForConfigMap["XForwardedForClientCertFingerprintAlias"] = xforwardedForConfigArg["xforwardedforclientcertfingerprintalias"]
xforwardedForConfigMap["XForwardedForClientCertFingerprintEnabled"] = xforwardedForConfigArg["xforwardedforclientcertfingerprintenabled"]
xforwardedForConfigMap["XForwardedForClientCertSubjectDNAlias"] = xforwardedForConfigArg["xforwardedforclientcertsubjectdnalias"]
xforwardedForConfigMap["XForwardedForClientCertSubjectDNEnabled"] = xforwardedForConfigArg["xforwardedforclientcertsubjectdnenabled"]
xforwardedForConfigMap["XForwardedForClientSrcPortEnabled"] = xforwardedForConfigArg["xforwardedforclientsrcportenabled"]
xforwardedForConfigMap["XForwardedForEnabled"] = xforwardedForConfigArg["xforwardedforenabled"]
xforwardedForConfigMap["XForwardedForProtoEnabled"] = xforwardedForConfigArg["xforwardedforprotoenabled"]
xforwardedForConfigMap["XForwardedForSLBIdEnabled"] = xforwardedForConfigArg["xforwardedforslbidenabled"]
xforwardedForConfigMap["XForwardedForSLBPortEnabled"] = xforwardedForConfigArg["xforwardedforslbportenabled"]
}
updateListenerAttributeReq["XForwardedForConfig"] = xforwardedForConfigMap
}
}
if update {
if v, ok := d.GetOkExists("dry_run"); ok {
updateListenerAttributeReq["DryRun"] = v
}
action := "UpdateListenerAttribute"
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
updateListenerAttributeReq["ClientToken"] = buildClientToken("UpdateListenerAttribute")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, updateListenerAttributeReq, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IdempotenceProcessing", "IncorrectBusinessStatus.LoadBalancer", "SystemBusy", "Throttling"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, updateListenerAttributeReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running", "Stopped"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, albService.AlbListenerStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("certificates")
d.SetPartial("default_actions")
d.SetPartial("server_group_id")
d.SetPartial("type")
d.SetPartial("gzip_enabled")
d.SetPartial("http2_enabled")
d.SetPartial("idle_timeout")
d.SetPartial("listener_description")
d.SetPartial("quic_config")
d.SetPartial("request_timeout")
d.SetPartial("security_policy_id")
d.SetPartial("xforwarded_for_config")
}
if d.HasChange("status") {
object, err := albService.DescribeAlbListener(d.Id())
if err != nil {
return WrapError(err)
}
target := d.Get("status").(string)
if object["ListenerStatus"].(string) != target {
if target == "Running" {
request := map[string]interface{}{
"ListenerId": d.Id(),
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
action := "StartListener"
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("StartListener")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IdempotenceProcessing", "IncorrectBusinessStatus.LoadBalancer", "SystemBusy", "Throttling"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, albService.AlbListenerStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if target == "Stopped" {
request := map[string]interface{}{
"ListenerId": d.Id(),
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
action := "StopListener"
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("StopListener")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IdempotenceProcessing", "IncorrectBusinessStatus.LoadBalancer", "SystemBusy", "Throttling"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Stopped"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, albService.AlbListenerStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.SetPartial("status")
}
}
d.Partial(false)
if d.HasChange("acl_config") {
oldAssociateAcls, newAssociateVpcs := d.GetChange("acl_config")
oldAssociateAclsSet := oldAssociateAcls.(*schema.Set)
newAssociateAclsSet := newAssociateVpcs.(*schema.Set)
removed := oldAssociateAclsSet.Difference(newAssociateAclsSet)
added := newAssociateAclsSet.Difference(oldAssociateAclsSet)
if removed.Len() > 0 {
action := "DissociateAclsFromListener"
dissociateAclsFromListenerReq := map[string]interface{}{
"ListenerId": d.Id(),
}
dissociateAclsFromListenerReq["ClientToken"] = buildClientToken("DissociateAclsFromListener")
associateAclIds := make([]string, 0)
for _, aclConfig := range removed.List() {
if aclRelationsMaps, ok := aclConfig.(map[string]interface{})["acl_relations"]; ok {
for _, aclRelationsMap := range aclRelationsMaps.(*schema.Set).List() {
associateAclIds = append(associateAclIds, aclRelationsMap.(map[string]interface{})["acl_id"].(string))
}
}
}
dissociateAclsFromListenerReq["AclIds"] = associateAclIds
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, dissociateAclsFromListenerReq, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, dissociateAclsFromListenerReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, albService.AlbListenerStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if added.Len() > 0 {
action := "AssociateAclsWithListener"
associateAclsWithListenerReq := map[string]interface{}{
"ListenerId": d.Id(),
}
associateAclsWithListenerReq["ClientToken"] = buildClientToken("AssociateAclsWithListener")
associateAclIds := make([]string, 0)
for _, aclConfig := range added.List() {
if aclRelationsMaps, ok := aclConfig.(map[string]interface{})["acl_relations"]; ok {
for _, aclRelationsMap := range aclRelationsMaps.(*schema.Set).List() {
associateAclIds = append(associateAclIds, aclRelationsMap.(map[string]interface{})["acl_id"].(string))
}
}
associateAclsWithListenerReq["AclType"] = aclConfig.(map[string]interface{})["acl_type"]
}
associateAclsWithListenerReq["AclIds"] = associateAclIds
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, associateAclsWithListenerReq, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, associateAclsWithListenerReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, albService.AlbListenerStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
}
return resourceAlicloudAlbListenerRead(d, meta)
}
func resourceAlicloudAlbListenerDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteListener"
var response map[string]interface{}
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ListenerId": d.Id(),
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["ClientToken"] = buildClientToken("DeleteListener")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IdempotenceProcessing", "ResourceInConfiguring.Listener", "IncorrectBusinessStatus.LoadBalancer", "SystemBusy", "Throttling", "-22031"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ResourceNotFound.Listener", "ResourceNotFound.LoadBalancer"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"strconv"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudAlbLoadBalancer() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAlbLoadBalancerCreate,
Read: resourceAlicloudAlbLoadBalancerRead,
Update: resourceAlicloudAlbLoadBalancerUpdate,
Delete: resourceAlicloudAlbLoadBalancerDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(2 * time.Minute),
Delete: schema.DefaultTimeout(2 * time.Minute),
Update: schema.DefaultTimeout(2 * time.Minute),
},
Schema: map[string]*schema.Schema{
"access_log_config": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"log_project": {
Type: schema.TypeString,
Optional: true,
},
"log_store": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"address_allocated_mode": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Dynamic", "Fixed"}, false),
},
"address_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Intranet", "Internet"}, false),
},
"deletion_protection_enabled": {
Type: schema.TypeBool,
Optional: true,
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"load_balancer_billing_config": {
Type: schema.TypeSet,
Required: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"pay_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo"}, false),
},
},
},
ForceNew: true,
},
"load_balancer_edition": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"Basic", "Standard"}, false),
},
"load_balancer_name": {
Type: schema.TypeString,
Required: true,
},
"modification_protection_config": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"reason": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9_\-.]{1,127}$`), "The reason must be 2 to 128 characters in length, and must start with a letter. It can contain digits, periods (.), underscores (_), and hyphens (-)."),
DiffSuppressFunc: modificationProtectionConfigDiffSuppressFunc,
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"ConsoleProtection", "NonProtection"}, false),
},
},
},
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
"vpc_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"zone_mappings": {
Type: schema.TypeSet,
Required: true,
MinItems: 2,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"vswitch_id": {
Type: schema.TypeString,
Required: true,
},
"zone_id": {
Type: schema.TypeString,
Required: true,
},
},
},
ForceNew: true,
},
},
}
}
func resourceAlicloudAlbLoadBalancerCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateLoadBalancer"
request := make(map[string]interface{})
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("address_allocated_mode"); ok {
request["AddressAllocatedMode"] = v
}
request["AddressType"] = d.Get("address_type")
if v, ok := d.GetOkExists("deletion_protection_enabled"); ok {
request["DeletionProtectionEnabled"] = v
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["LoadBalancerEdition"] = d.Get("load_balancer_edition")
request["LoadBalancerName"] = d.Get("load_balancer_name")
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
request["VpcId"] = d.Get("vpc_id")
zoneMappingsMaps := make([]map[string]interface{}, 0)
for _, zoneMappings := range d.Get("zone_mappings").(*schema.Set).List() {
zoneMappingsArg := zoneMappings.(map[string]interface{})
zoneMappingsMap := map[string]interface{}{}
zoneMappingsMap["VSwitchId"] = zoneMappingsArg["vswitch_id"]
zoneMappingsMap["ZoneId"] = zoneMappingsArg["zone_id"]
zoneMappingsMaps = append(zoneMappingsMaps, zoneMappingsMap)
}
request["ZoneMappings"] = zoneMappingsMaps
loadBalancerBillingConfigMap := map[string]interface{}{}
for _, loadBalancerBillingConfigs := range d.Get("load_balancer_billing_config").(*schema.Set).List() {
loadBalancerBillingConfigArg := loadBalancerBillingConfigs.(map[string]interface{})
loadBalancerBillingConfigMap["PayType"] = convertAlbLoadBalancerPaymentTypeRequest(loadBalancerBillingConfigArg["pay_type"].(string))
}
request["LoadBalancerBillingConfig"] = loadBalancerBillingConfigMap
modificationProtectionConfigMap := map[string]interface{}{}
for _, modificationProtectionConfigs := range d.Get("modification_protection_config").(*schema.Set).List() {
modificationProtectionConfigArg := modificationProtectionConfigs.(map[string]interface{})
modificationProtectionConfigMap["Reason"] = modificationProtectionConfigArg["reason"]
modificationProtectionConfigMap["Status"] = modificationProtectionConfigArg["status"]
}
request["ModificationProtectionConfig"] = modificationProtectionConfigMap
request["ClientToken"] = buildClientToken("CreateLoadBalancer")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IdempotenceProcessing", "SystemBusy", "Throttling"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_alb_load_balancer", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["LoadBalancerId"]))
albService := AlbService{client}
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, albService.AlbLoadBalancerStateRefreshFunc(d.Id(), []string{"CreateFailed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudAlbLoadBalancerUpdate(d, meta)
}
func resourceAlicloudAlbLoadBalancerRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
albService := AlbService{client}
object, err := albService.DescribeAlbLoadBalancer(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_alb_load_balancer albService.DescribeAlbLoadBalancer Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
accessLogConfigSli := make([]map[string]interface{}, 0)
if object["AccessLogConfig"] != nil && len(object["AccessLogConfig"].(map[string]interface{})) > 0 {
accessLogConfig := object["AccessLogConfig"].(map[string]interface{})
accessLogConfigMap := make(map[string]interface{})
accessLogConfigMap["log_project"] = accessLogConfig["LogProject"]
accessLogConfigMap["log_store"] = accessLogConfig["LogStore"]
accessLogConfigSli = append(accessLogConfigSli, accessLogConfigMap)
}
d.Set("access_log_config", accessLogConfigSli)
d.Set("address_allocated_mode", object["AddressAllocatedMode"])
d.Set("address_type", object["AddressType"])
loadBalancerBillingConfigSli := make([]map[string]interface{}, 0)
if object["LoadBalancerBillingConfig"] != nil && len(object["LoadBalancerBillingConfig"].(map[string]interface{})) > 0 {
loadBalancerBillingConfig := object["LoadBalancerBillingConfig"]
loadBalancerBillingConfigMap := make(map[string]interface{})
loadBalancerBillingConfigMap["pay_type"] = convertAlbLoadBalancerPaymentTypeResponse(loadBalancerBillingConfig.(map[string]interface{})["PayType"].(string))
loadBalancerBillingConfigSli = append(loadBalancerBillingConfigSli, loadBalancerBillingConfigMap)
}
d.Set("load_balancer_billing_config", loadBalancerBillingConfigSli)
d.Set("load_balancer_edition", object["LoadBalancerEdition"])
d.Set("load_balancer_name", object["LoadBalancerName"])
modificationProtectionConfigSli := make([]map[string]interface{}, 0)
if object["ModificationProtectionConfig"] != nil && len(object["ModificationProtectionConfig"].(map[string]interface{})) > 0 {
modificationProtectionConfig := object["ModificationProtectionConfig"].(map[string]interface{})
modificationProtectionConfigMap := make(map[string]interface{})
modificationProtectionConfigMap["reason"] = modificationProtectionConfig["Reason"]
modificationProtectionConfigMap["status"] = modificationProtectionConfig["Status"]
modificationProtectionConfigSli = append(modificationProtectionConfigSli, modificationProtectionConfigMap)
}
d.Set("modification_protection_config", modificationProtectionConfigSli)
d.Set("resource_group_id", object["ResourceGroupId"])
d.Set("status", object["LoadBalancerStatus"])
d.Set("tags", tagsToMap(object["Tags"]))
d.Set("vpc_id", object["VpcId"])
if zoneMappingsList, ok := object["ZoneMappings"]; ok {
zoneMappingsMaps := make([]map[string]interface{}, 0)
for _, zoneMappingsListItem := range zoneMappingsList.([]interface{}) {
if zoneMappingsListItemMap, ok := zoneMappingsListItem.(map[string]interface{}); ok {
zoneMappingsArg := map[string]interface{}{}
zoneMappingsArg["vswitch_id"] = zoneMappingsListItemMap["VSwitchId"]
zoneMappingsArg["zone_id"] = zoneMappingsListItemMap["ZoneId"]
zoneMappingsMaps = append(zoneMappingsMaps, zoneMappingsArg)
}
}
d.Set("zone_mappings", zoneMappingsMaps)
}
return nil
}
func resourceAlicloudAlbLoadBalancerUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
albService := AlbService{client}
var response map[string]interface{}
d.Partial(true)
if d.HasChange("tags") {
if err := albService.SetResourceTags(d, "loadbalancer"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
update := false
request := map[string]interface{}{
"ResourceId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("resource_group_id") {
update = true
if v, ok := d.GetOk("resource_group_id"); ok {
request["NewResourceGroupId"] = v
}
}
if update {
request["ResourceType"] = "loadbalancer"
action := "MoveResourceGroup"
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, albService.AlbLoadBalancerStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("resource_group_id")
}
update = false
updateLoadBalancerEditionReq := map[string]interface{}{
"LoadBalancerId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("load_balancer_edition") {
update = true
updateLoadBalancerEditionReq["LoadBalancerEdition"] = d.Get("load_balancer_edition")
}
if update {
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
action := "UpdateLoadBalancerEdition"
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("UpdateLoadBalancerEdition")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, updateLoadBalancerEditionReq, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, albService.AlbLoadBalancerStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("load_balancer_edition")
}
if d.HasChange("access_log_config") {
oraw, _ := d.GetChange("access_log_config")
if oraw != nil && oraw.(*schema.Set).Len() > 1 {
disableLoadBalancerAccessLogReq := map[string]interface{}{
"LoadBalancerId": d.Id(),
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
action := "DisableLoadBalancerAccessLog"
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("DisableLoadBalancerAccessLog")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, disableLoadBalancerAccessLogReq, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
} else {
enableLoadBalancerAccessLogReq := map[string]interface{}{
"LoadBalancerId": d.Id(),
}
if v, ok := d.GetOk("access_log_config"); ok {
for _, enableLoadBalancerAccessLogs := range v.(*schema.Set).List() {
enableLoadBalancerAccessArg := enableLoadBalancerAccessLogs.(map[string]interface{})
enableLoadBalancerAccessLogReq["LogProject"] = enableLoadBalancerAccessArg["log_project"]
enableLoadBalancerAccessLogReq["LogStore"] = enableLoadBalancerAccessArg["log_store"]
}
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
action := "EnableLoadBalancerAccessLog"
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("EnableLoadBalancerAccessLog")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, enableLoadBalancerAccessLogReq, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IdempotenceProcessing", "SystemBusy", "Throttling"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, albService.AlbLoadBalancerStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("access_log_config")
}
update = false
updateLoadBalancerAttributeReq := map[string]interface{}{
"LoadBalancerId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("load_balancer_name") {
update = true
if v, ok := d.GetOk("load_balancer_name"); ok {
updateLoadBalancerAttributeReq["LoadBalancerName"] = v
}
}
if !d.IsNewResource() && d.HasChange("modification_protection_config") {
update = true
modificationProtectionConfigMap := map[string]interface{}{}
if v, ok := d.GetOk("modification_protection_config"); ok {
for _, modificationProtectionConfigs := range v.(*schema.Set).List() {
modificationProtectionConfigArg := modificationProtectionConfigs.(map[string]interface{})
modificationProtectionConfigMap["Reason"] = modificationProtectionConfigArg["reason"]
modificationProtectionConfigMap["Status"] = modificationProtectionConfigArg["status"]
}
}
updateLoadBalancerAttributeReq["ModificationProtectionConfig"] = modificationProtectionConfigMap
}
if update {
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
action := "UpdateLoadBalancerAttribute"
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
updateLoadBalancerAttributeReq["ClientToken"] = buildClientToken("UpdateLoadBalancerAttribute")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, updateLoadBalancerAttributeReq, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, albService.AlbLoadBalancerStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("load_balancer_name")
d.SetPartial("modification_protection_config")
}
if d.HasChange("deletion_protection_enabled") {
target := strconv.FormatBool(d.Get("deletion_protection_enabled").(bool))
if target == "false" {
request := map[string]interface{}{
"ResourceId": d.Id(),
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
action := "DisableDeletionProtection"
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("DisableDeletionProtection")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IdempotenceProcessing", "SystemBusy", "Throttling"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, albService.AlbLoadBalancerStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if target == "true" {
request := map[string]interface{}{
"ResourceId": d.Id(),
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
action := "EnableDeletionProtection"
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("EnableDeletionProtection")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IdempotenceProcessing", "SystemBusy", "Throttling"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, albService.AlbLoadBalancerStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.SetPartial("deletion_protection_enabled")
}
d.Partial(false)
return resourceAlicloudAlbLoadBalancerRead(d, meta)
}
func resourceAlicloudAlbLoadBalancerDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteLoadBalancer"
var response map[string]interface{}
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"LoadBalancerId": d.Id(),
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["ClientToken"] = buildClientToken("DeleteLoadBalancer")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IdempotenceProcessing", "ResourceNotFound.LoadBalancer", "SystemBusy", "Throttling"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ResourceNotFound.LoadBalancer"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func convertAlbLoadBalancerPaymentTypeRequest(source interface{}) interface{} {
switch source {
case "PayAsYouGo":
return "PostPay"
}
return source
}
func convertAlbLoadBalancerPaymentTypeResponse(source interface{}) interface{} {
switch source {
case "PostPay":
return "PayAsYouGo"
}
return source
}
func modificationProtectionConfigDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("modification_protection_config"); ok {
val := v.(*schema.Set).List()
if len(val) > 2 {
// modification_protection_config 为 Object 类型
return true
}
for _, modificationProtectionConfigs := range val {
modificationProtectionConfigArg := modificationProtectionConfigs.(map[string]interface{})
return fmt.Sprintf(modificationProtectionConfigArg["status"].(string)) != "ConsoleProtection"
}
}
return true
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudAlbRule() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAlbRuleCreate,
Read: resourceAlicloudAlbRuleRead,
Update: resourceAlicloudAlbRuleUpdate,
Delete: resourceAlicloudAlbRuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(2 * time.Minute),
Delete: schema.DefaultTimeout(2 * time.Minute),
Update: schema.DefaultTimeout(2 * time.Minute),
},
Schema: map[string]*schema.Schema{
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"listener_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"priority": {
Type: schema.TypeInt,
Required: true,
},
"rule_actions": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"fixed_response_config": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"content": {
Type: schema.TypeString,
Required: true,
},
"content_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"text/plain", "text/css", "text/html", "application/javascript", "application/json"}, false),
},
"http_code": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[2-5][0-9]{2}$`), "The http code must be an HTTP_2xx,HTTP_4xx or HTTP_5xx.x is a digit."),
},
},
},
},
"forward_group_config": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"server_group_tuples": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"server_group_id": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
},
},
},
},
},
},
"insert_header_config": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[A-Za-z0-9_-]{1,40}$`), "The name of the header. The name must be 1 to 40 characters in length and can contain letters, digits, underscores (_), and hyphens (-)."),
},
"value": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"ClientSrcPort", "ClientSrcIp", "Protocol", "SLBId", "SLBPort", "UserDefined"}, false),
},
"value_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"UserDefined", "ReferenceHeader", "SystemDefined"}, false),
},
},
},
},
"order": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(1, 50000),
},
"redirect_config": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"host": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-z0-9\-\.\*\?]{3,128}$`), "The host name must be 3 to128 characters in length, and can contain lowercase letters, digits, hyphens (-), periods (.), asterisks (*), and question marks (?)."),
},
"http_code": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"301", "302", "303", "307", "308"}, false),
},
"path": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^\/[A-Za-z0-9\$\-_\.\+\/\&\~\@\:]{1,127}$`), "The value must be 1 to 128 characters in length and must start with a forward slash (/). The value can contain letters, digits, and the following special characters: $ - _ .+ / & ~ @ :. It cannot contain the following special characters: \" % # ; ! ( ) [ ]^ , \". The value is case-sensitive and can contain asterisks (*) and question marks (?)."),
},
"port": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: intBetween(1, 63335),
},
"protocol": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"HTTP", "HTTPS"}, false),
},
"query": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(1, 128),
},
},
},
},
"rewrite_config": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"host": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-z0-9\-\.\*\?]{3,128}$`), "The host name must be 3 to128 characters in length, and can contain lowercase letters, digits, hyphens (-), periods (.), asterisks (*), and question marks (?)."),
},
"path": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^\/[A-Za-z0-9\$\-_\.\+\/\&\~\@\:]{1,127}$`), "The value must be 1 to 128 characters in length and must start with a forward slash (/). The value can contain letters, digits, and the following special characters: $ - _ .+ / & ~ @ :. It cannot contain the following special characters: \" % # ; ! ( ) [ ]^ , \". The value is case-sensitive and can contain asterisks (*) and question marks (?)."),
},
"query": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(1, 128),
},
},
},
},
"type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"ForwardGroup", "Redirect", "FixedResponse", "Rewrite", "InsertHeader"}, false),
},
},
},
},
"rule_conditions": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cookie_config": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"values": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(1, 100),
},
"value": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(1, 128),
},
},
},
},
},
},
},
"header_config": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[A-Za-z0-9_-]{1,40}$`), "The name of the header. The name must be 1 to 40 characters in length and can contain letters, digits, underscores (_), and hyphens (-)."),
},
"values": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"host_config": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"values": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"method_config": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"values": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"path_config": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"values": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"query_string_config": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"values": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(1, 100),
},
"value": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(1, 128),
},
},
},
},
},
},
},
"type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"Host", "Path", "Header", "HTTP", "QueryString", "Method", "Cookie"}, false),
},
},
},
},
"rule_name": {
Type: schema.TypeString,
Required: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudAlbRuleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateRule"
request := make(map[string]interface{})
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["ListenerId"] = d.Get("listener_id")
request["Priority"] = d.Get("priority")
ruleActionsMaps := make([]map[string]interface{}, 0)
for _, ruleActions := range d.Get("rule_actions").(*schema.Set).List() {
ruleActionsArg := ruleActions.(map[string]interface{})
ruleActionsMap := map[string]interface{}{}
ruleActionsMap["Order"] = ruleActionsArg["order"]
ruleActionsMap["Type"] = ruleActionsArg["type"]
if ruleActionsMap["Type"] == "" {
continue
}
fixedResponseConfigMap := map[string]interface{}{}
for _, fixedResponseConfig := range ruleActionsArg["fixed_response_config"].(*schema.Set).List() {
fixedResponseConfigArg := fixedResponseConfig.(map[string]interface{})
fixedResponseConfigMap["Content"] = fixedResponseConfigArg["content"]
fixedResponseConfigMap["ContentType"] = fixedResponseConfigArg["content_type"]
fixedResponseConfigMap["HttpCode"] = fixedResponseConfigArg["http_code"]
ruleActionsMap["FixedResponseConfig"] = fixedResponseConfigMap
}
forwardGroupConfigMap := map[string]interface{}{}
for _, forwardGroupConfig := range ruleActionsArg["forward_group_config"].(*schema.Set).List() {
forwardGroupConfigArg := forwardGroupConfig.(map[string]interface{})
serverGroupTuplesMaps := make([]map[string]interface{}, 0)
for _, serverGroupTuples := range forwardGroupConfigArg["server_group_tuples"].(*schema.Set).List() {
serverGroupTuplesArg := serverGroupTuples.(map[string]interface{})
serverGroupTuplesMap := map[string]interface{}{}
serverGroupTuplesMap["ServerGroupId"] = serverGroupTuplesArg["server_group_id"]
serverGroupTuplesMaps = append(serverGroupTuplesMaps, serverGroupTuplesMap)
}
forwardGroupConfigMap["ServerGroupTuples"] = serverGroupTuplesMaps
ruleActionsMap["ForwardGroupConfig"] = forwardGroupConfigMap
}
insertHeaderConfigMap := map[string]interface{}{}
for _, insertHeaderConfig := range ruleActionsArg["insert_header_config"].(*schema.Set).List() {
insertHeaderConfigArg := insertHeaderConfig.(map[string]interface{})
insertHeaderConfigMap["Key"] = insertHeaderConfigArg["key"]
insertHeaderConfigMap["Value"] = insertHeaderConfigArg["value"]
insertHeaderConfigMap["ValueType"] = insertHeaderConfigArg["value_type"]
ruleActionsMap["InsertHeaderConfig"] = insertHeaderConfigMap
}
redirectConfigMap := map[string]interface{}{}
for _, redirectConfig := range ruleActionsArg["redirect_config"].(*schema.Set).List() {
redirectConfigArg := redirectConfig.(map[string]interface{})
redirectConfigMap["Host"] = redirectConfigArg["host"]
redirectConfigMap["HttpCode"] = redirectConfigArg["http_code"]
redirectConfigMap["Path"] = redirectConfigArg["path"]
redirectConfigMap["Port"] = redirectConfigArg["port"]
redirectConfigMap["Protocol"] = redirectConfigArg["protocol"]
redirectConfigMap["Query"] = redirectConfigArg["query"]
ruleActionsMap["RedirectConfig"] = redirectConfigMap
}
rewriteConfigMap := map[string]interface{}{}
for _, rewriteConfig := range ruleActionsArg["rewrite_config"].(*schema.Set).List() {
rewriteConfigArg := rewriteConfig.(map[string]interface{})
rewriteConfigMap["Host"] = rewriteConfigArg["host"]
rewriteConfigMap["Path"] = rewriteConfigArg["path"]
rewriteConfigMap["Query"] = rewriteConfigArg["query"]
ruleActionsMap["RewriteConfig"] = rewriteConfigMap
}
ruleActionsMaps = append(ruleActionsMaps, ruleActionsMap)
}
request["RuleActions"] = ruleActionsMaps
ruleConditionsMaps := make([]map[string]interface{}, 0)
for _, ruleConditions := range d.Get("rule_conditions").(*schema.Set).List() {
ruleConditionsArg := ruleConditions.(map[string]interface{})
ruleConditionsMap := map[string]interface{}{}
ruleConditionsMap["Type"] = ruleConditionsArg["type"]
cookieConfigMap := map[string]interface{}{}
for _, cookieConfig := range ruleConditionsArg["cookie_config"].(*schema.Set).List() {
cookieConfigArg := cookieConfig.(map[string]interface{})
valuesMaps := make([]map[string]interface{}, 0)
for _, values := range cookieConfigArg["values"].(*schema.Set).List() {
valuesArg := values.(map[string]interface{})
valuesMap := map[string]interface{}{}
valuesMap["Key"] = valuesArg["key"]
valuesMap["Value"] = valuesArg["value"]
valuesMaps = append(valuesMaps, valuesMap)
}
cookieConfigMap["Values"] = valuesMaps
ruleConditionsMap["CookieConfig"] = cookieConfigMap
}
headerConfigMap := map[string]interface{}{}
for _, headerConfig := range ruleConditionsArg["header_config"].(*schema.Set).List() {
headerConfigArg := headerConfig.(map[string]interface{})
headerConfigMap["Key"] = headerConfigArg["key"]
headerConfigMap["Values"] = headerConfigArg["values"].(*schema.Set).List()
ruleConditionsMap["HeaderConfig"] = headerConfigMap
}
hostConfigMap := map[string]interface{}{}
for _, hostConfig := range ruleConditionsArg["host_config"].(*schema.Set).List() {
hostConfigArg := hostConfig.(map[string]interface{})
hostConfigMap["Values"] = hostConfigArg["values"].(*schema.Set).List()
ruleConditionsMap["HostConfig"] = hostConfigMap
}
methodConfigMap := map[string]interface{}{}
for _, methodConfig := range ruleConditionsArg["method_config"].(*schema.Set).List() {
methodConfigArg := methodConfig.(map[string]interface{})
methodConfigMap["Values"] = methodConfigArg["values"].(*schema.Set).List()
ruleConditionsMap["MethodConfig"] = methodConfigMap
}
pathConfigMap := map[string]interface{}{}
for _, pathConfig := range ruleConditionsArg["path_config"].(*schema.Set).List() {
pathConfigArg := pathConfig.(map[string]interface{})
pathConfigMap["Values"] = pathConfigArg["values"].(*schema.Set).List()
ruleConditionsMap["PathConfig"] = pathConfigMap
}
queryStringConfigMap := map[string]interface{}{}
for _, queryStringConfig := range ruleConditionsArg["query_string_config"].(*schema.Set).List() {
queryStringConfigArg := queryStringConfig.(map[string]interface{})
valuesMaps := make([]map[string]interface{}, 0)
for _, values := range queryStringConfigArg["values"].(*schema.Set).List() {
valuesArg := values.(map[string]interface{})
valuesMap := map[string]interface{}{}
valuesMap["Key"] = valuesArg["key"]
valuesMap["Value"] = valuesArg["value"]
valuesMaps = append(valuesMaps, valuesMap)
}
queryStringConfigMap["Values"] = valuesMaps
ruleConditionsMap["QueryStringConfig"] = queryStringConfigMap
}
ruleConditionsMaps = append(ruleConditionsMaps, ruleConditionsMap)
}
request["RuleConditions"] = ruleConditionsMaps
request["RuleName"] = d.Get("rule_name")
request["ClientToken"] = buildClientToken("CreateRule")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IdempotenceProcessing", "IncorrectStatus.Listener", "SystemBusy", "Throttling"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_alb_rule", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["RuleId"]))
albService := AlbService{client}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, albService.AlbRuleStateRefreshFunc(d.Id(), []string{"CreateFailed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudAlbRuleRead(d, meta)
}
func resourceAlicloudAlbRuleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
albService := AlbService{client}
object, err := albService.DescribeAlbRule(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_alb_rule albService.DescribeAlbRule Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("listener_id", object["ListenerId"])
if v, ok := object["Priority"]; ok && fmt.Sprint(v) != "0" {
d.Set("priority", formatInt(v))
}
if ruleActionsList, ok := object["RuleActions"]; ok {
ruleActionsMaps := make([]map[string]interface{}, 0)
for _, ruleActions := range ruleActionsList.([]interface{}) {
ruleActionsArg := ruleActions.(map[string]interface{})
ruleActionsMap := map[string]interface{}{}
ruleActionsMap["type"] = ruleActionsArg["Type"]
ruleActionsMap["order"] = formatInt(ruleActionsArg["Order"])
if forwardGroupConfig, ok := ruleActionsArg["ForwardGroupConfig"]; ok {
forwardGroupConfigArg := forwardGroupConfig.(map[string]interface{})
if len(forwardGroupConfigArg) > 0 {
serverGroupTuplesMaps := make([]map[string]interface{}, 0)
if forwardGroupConfigArgs, ok := forwardGroupConfigArg["ServerGroupTuples"].([]interface{}); ok {
for _, serverGroupTuples := range forwardGroupConfigArgs {
serverGroupTuplesArg := serverGroupTuples.(map[string]interface{})
serverGroupTuplesMap := map[string]interface{}{}
serverGroupTuplesMap["server_group_id"] = serverGroupTuplesArg["ServerGroupId"]
serverGroupTuplesMaps = append(serverGroupTuplesMaps, serverGroupTuplesMap)
}
}
if len(serverGroupTuplesMaps) > 0 {
forwardGroupConfigMaps := make([]map[string]interface{}, 0)
forwardGroupConfigMap := map[string]interface{}{}
forwardGroupConfigMap["server_group_tuples"] = serverGroupTuplesMaps
forwardGroupConfigMaps = append(forwardGroupConfigMaps, forwardGroupConfigMap)
ruleActionsMap["forward_group_config"] = forwardGroupConfigMaps
ruleActionsMaps = append(ruleActionsMaps, ruleActionsMap)
}
}
}
if fixedResponseConfig, ok := ruleActionsArg["FixedResponseConfig"]; ok {
fixedResponseConfigArg := fixedResponseConfig.(map[string]interface{})
if len(fixedResponseConfigArg) > 0 {
fixedResponseConfigMaps := make([]map[string]interface{}, 0)
fixedResponseConfigMap := make(map[string]interface{}, 0)
fixedResponseConfigMap["content"] = fixedResponseConfigArg["Content"]
fixedResponseConfigMap["content_type"] = fixedResponseConfigArg["ContentType"]
fixedResponseConfigMap["http_code"] = fixedResponseConfigArg["HttpCode"]
fixedResponseConfigMaps = append(fixedResponseConfigMaps, fixedResponseConfigMap)
ruleActionsMap["fixed_response_config"] = fixedResponseConfigMaps
ruleActionsMaps = append(ruleActionsMaps, ruleActionsMap)
}
}
if insertHeaderConfig, ok := ruleActionsArg["InsertHeaderConfig"]; ok {
insertHeaderConfigArg := insertHeaderConfig.(map[string]interface{})
if len(insertHeaderConfigArg) > 0 {
insertHeaderConfigMaps := make([]map[string]interface{}, 0)
insertHeaderConfigMap := make(map[string]interface{}, 0)
insertHeaderConfigMap["key"] = insertHeaderConfigArg["Key"]
insertHeaderConfigMap["value"] = insertHeaderConfigArg["Value"]
insertHeaderConfigMap["value_type"] = insertHeaderConfigArg["ValueType"]
insertHeaderConfigMaps = append(insertHeaderConfigMaps, insertHeaderConfigMap)
ruleActionsMap["insert_header_config"] = insertHeaderConfigMaps
ruleActionsMaps = append(ruleActionsMaps, ruleActionsMap)
}
}
if redirectConfig, ok := ruleActionsArg["RedirectConfig"]; ok {
redirectConfigArg := redirectConfig.(map[string]interface{})
if len(redirectConfigArg) > 0 {
redirectConfigMaps := make([]map[string]interface{}, 0)
redirectConfigMap := make(map[string]interface{}, 0)
redirectConfigMap["host"] = redirectConfigArg["Host"]
redirectConfigMap["http_code"] = redirectConfigArg["HttpCode"]
redirectConfigMap["path"] = redirectConfigArg["Path"]
redirectConfigMap["port"] = formatInt(redirectConfigArg["Port"])
redirectConfigMap["protocol"] = redirectConfigArg["Protocol"]
redirectConfigMap["query"] = redirectConfigArg["Query"]
redirectConfigMaps = append(redirectConfigMaps, redirectConfigMap)
ruleActionsMap["redirect_config"] = redirectConfigMaps
ruleActionsMaps = append(ruleActionsMaps, ruleActionsMap)
}
}
if rewriteConfig, ok := ruleActionsArg["RewriteConfig"]; ok {
rewriteConfigArg := rewriteConfig.(map[string]interface{})
if len(rewriteConfigArg) > 0 {
rewriteConfigMaps := make([]map[string]interface{}, 0)
rewriteConfigMap := make(map[string]interface{}, 0)
rewriteConfigMap["host"] = rewriteConfigArg["Host"]
rewriteConfigMap["path"] = rewriteConfigArg["Path"]
rewriteConfigMap["query"] = rewriteConfigArg["Query"]
rewriteConfigMaps = append(rewriteConfigMaps, rewriteConfigMap)
ruleActionsMap["rewrite_config"] = rewriteConfigMaps
ruleActionsMaps = append(ruleActionsMaps, ruleActionsMap)
}
}
}
d.Set("rule_actions", ruleActionsMaps)
}
if ruleConditionsList, ok := object["RuleConditions"]; ok {
ruleConditionsMaps := make([]map[string]interface{}, 0)
for _, ruleConditions := range ruleConditionsList.([]interface{}) {
ruleConditionsArg := ruleConditions.(map[string]interface{})
ruleConditionsMap := map[string]interface{}{}
ruleConditionsMap["type"] = ruleConditionsArg["Type"]
if cookieConfig, ok := ruleConditionsArg["CookieConfig"]; ok {
cookieConfigArg := cookieConfig.(map[string]interface{})
if len(cookieConfigArg) > 0 {
cookieConfigMaps := make([]map[string]interface{}, 0)
valuesMaps := make([]map[string]interface{}, 0)
for _, values := range cookieConfigArg["Values"].([]interface{}) {
valuesArg := values.(map[string]interface{})
valuesMap := map[string]interface{}{}
valuesMap["key"] = valuesArg["Key"]
valuesMap["value"] = valuesArg["Value"]
valuesMaps = append(valuesMaps, valuesMap)
}
cookieConfigMap := map[string]interface{}{}
cookieConfigMap["values"] = valuesMaps
cookieConfigMaps = append(cookieConfigMaps, cookieConfigMap)
ruleConditionsMap["cookie_config"] = cookieConfigMaps
ruleConditionsMaps = append(ruleConditionsMaps, ruleConditionsMap)
}
}
if headerConfig, ok := ruleConditionsArg["HeaderConfig"]; ok {
headerConfigArg := headerConfig.(map[string]interface{})
if len(headerConfigArg) > 0 {
headerConfigMaps := make([]map[string]interface{}, 0)
headerConfigMap := map[string]interface{}{}
headerConfigMap["values"] = headerConfigArg["Values"].([]interface{})
headerConfigMap["key"] = headerConfigArg["Key"]
headerConfigMaps = append(headerConfigMaps, headerConfigMap)
ruleConditionsMap["header_config"] = headerConfigMaps
ruleConditionsMaps = append(ruleConditionsMaps, ruleConditionsMap)
}
}
if queryStringConfig, ok := ruleConditionsArg["QueryStringConfig"]; ok {
queryStringConfigArg := queryStringConfig.(map[string]interface{})
if len(queryStringConfigArg) > 0 {
queryStringConfigMaps := make([]map[string]interface{}, 0)
queryStringValuesMaps := make([]map[string]interface{}, 0)
for _, values := range queryStringConfigArg["Values"].([]interface{}) {
valuesArg := values.(map[string]interface{})
valuesMap := map[string]interface{}{}
valuesMap["key"] = valuesArg["Key"]
valuesMap["value"] = valuesArg["Value"]
queryStringValuesMaps = append(queryStringValuesMaps, valuesMap)
}
queryStringConfigMap := map[string]interface{}{}
queryStringConfigMap["values"] = queryStringValuesMaps
queryStringConfigMaps = append(queryStringConfigMaps, queryStringConfigMap)
ruleConditionsMap["query_string_config"] = queryStringConfigMaps
ruleConditionsMaps = append(ruleConditionsMaps, ruleConditionsMap)
}
}
if hostConfig, ok := ruleConditionsArg["HostConfig"]; ok {
hostConfigArg := hostConfig.(map[string]interface{})
if len(hostConfigArg) > 0 {
hostConfigMaps := make([]map[string]interface{}, 0)
hostConfigMap := map[string]interface{}{}
hostConfigMap["values"] = hostConfigArg["Values"].([]interface{})
hostConfigMaps = append(hostConfigMaps, hostConfigMap)
ruleConditionsMap["host_config"] = hostConfigMaps
ruleConditionsMaps = append(ruleConditionsMaps, ruleConditionsMap)
}
}
if methodConfig, ok := ruleConditionsArg["MethodConfig"]; ok {
methodConfigArg := methodConfig.(map[string]interface{})
if len(methodConfigArg) > 0 {
methodConfigMaps := make([]map[string]interface{}, 0)
methodConfigMap := map[string]interface{}{}
methodConfigMap["values"] = methodConfigArg["Values"].([]interface{})
methodConfigMaps = append(methodConfigMaps, methodConfigMap)
ruleConditionsMap["method_config"] = methodConfigMaps
ruleConditionsMaps = append(ruleConditionsMaps, ruleConditionsMap)
}
}
if pathConfig, ok := ruleConditionsArg["PathConfig"]; ok {
pathConfigArg := pathConfig.(map[string]interface{})
if len(pathConfigArg) > 0 {
pathConfigMaps := make([]map[string]interface{}, 0)
pathConfigMap := map[string]interface{}{}
pathConfigMap["values"] = pathConfigArg["Values"].([]interface{})
pathConfigMaps = append(pathConfigMaps, pathConfigMap)
ruleConditionsMap["path_config"] = pathConfigMaps
ruleConditionsMaps = append(ruleConditionsMaps, ruleConditionsMap)
}
}
}
d.Set("rule_conditions", ruleConditionsMaps)
}
d.Set("rule_name", object["RuleName"])
d.Set("status", object["RuleStatus"])
return nil
}
func resourceAlicloudAlbRuleUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"RuleId": d.Id(),
}
if d.HasChange("priority") {
update = true
request["Priority"] = d.Get("priority")
}
if d.HasChange("rule_name") {
update = true
request["RuleName"] = d.Get("rule_name")
}
if d.HasChange("rule_actions") {
update = true
ruleActionsMaps := make([]map[string]interface{}, 0)
for _, ruleActions := range d.Get("rule_actions").(*schema.Set).List() {
ruleActionsArg := ruleActions.(map[string]interface{})
ruleActionsMap := map[string]interface{}{}
ruleActionsMap["Order"] = ruleActionsArg["order"]
ruleActionsMap["Type"] = ruleActionsArg["type"]
if ruleActionsMap["Type"] == "" {
continue
}
fixedResponseConfigMap := map[string]interface{}{}
for _, fixedResponseConfig := range ruleActionsArg["fixed_response_config"].(*schema.Set).List() {
fixedResponseConfigArg := fixedResponseConfig.(map[string]interface{})
fixedResponseConfigMap["Content"] = fixedResponseConfigArg["content"]
fixedResponseConfigMap["ContentType"] = fixedResponseConfigArg["content_type"]
fixedResponseConfigMap["HttpCode"] = fixedResponseConfigArg["http_code"]
ruleActionsMap["FixedResponseConfig"] = fixedResponseConfigMap
}
forwardGroupConfigMap := map[string]interface{}{}
for _, forwardGroupConfig := range ruleActionsArg["forward_group_config"].(*schema.Set).List() {
forwardGroupConfigArg := forwardGroupConfig.(map[string]interface{})
serverGroupTuplesMaps := make([]map[string]interface{}, 0)
for _, serverGroupTuples := range forwardGroupConfigArg["server_group_tuples"].(*schema.Set).List() {
serverGroupTuplesArg := serverGroupTuples.(map[string]interface{})
serverGroupTuplesMap := map[string]interface{}{}
serverGroupTuplesMap["ServerGroupId"] = serverGroupTuplesArg["server_group_id"]
serverGroupTuplesMaps = append(serverGroupTuplesMaps, serverGroupTuplesMap)
}
forwardGroupConfigMap["ServerGroupTuples"] = serverGroupTuplesMaps
ruleActionsMap["ForwardGroupConfig"] = forwardGroupConfigMap
}
insertHeaderConfigMap := map[string]interface{}{}
for _, insertHeaderConfig := range ruleActionsArg["insert_header_config"].(*schema.Set).List() {
insertHeaderConfigArg := insertHeaderConfig.(map[string]interface{})
insertHeaderConfigMap["Key"] = insertHeaderConfigArg["key"]
insertHeaderConfigMap["Value"] = insertHeaderConfigArg["value"]
insertHeaderConfigMap["ValueType"] = insertHeaderConfigArg["value_type"]
ruleActionsMap["InsertHeaderConfig"] = insertHeaderConfigMap
}
redirectConfigMap := map[string]interface{}{}
for _, redirectConfig := range ruleActionsArg["redirect_config"].(*schema.Set).List() {
redirectConfigArg := redirectConfig.(map[string]interface{})
redirectConfigMap["Host"] = redirectConfigArg["host"]
redirectConfigMap["HttpCode"] = redirectConfigArg["http_code"]
redirectConfigMap["Path"] = redirectConfigArg["path"]
redirectConfigMap["Port"] = redirectConfigArg["port"]
redirectConfigMap["Protocol"] = redirectConfigArg["protocol"]
redirectConfigMap["Query"] = redirectConfigArg["query"]
ruleActionsMap["RedirectConfig"] = redirectConfigMap
}
rewriteConfigMap := map[string]interface{}{}
for _, rewriteConfig := range ruleActionsArg["rewrite_config"].(*schema.Set).List() {
rewriteConfigArg := rewriteConfig.(map[string]interface{})
rewriteConfigMap["Host"] = rewriteConfigArg["host"]
rewriteConfigMap["Path"] = rewriteConfigArg["path"]
rewriteConfigMap["Query"] = rewriteConfigArg["query"]
ruleActionsMap["RewriteConfig"] = rewriteConfigMap
}
ruleActionsMaps = append(ruleActionsMaps, ruleActionsMap)
}
request["RuleActions"] = ruleActionsMaps
}
if d.HasChange("rule_conditions") {
update = true
ruleConditionsMaps := make([]map[string]interface{}, 0)
for _, ruleConditions := range d.Get("rule_conditions").(*schema.Set).List() {
ruleConditionsArg := ruleConditions.(map[string]interface{})
ruleConditionsMap := map[string]interface{}{}
ruleConditionsMap["Type"] = ruleConditionsArg["type"]
cookieConfigMap := map[string]interface{}{}
for _, cookieConfig := range ruleConditionsArg["cookie_config"].(*schema.Set).List() {
cookieConfigArg := cookieConfig.(map[string]interface{})
valuesMaps := make([]map[string]interface{}, 0)
for _, values := range cookieConfigArg["values"].(*schema.Set).List() {
valuesArg := values.(map[string]interface{})
valuesMap := map[string]interface{}{}
valuesMap["Key"] = valuesArg["key"]
valuesMap["Value"] = valuesArg["value"]
valuesMaps = append(valuesMaps, valuesMap)
}
cookieConfigMap["Values"] = valuesMaps
ruleConditionsMap["CookieConfig"] = cookieConfigMap
}
headerConfigMap := map[string]interface{}{}
for _, headerConfig := range ruleConditionsArg["header_config"].(*schema.Set).List() {
headerConfigArg := headerConfig.(map[string]interface{})
headerConfigMap["Key"] = headerConfigArg["key"]
headerConfigMap["Values"] = headerConfigArg["values"].(*schema.Set).List()
ruleConditionsMap["HeaderConfig"] = headerConfigMap
}
hostConfigMap := map[string]interface{}{}
for _, hostConfig := range ruleConditionsArg["host_config"].(*schema.Set).List() {
hostConfigArg := hostConfig.(map[string]interface{})
hostConfigMap["Values"] = hostConfigArg["values"].(*schema.Set).List()
ruleConditionsMap["HostConfig"] = hostConfigMap
}
methodConfigMap := map[string]interface{}{}
for _, methodConfig := range ruleConditionsArg["method_config"].(*schema.Set).List() {
methodConfigArg := methodConfig.(map[string]interface{})
methodConfigMap["Values"] = methodConfigArg["values"].(*schema.Set).List()
ruleConditionsMap["MethodConfig"] = methodConfigMap
}
pathConfigMap := map[string]interface{}{}
for _, pathConfig := range ruleConditionsArg["path_config"].(*schema.Set).List() {
pathConfigArg := pathConfig.(map[string]interface{})
pathConfigMap["Values"] = pathConfigArg["values"].(*schema.Set).List()
ruleConditionsMap["PathConfig"] = pathConfigMap
}
queryStringConfigMap := map[string]interface{}{}
for _, queryStringConfig := range ruleConditionsArg["query_string_config"].(*schema.Set).List() {
queryStringConfigArg := queryStringConfig.(map[string]interface{})
valuesMaps := make([]map[string]interface{}, 0)
for _, values := range queryStringConfigArg["values"].(*schema.Set).List() {
valuesArg := values.(map[string]interface{})
valuesMap := map[string]interface{}{}
valuesMap["Key"] = valuesArg["key"]
valuesMap["Value"] = valuesArg["value"]
valuesMaps = append(valuesMaps, valuesMap)
}
queryStringConfigMap["Values"] = valuesMaps
ruleConditionsMap["QueryStringConfig"] = queryStringConfigMap
}
ruleConditionsMaps = append(ruleConditionsMaps, ruleConditionsMap)
}
request["RuleConditions"] = ruleConditionsMaps
}
if update {
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
action := "UpdateRuleAttribute"
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("UpdateRuleAttribute")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
albService := AlbService{client}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, albService.AlbRuleStateRefreshFunc(d.Id(), []string{"CreateFailed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudAlbRuleRead(d, meta)
}
func resourceAlicloudAlbRuleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteRule"
var response map[string]interface{}
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"RuleId": d.Id(),
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["ClientToken"] = buildClientToken("DeleteRule")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IdempotenceProcessing", "IncorrectStatus.Rule", "SystemBusy", "Throttling"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ResourceNotFound.Rule"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudAlbSecurityPolicy() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAlbSecurityPolicyCreate,
Read: resourceAlicloudAlbSecurityPolicyRead,
Update: resourceAlicloudAlbSecurityPolicyUpdate,
Delete: resourceAlicloudAlbSecurityPolicyDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Update: schema.DefaultTimeout(16 * time.Minute),
},
Schema: map[string]*schema.Schema{
"ciphers": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"security_policy_name": {
Type: schema.TypeString,
Required: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
"tls_versions": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
}
}
func resourceAlicloudAlbSecurityPolicyCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateSecurityPolicy"
request := make(map[string]interface{})
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
request["SecurityPolicyName"] = d.Get("security_policy_name")
request["TLSVersions"] = d.Get("tls_versions")
request["Ciphers"] = d.Get("ciphers")
request["ClientToken"] = buildClientToken("CreateSecurityPolicy")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_alb_security_policy", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["SecurityPolicyId"]))
return resourceAlicloudAlbSecurityPolicyRead(d, meta)
}
func resourceAlicloudAlbSecurityPolicyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
albService := AlbService{client}
object, err := albService.DescribeAlbSecurityPolicy(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_alb_security_policy albService.DescribeAlbSecurityPolicy Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("ciphers", object["Ciphers"])
d.Set("resource_group_id", object["ResourceGroupId"])
d.Set("security_policy_name", object["SecurityPolicyName"])
d.Set("status", object["SecurityPolicyStatus"])
d.Set("tls_versions", object["TLSVersions"])
tagResp, err := albService.ListTagResources(d.Id(), "securitypolicy")
d.Set("tags", tagsToMap(tagResp))
return nil
}
func resourceAlicloudAlbSecurityPolicyUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
albService := AlbService{client}
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
d.Partial(true)
if d.HasChange("tags") {
if err := albService.SetResourceTags(d, "securitypolicy"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
update := false
request := map[string]interface{}{
"ResourceId": d.Id(),
}
if d.HasChange("resource_group_id") {
update = true
}
if v, ok := d.GetOk("resource_group_id"); ok {
request["NewResourceGroupId"] = v
}
request["ResourceType"] = "securitypolicy"
if update {
action := "MoveResourceGroup"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("resource_group_id")
}
update = false
updateSecurityPolicyAttributeReq := map[string]interface{}{
"SecurityPolicyId": d.Id(),
}
if d.HasChange("ciphers") {
update = true
updateSecurityPolicyAttributeReq[""] = d.Get("ciphers")
}
if d.HasChange("security_policy_name") {
update = true
updateSecurityPolicyAttributeReq["SecurityPolicyName"] = d.Get("security_policy_name")
}
if d.HasChange("tls_versions") {
update = true
updateSecurityPolicyAttributeReq[""] = d.Get("tls_versions")
}
if update {
if v, ok := d.GetOkExists("dry_run"); ok {
updateSecurityPolicyAttributeReq["DryRun"] = v
}
if v, ok := d.GetOk("tls_versions"); ok {
updateSecurityPolicyAttributeReq["TLSVersions"] = v
}
if v, ok := d.GetOk("ciphers"); ok {
updateSecurityPolicyAttributeReq["Ciphers"] = v
}
action := "UpdateSecurityPolicyAttribute"
request["ClientToken"] = buildClientToken("UpdateSecurityPolicyAttribute")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 30*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, updateSecurityPolicyAttributeReq, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectStatus.SecurityPolicy"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, updateSecurityPolicyAttributeReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, albService.AlbSecurityPolicyStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("ciphers")
d.SetPartial("security_policy_name")
d.SetPartial("tls_versions")
}
d.Partial(false)
return resourceAlicloudAlbSecurityPolicyRead(d, meta)
}
func resourceAlicloudAlbSecurityPolicyDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteSecurityPolicy"
var response map[string]interface{}
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"SecurityPolicyId": d.Id(),
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["ClientToken"] = buildClientToken("DeleteSecurityPolicy")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ResourceNotFound.SecurityPolicy"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudAlbServerGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAlbServerGroupCreate,
Read: resourceAlicloudAlbServerGroupRead,
Update: resourceAlicloudAlbServerGroupUpdate,
Delete: resourceAlicloudAlbServerGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(6 * time.Minute),
Delete: schema.DefaultTimeout(6 * time.Minute),
Update: schema.DefaultTimeout(6 * time.Minute),
},
Schema: map[string]*schema.Schema{
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"health_check_config": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"health_check_connect_port": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(0, 65535),
},
"health_check_enabled": {
Type: schema.TypeBool,
Optional: true,
},
"health_check_host": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"health_check_http_version": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"HTTP1.0", "HTTP1.1"}, false),
},
"health_check_interval": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(1, 50),
},
"health_check_method": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"GET", "HEAD"}, false),
},
"health_check_path": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"health_check_protocol": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"health_check_timeout": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(1, 300),
},
"healthy_threshold": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(2, 10),
},
"unhealthy_threshold": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(2, 10),
},
"health_check_codes": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"protocol": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"HTTPS", "HTTP"}, false),
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"scheduler": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Sch", "Wlc", "Wrr"}, false),
},
"server_group_name": {
Type: schema.TypeString,
Optional: true,
},
"servers": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
},
"port": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(0, 65535),
},
"server_id": {
Type: schema.TypeString,
Optional: true,
},
"server_ip": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"server_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Ecs", "Eni", "Eci"}, false),
},
"weight": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(0, 100),
},
},
},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"sticky_session_config": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cookie": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"cookie_timeout": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.Any(validation.IntInSlice([]int{0}), validation.IntBetween(1, 86400)),
},
"sticky_session_enabled": {
Type: schema.TypeBool,
Optional: true,
},
"sticky_session_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Insert", "Server"}, false),
},
},
},
ForceNew: true,
},
"tags": tagsSchema(),
"vpc_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudAlbServerGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateServerGroup"
request := make(map[string]interface{})
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
if v, ok := d.GetOk("protocol"); ok {
request["Protocol"] = v
}
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("scheduler"); ok {
request["Scheduler"] = v
}
if v, ok := d.GetOk("server_group_name"); ok {
request["ServerGroupName"] = v
}
if v, ok := d.GetOk("vpc_id"); ok {
request["VpcId"] = v
}
if v, ok := d.GetOk("health_check_config"); ok {
healthCheckConfig := make(map[string]interface{})
for _, healthCheckConfigArgs := range v.(*schema.Set).List() {
healthCheckConfigArg := healthCheckConfigArgs.(map[string]interface{})
healthCheckConfig["HealthCheckEnabled"] = healthCheckConfigArg["health_check_enabled"]
if healthCheckConfig["HealthCheckEnabled"] == true {
healthCheckConfig["HealthCheckCodes"] = healthCheckConfigArg["health_check_codes"]
healthCheckConfig["HealthCheckConnectPort"] = healthCheckConfigArg["health_check_connect_port"]
healthCheckConfig["HealthCheckHost"] = healthCheckConfigArg["health_check_host"]
healthCheckConfig["HealthCheckHttpVersion"] = healthCheckConfigArg["health_check_http_version"]
healthCheckConfig["HealthCheckInterval"] = healthCheckConfigArg["health_check_interval"]
healthCheckConfig["HealthCheckMethod"] = healthCheckConfigArg["health_check_method"]
healthCheckConfig["HealthCheckPath"] = healthCheckConfigArg["health_check_path"]
healthCheckConfig["HealthCheckProtocol"] = healthCheckConfigArg["health_check_protocol"]
healthCheckConfig["HealthCheckTimeout"] = healthCheckConfigArg["health_check_timeout"]
healthCheckConfig["HealthyThreshold"] = healthCheckConfigArg["healthy_threshold"]
healthCheckConfig["UnhealthyThreshold"] = healthCheckConfigArg["unhealthy_threshold"]
}
}
request["HealthCheckConfig"] = healthCheckConfig
}
if v, ok := d.GetOk("sticky_session_config"); ok {
stickySessionConfig := make(map[string]interface{})
for _, stickySessionConfigArgs := range v.(*schema.Set).List() {
stickySessionConfigArg := stickySessionConfigArgs.(map[string]interface{})
stickySessionConfig["StickySessionEnabled"] = stickySessionConfigArg["sticky_session_enabled"]
if stickySessionConfig["StickySessionEnabled"] == true {
stickySessionConfig["StickySessionType"] = stickySessionConfigArg["sticky_session_type"]
if stickySessionConfig["StickySessionType"] == "Server" {
stickySessionConfig["Cookie"] = stickySessionConfigArg["cookie"]
}
if stickySessionConfig["StickySessionType"] == "Insert" {
stickySessionConfig["CookieTimeout"] = stickySessionConfigArg["cookie_timeout"]
}
}
}
request["StickySessionConfig"] = stickySessionConfig
}
request["ClientToken"] = buildClientToken("CreateServerGroup")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_alb_server_group", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["ServerGroupId"]))
albService := AlbService{client}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, albService.AlbServerGroupStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudAlbServerGroupUpdate(d, meta)
}
func resourceAlicloudAlbServerGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
albService := AlbService{client}
object, err := albService.DescribeAlbServerGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_alb_server_group albService.DescribeAlbServerGroup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
healthCheckConfigSli := make([]map[string]interface{}, 0)
if len(object["HealthCheckConfig"].(map[string]interface{})) > 0 {
healthCheckConfig := object["HealthCheckConfig"]
healthCheckConfigMap := make(map[string]interface{})
healthCheckConfigMap["health_check_codes"] = healthCheckConfig.(map[string]interface{})["HealthCheckCodes"]
healthCheckConfigMap["health_check_connect_port"] = formatInt(healthCheckConfig.(map[string]interface{})["HealthCheckConnectPort"])
healthCheckConfigMap["health_check_enabled"] = healthCheckConfig.(map[string]interface{})["HealthCheckEnabled"]
healthCheckConfigMap["health_check_host"] = healthCheckConfig.(map[string]interface{})["HealthCheckHost"]
healthCheckConfigMap["health_check_http_version"] = healthCheckConfig.(map[string]interface{})["HealthCheckHttpVersion"]
healthCheckConfigMap["health_check_interval"] = formatInt(healthCheckConfig.(map[string]interface{})["HealthCheckInterval"])
healthCheckConfigMap["health_check_method"] = healthCheckConfig.(map[string]interface{})["HealthCheckMethod"]
healthCheckConfigMap["health_check_path"] = healthCheckConfig.(map[string]interface{})["HealthCheckPath"]
healthCheckConfigMap["health_check_protocol"] = healthCheckConfig.(map[string]interface{})["HealthCheckProtocol"]
healthCheckConfigMap["health_check_timeout"] = formatInt(healthCheckConfig.(map[string]interface{})["HealthCheckTimeout"])
healthCheckConfigMap["healthy_threshold"] = formatInt(healthCheckConfig.(map[string]interface{})["HealthyThreshold"])
healthCheckConfigMap["unhealthy_threshold"] = formatInt(healthCheckConfig.(map[string]interface{})["UnhealthyThreshold"])
healthCheckConfigSli = append(healthCheckConfigSli, healthCheckConfigMap)
}
d.Set("health_check_config", healthCheckConfigSli)
d.Set("protocol", object["Protocol"])
d.Set("resource_group_id", object["ResourceGroupId"])
d.Set("scheduler", object["Scheduler"])
d.Set("server_group_name", object["ServerGroupName"])
d.Set("status", object["ServerGroupStatus"])
stickySessionConfigSli := make([]map[string]interface{}, 0)
if len(object["StickySessionConfig"].(map[string]interface{})) > 0 {
stickySessionConfig := object["StickySessionConfig"]
stickySessionConfigMap := make(map[string]interface{})
stickySessionConfigMap["cookie"] = stickySessionConfig.(map[string]interface{})["Cookie"]
stickySessionConfigMap["cookie_timeout"] = stickySessionConfig.(map[string]interface{})["CookieTimeout"]
stickySessionConfigMap["sticky_session_enabled"] = stickySessionConfig.(map[string]interface{})["StickySessionEnabled"]
stickySessionConfigMap["sticky_session_type"] = stickySessionConfig.(map[string]interface{})["StickySessionType"]
stickySessionConfigSli = append(stickySessionConfigSli, stickySessionConfigMap)
}
d.Set("sticky_session_config", stickySessionConfigSli)
d.Set("vpc_id", object["VpcId"])
serversList, err := albService.ListServerGroupServers(d.Id())
serversMaps := make([]map[string]interface{}, 0)
if serversList != nil {
for _, serversListItem := range serversList {
if serversListItemMap, ok := serversListItem.(map[string]interface{}); ok {
serversMap := make(map[string]interface{}, 0)
serversMap["description"] = serversListItemMap["Description"]
serversMap["port"] = serversListItemMap["Port"]
serversMap["server_id"] = serversListItemMap["ServerId"]
serversMap["server_ip"] = serversListItemMap["ServerIp"]
serversMap["server_type"] = serversListItemMap["ServerType"]
serversMap["status"] = serversListItemMap["Status"]
serversMap["weight"] = serversListItemMap["Weight"]
serversMaps = append(serversMaps, serversMap)
}
}
}
d.Set("servers", serversMaps)
listTagResourcesObject, err := albService.ListTagResources(d.Id(), "servergroup")
d.Set("tags", tagsToMap(listTagResourcesObject))
return nil
}
func resourceAlicloudAlbServerGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
albService := AlbService{client}
var response map[string]interface{}
d.Partial(true)
if d.HasChange("tags") {
if err := albService.SetResourceTags(d, "servergroup"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
update := false
request := map[string]interface{}{
"ResourceId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("resource_group_id") {
update = true
if v, ok := d.GetOk("resource_group_id"); ok {
request["NewResourceGroupId"] = v
}
}
if update {
action := "MoveResourceGroup"
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
request["ResourceType"] = "servergroup"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("resource_group_id")
}
update = false
if d.HasChange("servers") {
removed, added := d.GetChange("servers")
removeServersFromServerGroupReq := map[string]interface{}{
"ServerGroupId": d.Id(),
}
removeServersMaps := make([]map[string]interface{}, 0)
for _, servers := range removed.(*schema.Set).List() {
update = true
serversMap := map[string]interface{}{}
serversArg := servers.(map[string]interface{})
serversMap["Description"] = serversArg["description"]
serversMap["Port"] = serversArg["port"]
serversMap["ServerId"] = serversArg["server_id"]
serversMap["ServerIp"] = serversArg["server_ip"]
serversMap["ServerType"] = serversArg["server_type"]
serversMap["Weight"] = serversArg["weight"]
removeServersMaps = append(removeServersMaps, serversMap)
}
removeServersFromServerGroupReq["Servers"] = removeServersMaps
if update {
action := "RemoveServersFromServerGroup"
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
removeServersFromServerGroupReq["ClientToken"] = buildClientToken(action)
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, removeServersFromServerGroupReq, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectStatus.ServerGroup"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, removeServersFromServerGroupReq)
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, albService.AlbServerGroupStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
update = false
addServersToServerGroupReq := map[string]interface{}{
"ServerGroupId": d.Id(),
}
addServersMaps := make([]map[string]interface{}, 0)
for _, servers := range added.(*schema.Set).List() {
update = true
serversArg := servers.(map[string]interface{})
serversMap := map[string]interface{}{}
serversMap["Description"] = serversArg["description"]
serversMap["Port"] = serversArg["port"]
serversMap["ServerId"] = serversArg["server_id"]
serversMap["ServerIp"] = serversArg["server_ip"]
serversMap["ServerType"] = serversArg["server_type"]
serversMap["Weight"] = serversArg["weight"]
addServersMaps = append(addServersMaps, serversMap)
}
addServersToServerGroupReq["Servers"] = addServersMaps
if update {
action := "AddServersToServerGroup"
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
addServersToServerGroupReq["ClientToken"] = buildClientToken(action)
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, addServersToServerGroupReq, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectStatus.ServerGroup"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, addServersToServerGroupReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, albService.AlbServerGroupStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("servers")
}
}
update = false
updateServerGroupAttributeReq := map[string]interface{}{
"ServerGroupId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("scheduler") {
update = true
if v, ok := d.GetOk("scheduler"); ok {
updateServerGroupAttributeReq["Scheduler"] = v
}
}
if !d.IsNewResource() && d.HasChange("server_group_name") {
update = true
if v, ok := d.GetOk("server_group_name"); ok {
updateServerGroupAttributeReq["ServerGroupName"] = v
}
}
if d.HasChange("health_check_config") {
update = true
if v, ok := d.GetOk("health_check_config"); ok {
healthCheckConfig := make(map[string]interface{})
for _, healthCheckConfigArgs := range v.(*schema.Set).List() {
healthCheckConfigArg := healthCheckConfigArgs.(map[string]interface{})
healthCheckConfig["HealthCheckEnabled"] = healthCheckConfigArg["health_check_enabled"]
if healthCheckConfig["HealthCheckEnabled"] == true {
healthCheckConfig["HealthCheckCodes"] = healthCheckConfigArg["health_check_codes"]
healthCheckConfig["HealthCheckConnectPort"] = healthCheckConfigArg["health_check_connect_port"]
healthCheckConfig["HealthCheckHost"] = healthCheckConfigArg["health_check_host"]
healthCheckConfig["HealthCheckHttpVersion"] = healthCheckConfigArg["health_check_http_version"]
healthCheckConfig["HealthCheckInterval"] = healthCheckConfigArg["health_check_interval"]
healthCheckConfig["HealthCheckMethod"] = healthCheckConfigArg["health_check_method"]
healthCheckConfig["HealthCheckPath"] = healthCheckConfigArg["health_check_path"]
healthCheckConfig["HealthCheckProtocol"] = healthCheckConfigArg["health_check_protocol"]
healthCheckConfig["HealthCheckTimeout"] = healthCheckConfigArg["health_check_timeout"]
healthCheckConfig["HealthyThreshold"] = healthCheckConfigArg["healthy_threshold"]
healthCheckConfig["UnhealthyThreshold"] = healthCheckConfigArg["unhealthy_threshold"]
}
}
updateServerGroupAttributeReq["HealthCheckConfig"] = healthCheckConfig
}
}
if d.HasChange("sticky_session_config") {
update = true
if v, ok := d.GetOk("sticky_session_config"); ok {
stickySessionConfig := make(map[string]interface{})
for _, stickySessionConfigArgs := range v.(*schema.Set).List() {
stickySessionConfigArg := stickySessionConfigArgs.(map[string]interface{})
stickySessionConfig["StickySessionEnabled"] = stickySessionConfigArg["sticky_session_enabled"]
if stickySessionConfig["StickySessionEnabled"] == true {
stickySessionConfig["StickySessionType"] = stickySessionConfigArg["sticky_session_type"]
if stickySessionConfig["StickySessionType"] == "Server" {
stickySessionConfig["Cookie"] = stickySessionConfigArg["cookie"]
}
if stickySessionConfig["StickySessionType"] == "Insert" {
stickySessionConfig["CookieTimeout"] = stickySessionConfigArg["cookie_timeout"]
}
}
}
updateServerGroupAttributeReq["StickySessionConfig"] = stickySessionConfig
}
}
if update {
if v, ok := d.GetOkExists("dry_run"); ok {
updateServerGroupAttributeReq["DryRun"] = v
}
action := "UpdateServerGroupAttribute"
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("UpdateServerGroupAttribute")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, updateServerGroupAttributeReq, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectStatus.ServerGroup", "ResourceNotFound.ServerGroup"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, updateServerGroupAttributeReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, albService.AlbServerGroupStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("scheduler")
d.SetPartial("server_group_name")
}
d.Partial(false)
return resourceAlicloudAlbServerGroupRead(d, meta)
}
func resourceAlicloudAlbServerGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteServerGroup"
var response map[string]interface{}
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ServerGroupId": d.Id(),
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["ClientToken"] = buildClientToken("DeleteServerGroup")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectStatus.ServerGroup", "ResourceInUse.ServerGroup"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ResourceNotFound.ServerGroup"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudAlidnsAccessStrategy() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAlidnsAccessStrategyCreate,
Read: resourceAlicloudAlidnsAccessStrategyRead,
Update: resourceAlicloudAlidnsAccessStrategyUpdate,
Delete: resourceAlicloudAlidnsAccessStrategyDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"access_mode": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"AUTO", "DEFAULT", "FAILOVER"}, false),
},
"default_addr_pool_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"IPV4", "IPV6", "DOMAIN"}, false),
},
"lines": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"line_code": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"default_addr_pools": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"addr_pool_id": {
Type: schema.TypeString,
Required: true,
},
"lba_weight": {
Type: schema.TypeInt,
Optional: true,
},
},
},
},
"default_latency_optimization": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"OPEN", "CLOSE"}, false),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("strategy_mode"); ok && v.(string) == "LATENCY" {
return false
}
return true
},
},
"default_lba_strategy": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"ALL_RR", "RATIO"}, false),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("strategy_mode"); ok && v.(string) == "GEO" {
return false
}
return true
},
},
"default_max_return_addr_num": {
Type: schema.TypeInt,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("strategy_mode"); ok && v.(string) == "LATENCY" {
return false
}
return true
},
},
"default_min_available_addr_num": {
Type: schema.TypeInt,
Required: true,
},
"failover_addr_pool_type": {
Type: schema.TypeString,
Optional: true,
},
"failover_addr_pools": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"addr_pool_id": {
Type: schema.TypeString,
Optional: true,
},
"lba_weight": {
Type: schema.TypeInt,
Optional: true,
},
},
},
},
"failover_latency_optimization": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"OPEN", "CLOSE"}, false),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("strategy_mode"); ok && v.(string) == "LATENCY" {
return false
}
return true
},
},
"failover_lba_strategy": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"ALL_RR", "RATIO"}, false),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("strategy_mode"); ok && v.(string) == "GEO" {
return false
}
return true
},
},
"failover_max_return_addr_num": {
Type: schema.TypeInt,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("strategy_mode"); ok && v.(string) == "LATENCY" {
return false
}
return true
},
},
"failover_min_available_addr_num": {
Type: schema.TypeInt,
Optional: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"lang": {
Type: schema.TypeString,
Optional: true,
},
"strategy_mode": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"GEO", "LATENCY"}, false),
},
"strategy_name": {
Type: schema.TypeString,
Required: true,
},
},
}
}
func resourceAlicloudAlidnsAccessStrategyCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AddDnsGtmAccessStrategy"
request := make(map[string]interface{})
conn, err := client.NewAlidnsClient()
if err != nil {
return WrapError(err)
}
request["DefaultAddrPoolType"] = d.Get("default_addr_pool_type")
if v, ok := d.GetOk("default_latency_optimization"); ok {
request["DefaultLatencyOptimization"] = v
}
if v, ok := d.GetOk("default_lba_strategy"); ok {
request["DefaultLbaStrategy"] = v
}
if v, ok := d.GetOk("default_max_return_addr_num"); ok {
request["DefaultMaxReturnAddrNum"] = v
}
request["DefaultMinAvailableAddrNum"] = d.Get("default_min_available_addr_num")
if v, ok := d.GetOk("lines"); ok {
lines := make([]interface{}, 0)
for _, line := range v.(*schema.Set).List() {
lineArg := line.(map[string]interface{})
if v, ok := lineArg["line_code"]; ok && fmt.Sprint(v) != "" {
lines = append(lines, v)
}
}
request["Lines"] = convertListToJsonString(lines)
}
if v, ok := d.GetOk("failover_addr_pools"); ok {
failoverAddrPoolMaps := make([]map[string]interface{}, 0)
for _, failoverAddrPool := range v.(*schema.Set).List() {
failoverAddrPoolArg := failoverAddrPool.(map[string]interface{})
failoverAddrPoolMap := map[string]interface{}{}
failoverAddrPoolMap["Id"] = failoverAddrPoolArg["addr_pool_id"]
if v, ok := failoverAddrPoolArg["lba_weight"]; ok && fmt.Sprint(v) != "0" {
failoverAddrPoolMap["LbaWeight"] = v
}
failoverAddrPoolMaps = append(failoverAddrPoolMaps, failoverAddrPoolMap)
}
request["FailoverAddrPool"] = failoverAddrPoolMaps
}
if v, ok := d.GetOk("default_addr_pools"); ok {
defaultAddrPoolMaps := make([]map[string]interface{}, 0)
for _, defaultAddrPool := range v.(*schema.Set).List() {
defaultAddrPoolArg := defaultAddrPool.(map[string]interface{})
defaultAddrPoolMap := map[string]interface{}{}
defaultAddrPoolMap["Id"] = defaultAddrPoolArg["addr_pool_id"]
if v, ok := defaultAddrPoolArg["lba_weight"]; ok && fmt.Sprint(v) != "0" {
defaultAddrPoolMap["LbaWeight"] = v
}
defaultAddrPoolMaps = append(defaultAddrPoolMaps, defaultAddrPoolMap)
}
request["DefaultAddrPool"] = defaultAddrPoolMaps
}
if v, ok := d.GetOk("failover_addr_pool_type"); ok {
request["FailoverAddrPoolType"] = v
}
if v, ok := d.GetOk("failover_latency_optimization"); ok {
request["FailoverLatencyOptimization"] = v
}
if v, ok := d.GetOk("failover_lba_strategy"); ok {
request["FailoverLbaStrategy"] = v
}
if v, ok := d.GetOk("failover_max_return_addr_num"); ok {
request["FailoverMaxReturnAddrNum"] = v
}
if v, ok := d.GetOk("failover_min_available_addr_num"); ok {
request["FailoverMinAvailableAddrNum"] = v
}
request["InstanceId"] = d.Get("instance_id")
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
request["StrategyMode"] = d.Get("strategy_mode")
request["StrategyName"] = d.Get("strategy_name")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_alidns_access_strategy", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["StrategyId"]))
return resourceAlicloudAlidnsAccessStrategyRead(d, meta)
}
func resourceAlicloudAlidnsAccessStrategyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alidnsService := AlidnsService{client}
object, err := alidnsService.DescribeAlidnsAccessStrategy(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_alidns_access_strategy alidnsService.DescribeAlidnsAccessStrategy Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("default_addr_pool_type", object["DefaultAddrPoolType"])
if defaultAddrPoolsMap, ok := object["DefaultAddrPools"].(map[string]interface{}); ok && defaultAddrPoolsMap != nil {
if defaultAddrPoolList, ok := defaultAddrPoolsMap["DefaultAddrPool"]; ok && defaultAddrPoolList != nil {
defaultAddrPoolsMaps := make([]map[string]interface{}, 0)
for _, defaultAddrPoolListItem := range defaultAddrPoolList.([]interface{}) {
if v, ok := defaultAddrPoolListItem.(map[string]interface{}); ok {
defaultAddrPoolListItemMap := make(map[string]interface{}, 0)
defaultAddrPoolListItemMap["addr_pool_id"] = v["Id"]
defaultAddrPoolListItemMap["lba_weight"] = v["LbaWeight"]
defaultAddrPoolsMaps = append(defaultAddrPoolsMaps, defaultAddrPoolListItemMap)
}
}
d.Set("default_addr_pools", defaultAddrPoolsMaps)
}
}
d.Set("default_latency_optimization", object["DefaultLatencyOptimization"])
d.Set("default_lba_strategy", object["DefaultLbaStrategy"])
if v, ok := object["DefaultMaxReturnAddrNum"]; ok {
d.Set("default_max_return_addr_num", formatInt(v))
}
if v, ok := object["DefaultMinAvailableAddrNum"]; ok {
d.Set("default_min_available_addr_num", formatInt(v))
}
d.Set("failover_addr_pool_type", object["FailoverAddrPoolType"])
if failoverAddrPoolsMap, ok := object["FailoverAddrPools"].(map[string]interface{}); ok && failoverAddrPoolsMap != nil {
if failoverAddrPoolList, ok := failoverAddrPoolsMap["FailoverAddrPool"]; ok && failoverAddrPoolList != nil {
failoverAddrPoolsMaps := make([]map[string]interface{}, 0)
for _, failoverAddrPoolListItem := range failoverAddrPoolList.([]interface{}) {
if v, ok := failoverAddrPoolListItem.(map[string]interface{}); ok {
failoverAddrPoolListItemMap := make(map[string]interface{}, 0)
failoverAddrPoolListItemMap["addr_pool_id"] = v["Id"]
failoverAddrPoolListItemMap["lba_weight"] = v["LbaWeight"]
failoverAddrPoolsMaps = append(failoverAddrPoolsMaps, failoverAddrPoolListItemMap)
}
}
d.Set("failover_addr_pools", failoverAddrPoolsMaps)
}
}
if LinesMap, ok := object["Lines"].(map[string]interface{}); ok && LinesMap != nil {
if LineList, ok := LinesMap["Line"]; ok && LineList != nil {
LinesMaps := make([]map[string]interface{}, 0)
for _, lineListItem := range LineList.([]interface{}) {
if v, ok := lineListItem.(map[string]interface{}); ok {
lineListItemMap := make(map[string]interface{}, 0)
lineListItemMap["line_code"] = v["LineCode"]
LinesMaps = append(LinesMaps, lineListItemMap)
}
}
d.Set("lines", LinesMaps)
}
}
d.Set("failover_latency_optimization", object["FailoverLatencyOptimization"])
d.Set("failover_lba_strategy", object["FailoverLbaStrategy"])
if v, ok := object["FailoverMaxReturnAddrNum"]; ok {
d.Set("failover_max_return_addr_num", formatInt(v))
}
if v, ok := object["FailoverMinAvailableAddrNum"]; ok {
d.Set("failover_min_available_addr_num", formatInt(v))
}
d.Set("instance_id", object["InstanceId"])
d.Set("strategy_mode", object["StrategyMode"])
d.Set("strategy_name", object["StrategyName"])
d.Set("access_mode", object["AccessMode"])
return nil
}
func resourceAlicloudAlidnsAccessStrategyUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"StrategyId": d.Id(),
}
if d.HasChange("access_mode") {
update = true
if v, ok := d.GetOk("access_mode"); ok {
request["AccessMode"] = v
}
}
if d.HasChange("default_addr_pool_type") {
update = true
}
request["DefaultAddrPoolType"] = d.Get("default_addr_pool_type")
if d.HasChange("lines") {
update = true
}
if v, ok := d.GetOk("lines"); ok {
lines := make([]interface{}, 0)
for _, line := range v.(*schema.Set).List() {
lineArg := line.(map[string]interface{})
if v, ok := lineArg["line_code"]; ok && fmt.Sprint(v) != "" {
lines = append(lines, v)
}
}
request["Lines"] = convertListToJsonString(lines)
}
if d.HasChange("default_min_available_addr_num") {
update = true
}
request["DefaultMinAvailableAddrNum"] = d.Get("default_min_available_addr_num")
if d.HasChange("strategy_name") {
update = true
}
request["StrategyName"] = d.Get("strategy_name")
if d.HasChange("default_latency_optimization") {
update = true
}
if v, ok := d.GetOk("default_latency_optimization"); ok {
request["DefaultLatencyOptimization"] = v
}
if d.HasChange("default_lba_strategy") {
update = true
}
if v, ok := d.GetOk("default_lba_strategy"); ok {
request["DefaultLbaStrategy"] = v
}
if d.HasChange("default_max_return_addr_num") {
update = true
}
if v, ok := d.GetOk("default_max_return_addr_num"); ok {
request["DefaultMaxReturnAddrNum"] = v
}
if d.HasChange("failover_addr_pool_type") {
update = true
}
if v, ok := d.GetOk("failover_addr_pool_type"); ok {
request["FailoverAddrPoolType"] = v
}
if d.HasChange("failover_latency_optimization") {
update = true
}
if v, ok := d.GetOk("failover_latency_optimization"); ok {
request["FailoverLatencyOptimization"] = v
}
if d.HasChange("failover_lba_strategy") {
update = true
}
if v, ok := d.GetOk("failover_lba_strategy"); ok {
request["FailoverLbaStrategy"] = v
}
if d.HasChange("failover_max_return_addr_num") {
update = true
}
if v, ok := d.GetOk("failover_max_return_addr_num"); ok {
request["FailoverMaxReturnAddrNum"] = v
}
if d.HasChange("failover_min_available_addr_num") {
update = true
}
if v, ok := d.GetOk("failover_min_available_addr_num"); ok {
request["FailoverMinAvailableAddrNum"] = v
}
if d.HasChange("default_addr_pools") {
update = true
}
if v, ok := d.GetOk("default_addr_pools"); ok {
defaultAddrPoolMaps := make([]map[string]interface{}, 0)
for _, defaultAddrPool := range v.(*schema.Set).List() {
defaultAddrPoolArg := defaultAddrPool.(map[string]interface{})
defaultAddrPoolMap := map[string]interface{}{}
defaultAddrPoolMap["Id"] = defaultAddrPoolArg["addr_pool_id"]
if v, ok := defaultAddrPoolArg["lba_weight"]; ok && fmt.Sprint(v) != "0" {
defaultAddrPoolMap["LbaWeight"] = v
}
defaultAddrPoolMaps = append(defaultAddrPoolMaps, defaultAddrPoolMap)
}
request["DefaultAddrPool"] = defaultAddrPoolMaps
}
if d.HasChange("failover_addr_pools") {
update = true
}
if v, ok := d.GetOk("failover_addr_pools"); ok {
failoverAddrPoolMaps := make([]map[string]interface{}, 0)
for _, failoverAddrPool := range v.(*schema.Set).List() {
failoverAddrPoolArg := failoverAddrPool.(map[string]interface{})
failoverAddrPoolMap := map[string]interface{}{}
failoverAddrPoolMap["Id"] = failoverAddrPoolArg["addr_pool_id"]
if v, ok := failoverAddrPoolArg["lba_weight"]; ok && fmt.Sprint(v) != "0" {
failoverAddrPoolMap["LbaWeight"] = v
}
failoverAddrPoolMaps = append(failoverAddrPoolMaps, failoverAddrPoolMap)
}
request["FailoverAddrPool"] = failoverAddrPoolMaps
}
if update {
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
action := "UpdateDnsGtmAccessStrategy"
conn, err := client.NewAlidnsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudAlidnsAccessStrategyRead(d, meta)
}
func resourceAlicloudAlidnsAccessStrategyDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteDnsGtmAccessStrategy"
var response map[string]interface{}
conn, err := client.NewAlidnsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"StrategyId": d.Id(),
}
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudAlidnsAddressPool() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAlidnsAddressPoolCreate,
Read: resourceAlicloudAlidnsAddressPoolRead,
Update: resourceAlicloudAlidnsAddressPoolUpdate,
Delete: resourceAlicloudAlidnsAddressPoolDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"address": {
Type: schema.TypeSet,
Required: true,
MaxItems: 20,
MinItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"address": {
Type: schema.TypeString,
Required: true,
},
"attribute_info": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.ValidateJsonString,
},
"lba_weight": {
Type: schema.TypeInt,
Optional: true,
},
"mode": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"SMART", "ONLINE", "OFFLINE"}, false),
},
"remark": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"address_pool_name": {
Type: schema.TypeString,
Required: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"lba_strategy": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"ALL_RR", "RATIO"}, false),
},
"type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"IPV4", "IPV6", "DOMAIN"}, false),
},
},
}
}
func resourceAlicloudAlidnsAddressPoolCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AddDnsGtmAddressPool"
request := make(map[string]interface{})
conn, err := client.NewAlidnsClient()
if err != nil {
return WrapError(err)
}
request["Name"] = d.Get("address_pool_name")
request["InstanceId"] = d.Get("instance_id")
request["LbaStrategy"] = d.Get("lba_strategy")
if v, ok := d.GetOk("address"); ok {
addressMaps := make([]map[string]interface{}, 0)
for _, address := range v.(*schema.Set).List() {
addressArg := address.(map[string]interface{})
addressMap := map[string]interface{}{}
addressMap["Addr"] = addressArg["address"]
addressMap["AttributeInfo"] = addressArg["attribute_info"]
if v, ok := addressArg["remark"]; ok {
addressMap["Remark"] = v
}
if v, ok := addressArg["lba_weight"]; ok && fmt.Sprint(v) != "0" {
addressMap["LbaWeight"] = v
}
addressMap["Mode"] = addressArg["mode"]
addressMaps = append(addressMaps, addressMap)
}
request["Addr"] = addressMaps
}
request["Type"] = d.Get("type")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_alidns_address_pool", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["AddrPoolId"]))
return resourceAlicloudAlidnsAddressPoolRead(d, meta)
}
func resourceAlicloudAlidnsAddressPoolRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alidnsService := AlidnsService{client}
object, err := alidnsService.DescribeAlidnsAddressPool(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_alidns_address_pool alidnsService.DescribeAlidnsAddressPool Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("address_pool_name", object["Name"])
d.Set("lba_strategy", object["LbaStrategy"])
d.Set("type", object["Type"])
return nil
}
func resourceAlicloudAlidnsAddressPoolUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewAlidnsClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
update := false
request := map[string]interface{}{
"AddrPoolId": d.Id(),
}
if d.HasChange("lba_strategy") {
update = true
}
request["LbaStrategy"] = d.Get("lba_strategy")
if d.HasChange("address_pool_name") {
update = true
request["Name"] = d.Get("address_pool_name")
}
if d.HasChange("address") {
update = true
}
if v, ok := d.GetOk("address"); ok {
addressMaps := make([]map[string]interface{}, 0)
for _, address := range v.(*schema.Set).List() {
addressArg := address.(map[string]interface{})
addressMap := map[string]interface{}{}
addressMap["Addr"] = addressArg["address"]
addressMap["AttributeInfo"] = addressArg["attribute_info"]
if v, ok := addressArg["remark"]; ok {
addressMap["Remark"] = v
}
if v, ok := addressArg["lba_weight"]; ok && fmt.Sprint(v) != "0" {
addressMap["LbaWeight"] = v
}
addressMap["Mode"] = addressArg["mode"]
addressMaps = append(addressMaps, addressMap)
}
request["Addr"] = addressMaps
}
if update {
action := "UpdateDnsGtmAddressPool"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudAlidnsAddressPoolRead(d, meta)
}
func resourceAlicloudAlidnsAddressPoolDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteDnsGtmAddressPool"
var response map[string]interface{}
conn, err := client.NewAlidnsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AddrPoolId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudAlidnsCustomLine() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAlidnsCustomLineCreate,
Read: resourceAlicloudAlidnsCustomLineRead,
Update: resourceAlicloudAlidnsCustomLineUpdate,
Delete: resourceAlicloudAlidnsCustomLineDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"custom_line_name": {
Type: schema.TypeString,
Required: true,
},
"domain_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ip_segment_list": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"end_ip": {
Type: schema.TypeString,
Required: true,
},
"start_ip": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"lang": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudAlidnsCustomLineCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AddCustomLine"
request := make(map[string]interface{})
conn, err := client.NewAlidnsClient()
if err != nil {
return WrapError(err)
}
for index, ipSegment := range d.Get("ip_segment_list").(*schema.Set).List() {
ipSegmentArg := ipSegment.(map[string]interface{})
request[fmt.Sprintf("IpSegment.%d.EndIp", index+1)] = ipSegmentArg["end_ip"]
request[fmt.Sprintf("IpSegment.%d.StartIp", index+1)] = ipSegmentArg["start_ip"]
}
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
request["DomainName"] = d.Get("domain_name")
request["LineName"] = d.Get("custom_line_name")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_alidns_custom_line", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["LineId"]))
return resourceAlicloudAlidnsCustomLineRead(d, meta)
}
func resourceAlicloudAlidnsCustomLineRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alidnsService := AlidnsService{client}
object, err := alidnsService.DescribeAlidnsCustomLine(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_alidns_custom_line alidnsService.DescribeAlidnsCustomLine Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("custom_line_name", object["Name"])
d.Set("domain_name", object["DomainName"])
if ipSegmentList, ok := object["IpSegmentList"]; ok {
ipSegments := make([]map[string]interface{}, 0)
for _, ipSegmentListItem := range ipSegmentList.([]interface{}) {
ipSegmentMap := ipSegmentListItem.(map[string]interface{})
ipSegmentArg := make(map[string]interface{}, 0)
ipSegmentArg["end_ip"] = ipSegmentMap["EndIp"]
ipSegmentArg["start_ip"] = ipSegmentMap["StartIp"]
ipSegments = append(ipSegments, ipSegmentArg)
}
d.Set("ip_segment_list", ipSegments)
}
return nil
}
func resourceAlicloudAlidnsCustomLineUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewAlidnsClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
update := false
request := map[string]interface{}{
"LineId": d.Id(),
}
if d.HasChange("custom_line_name") {
update = true
if v, ok := d.GetOk("custom_line_name"); ok {
request["LineName"] = v
}
}
if d.HasChange("ip_segment_list") {
update = true
for index, ipSegment := range d.Get("ip_segment_list").(*schema.Set).List() {
ipSegmentArg := ipSegment.(map[string]interface{})
request[fmt.Sprintf("IpSegment.%d.EndIp", index+1)] = ipSegmentArg["end_ip"]
request[fmt.Sprintf("IpSegment.%d.StartIp", index+1)] = ipSegmentArg["start_ip"]
}
}
if update {
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
action := "UpdateCustomLine"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudAlidnsCustomLineRead(d, meta)
}
func resourceAlicloudAlidnsCustomLineDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteCustomLines"
var response map[string]interface{}
conn, err := client.NewAlidnsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"LineIds": d.Id(),
}
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/alidns"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudAlidnsDomain() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAlidnsDomainCreate,
Read: resourceAlicloudAlidnsDomainRead,
Update: resourceAlicloudAlidnsDomainUpdate,
Delete: resourceAlicloudAlidnsDomainDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Delete: schema.DefaultTimeout(6 * time.Minute),
},
Schema: map[string]*schema.Schema{
"dns_servers": {
Type: schema.TypeSet,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"domain_id": {
Type: schema.TypeString,
Computed: true,
},
"domain_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"group_id": {
Type: schema.TypeString,
Optional: true,
},
"group_name": {
Type: schema.TypeString,
Computed: true,
},
"lang": {
Type: schema.TypeString,
Optional: true,
},
"puny_code": {
Type: schema.TypeString,
Computed: true,
},
"remark": {
Type: schema.TypeString,
Optional: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"tags": tagsSchema(),
},
}
}
func resourceAlicloudAlidnsDomainCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := alidns.CreateAddDomainRequest()
request.DomainName = d.Get("domain_name").(string)
if v, ok := d.GetOk("group_id"); ok {
request.GroupId = v.(string)
}
if v, ok := d.GetOk("lang"); ok {
request.Lang = v.(string)
}
if v, ok := d.GetOk("resource_group_id"); ok {
request.ResourceGroupId = v.(string)
}
raw, err := client.WithAlidnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.AddDomain(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_alidns_domain", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ := raw.(*alidns.AddDomainResponse)
d.SetId(fmt.Sprintf("%v", response.DomainName))
return resourceAlicloudAlidnsDomainUpdate(d, meta)
}
func resourceAlicloudAlidnsDomainRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alidnsService := AlidnsService{client}
object, err := alidnsService.DescribeAlidnsDomain(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_alidns_domain alidnsService.DescribeAlidnsDomain Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("domain_name", d.Id())
d.Set("dns_servers", object.DnsServers.DnsServer)
d.Set("domain_id", object.DomainId)
d.Set("group_id", object.GroupId)
d.Set("group_name", object.GroupName)
d.Set("puny_code", object.PunyCode)
d.Set("remark", object.Remark)
d.Set("resource_group_id", object.ResourceGroupId)
listTagResourcesObject, err := alidnsService.ListTagResources(d.Id())
if err != nil {
return WrapError(err)
}
tags := make(map[string]string)
for _, t := range listTagResourcesObject.TagResources {
tags[t.TagKey] = t.TagValue
}
d.Set("tags", tags)
return nil
}
func resourceAlicloudAlidnsDomainUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alidnsService := AlidnsService{client}
d.Partial(true)
if d.HasChange("tags") {
if err := alidnsService.SetResourceTags(d, "DOMAIN"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
update := false
request := alidns.CreateUpdateDomainRemarkRequest()
request.DomainName = d.Id()
if !d.IsNewResource() && d.HasChange("lang") {
update = true
request.Lang = d.Get("lang").(string)
}
if d.HasChange("remark") {
update = true
request.Remark = d.Get("remark").(string)
}
if update {
raw, err := client.WithAlidnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.UpdateDomainRemark(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("lang")
d.SetPartial("remark")
}
update = false
changeDomainGroupReq := alidns.CreateChangeDomainGroupRequest()
changeDomainGroupReq.DomainName = d.Id()
if !d.IsNewResource() && d.HasChange("group_id") {
update = true
changeDomainGroupReq.GroupId = d.Get("group_id").(string)
}
if !d.IsNewResource() && d.HasChange("lang") {
update = true
changeDomainGroupReq.Lang = d.Get("lang").(string)
}
if update {
raw, err := client.WithAlidnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.ChangeDomainGroup(changeDomainGroupReq)
})
addDebug(changeDomainGroupReq.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), changeDomainGroupReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("group_id")
d.SetPartial("lang")
}
d.Partial(false)
return resourceAlicloudAlidnsDomainRead(d, meta)
}
func resourceAlicloudAlidnsDomainDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := alidns.CreateDeleteDomainRequest()
request.DomainName = d.Id()
if v, ok := d.GetOk("lang"); ok {
request.Lang = v.(string)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err := resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
raw, err := client.WithAlidnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.DeleteDomain(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"RecordForbidden.DNSChange", "DnsSystemBusyness", "InternalError"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDomainName.NoExist"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"github.com/aliyun/alibaba-cloud-sdk-go/services/alidns"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudAlidnsDomainGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAlidnsDomainGroupCreate,
Read: resourceAlicloudAlidnsDomainGroupRead,
Update: resourceAlicloudAlidnsDomainGroupUpdate,
Delete: resourceAlicloudAlidnsDomainGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"domain_group_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"group_name"},
},
"group_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Field 'group_name' has been deprecated from version 1.97.0. Use 'domain_group_name' instead.",
ConflictsWith: []string{"domain_group_name"},
},
"lang": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudAlidnsDomainGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := alidns.CreateAddDomainGroupRequest()
if v, ok := d.GetOk("domain_group_name"); ok {
request.GroupName = v.(string)
} else if v, ok := d.GetOk("group_name"); ok {
request.GroupName = v.(string)
} else {
return WrapError(Error(`[ERROR] Argument "group_name" or "domain_group_name" must be set one!`))
}
if v, ok := d.GetOk("lang"); ok {
request.Lang = v.(string)
}
raw, err := client.WithAlidnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.AddDomainGroup(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_alidns_domain_group", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ := raw.(*alidns.AddDomainGroupResponse)
d.SetId(fmt.Sprintf("%v", response.GroupId))
return resourceAlicloudAlidnsDomainGroupRead(d, meta)
}
func resourceAlicloudAlidnsDomainGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alidnsService := AlidnsService{client}
object, err := alidnsService.DescribeAlidnsDomainGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_alidns_domain_group alidnsService.DescribeAlidnsDomainGroup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("domain_group_name", object.GroupName)
d.Set("group_name", object.GroupName)
return nil
}
func resourceAlicloudAlidnsDomainGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
update := false
request := alidns.CreateUpdateDomainGroupRequest()
request.GroupId = d.Id()
if d.HasChange("domain_group_name") {
update = true
request.GroupName = d.Get("domain_group_name").(string)
}
if d.HasChange("group_name") {
update = true
request.GroupName = d.Get("group_name").(string)
}
if request.GroupName == "" {
request.GroupName = d.Get("domain_group_name").(string)
}
if d.HasChange("lang") {
update = true
request.Lang = d.Get("lang").(string)
}
if update {
raw, err := client.WithAlidnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.UpdateDomainGroup(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudAlidnsDomainGroupRead(d, meta)
}
func resourceAlicloudAlidnsDomainGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := alidns.CreateDeleteDomainGroupRequest()
request.GroupId = d.Id()
if v, ok := d.GetOk("lang"); ok {
request.Lang = v.(string)
}
raw, err := client.WithAlidnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.DeleteDomainGroup(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudAlidnsGtmInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAlidnsGtmInstanceCreate,
Read: resourceAlicloudAlidnsGtmInstanceRead,
Update: resourceAlicloudAlidnsGtmInstanceUpdate,
Delete: resourceAlicloudAlidnsGtmInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"alert_config": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"dingtalk_notice": {
Type: schema.TypeBool,
Optional: true,
},
"email_notice": {
Type: schema.TypeBool,
Optional: true,
},
"notice_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"ADDR_RESUME", "ADDR_ALERT", "ADDR_POOL_GROUP_UNAVAILABLE", "ADDR_POOL_GROUP_AVAILABLE", "ACCESS_STRATEGY_POOL_GROUP_SWITCH", "MONITOR_NODE_IP_CHANGE"}, false),
},
"sms_notice": {
Type: schema.TypeBool,
Optional: true,
},
},
},
},
"alert_group": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"cname_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"PUBLIC"}, false),
},
"force_update": {
Type: schema.TypeBool,
Optional: true,
},
"instance_name": {
Type: schema.TypeString,
Required: true,
},
"lang": {
Type: schema.TypeString,
Optional: true,
},
"payment_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Subscription"}, false),
},
"period": {
Type: schema.TypeInt,
Required: true,
},
"renew_period": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return fmt.Sprint(d.Get("renewal_status")) == "ManualRenewal"
},
},
"renewal_status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"AutoRenewal", "ManualRenewal"}, false),
},
"package_edition": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"standard", "ultimate"}, false),
},
"health_check_task_count": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
ValidateFunc: validation.IntBetween(0, 100000),
},
"sms_notification_count": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
ValidateFunc: validation.IntBetween(0, 100000),
},
"strategy_mode": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"GEO", "LATENCY"}, false),
},
"public_cname_mode": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"CUSTOM", "SYSTEM_ASSIGN"}, false),
},
"public_rr": {
Type: schema.TypeString,
Optional: true,
Computed: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return fmt.Sprint(d.Get("public_cname_mode")) == "SYSTEM_ASSIGN"
},
},
"public_user_domain_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"public_zone_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return fmt.Sprint(d.Get("public_cname_mode")) == "SYSTEM_ASSIGN"
},
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
},
"ttl": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{60, 120, 300, 600}),
},
},
}
}
func resourceAlicloudAlidnsGtmInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateInstance"
request := make(map[string]interface{})
conn, err := client.NewBssopenapiClient()
if err != nil {
return WrapError(err)
}
request["SubscriptionType"] = d.Get("payment_type")
if v, ok := d.GetOk("period"); ok {
request["Period"] = v
}
request["ProductCode"] = "dns"
request["ProductType"] = "dns_gtm_public_cn"
if v, ok := d.GetOk("renew_period"); ok {
request["RenewPeriod"] = v
}
if v, ok := d.GetOk("renewal_status"); ok {
request["RenewalStatus"] = v
}
parameters := []map[string]string{
{
"Code": "PackageEdition",
"Value": fmt.Sprint(d.Get("package_edition")),
},
{
"Code": "HealthcheckTaskCount",
"Value": fmt.Sprint(d.Get("health_check_task_count")),
},
{
"Code": "SmsNotificationCount",
"Value": fmt.Sprint(d.Get("sms_notification_count")),
},
}
request["Parameter"] = parameters
request["ClientToken"] = buildClientToken("CreateInstance")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-14"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"NotApplicable"}) {
request["ProductType"] = "dns_gtm_public_intl"
conn.Endpoint = String(connectivity.BssOpenAPIEndpointInternational)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_alidns_gtm_instance", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
responseData := response["Data"].(map[string]interface{})
d.SetId(fmt.Sprint(responseData["InstanceId"]))
return resourceAlicloudAlidnsGtmInstanceUpdate(d, meta)
}
func resourceAlicloudAlidnsGtmInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alidnsService := AlidnsService{client}
object, err := alidnsService.DescribeAlidnsGtmInstance(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_alidns_gtm_instance alidnsService.DescribeAlidnsGtmInstance Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("resource_group_id", object["ResourceGroupId"])
d.Set("payment_type", object["PaymentType"])
d.Set("package_edition", object["VersionCode"])
if config, ok := object["Config"].(map[string]interface{}); ok {
d.Set("cname_type", config["CnameType"])
d.Set("instance_name", config["InstanceName"])
d.Set("strategy_mode", config["StrategyMode"])
d.Set("public_cname_mode", config["PublicCnameMode"])
d.Set("public_rr", config["PublicRr"])
d.Set("public_user_domain_name", config["PublicUserDomainName"])
d.Set("public_zone_name", config["PubicZoneName"])
if v, ok := config["Ttl"]; ok {
d.Set("ttl", formatInt(v))
}
v, err := convertJsonStringToList(config["AlertGroup"].(string))
if err != nil {
return WrapError(err)
} else {
d.Set("alert_group", v)
}
if alertConfigsList, ok := config["AlertConfig"]; ok {
alertConfigsArg := alertConfigsList.(map[string]interface{})
if alertConfigConfig, ok := alertConfigsArg["AlertConfig"]; ok {
alertConfigConfigArgs := alertConfigConfig.([]interface{})
alertConfigsMaps := make([]map[string]interface{}, 0)
for _, alertConfigMapArgitem := range alertConfigConfigArgs {
alertConfigMapArg := alertConfigMapArgitem.(map[string]interface{})
alertConfigsMap := map[string]interface{}{}
alertConfigsMap["sms_notice"] = alertConfigMapArg["SmsNotice"]
alertConfigsMap["notice_type"] = alertConfigMapArg["NoticeType"]
alertConfigsMap["email_notice"] = alertConfigMapArg["EmailNotice"]
alertConfigsMap["dingtalk_notice"] = alertConfigMapArg["DingtalkNotice"]
alertConfigsMaps = append(alertConfigsMaps, alertConfigsMap)
}
d.Set("alert_config", alertConfigsMaps)
}
}
}
return nil
}
func resourceAlicloudAlidnsGtmInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"ResourceId": d.Id(),
}
if d.HasChange("resource_group_id") {
update = true
if v, ok := d.GetOk("resource_group_id"); ok {
request["NewResourceGroupId"] = v
}
}
if update {
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
action := "MoveGtmResourceGroup"
conn, err := client.NewAlidnsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("resource_group_id")
}
update = false
switchDnsGtmInstanceStrategyModeRequest := map[string]interface{}{
"InstanceId": d.Id(),
}
if d.HasChange("strategy_mode") {
update = true
if v, ok := d.GetOk("strategy_mode"); ok {
switchDnsGtmInstanceStrategyModeRequest["StrategyMode"] = v
}
}
if update {
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
action := "SwitchDnsGtmInstanceStrategyMode"
conn, err := client.NewAlidnsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, switchDnsGtmInstanceStrategyModeRequest, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("strategy_mode")
}
update = false
updateDnsGtmInstanceGlobalConfigReq := map[string]interface{}{
"InstanceId": d.Id(),
}
if d.HasChange("alert_config") {
update = true
alertConfigMaps := make([]map[string]interface{}, 0)
if v, ok := d.GetOk("alert_config"); ok {
for _, alertConfig := range v.(*schema.Set).List() {
alertConfigArg := alertConfig.(map[string]interface{})
alertConfigMap := map[string]interface{}{}
alertConfigMap["SmsNotice"] = alertConfigArg["sms_notice"]
alertConfigMap["NoticeType"] = alertConfigArg["notice_type"]
alertConfigMap["EmailNotice"] = alertConfigArg["email_notice"]
alertConfigMap["DingtalkNotice"] = alertConfigArg["dingtalk_notice"]
alertConfigMaps = append(alertConfigMaps, alertConfigMap)
}
updateDnsGtmInstanceGlobalConfigReq["AlertConfig"] = alertConfigMaps
}
}
if d.HasChange("alert_group") {
update = true
if v, ok := d.GetOk("alert_group"); ok {
updateDnsGtmInstanceGlobalConfigReq["AlertGroup"] = convertListToJsonString(v.(*schema.Set).List())
}
}
if d.HasChange("instance_name") {
update = true
}
if v, ok := d.GetOk("instance_name"); ok {
updateDnsGtmInstanceGlobalConfigReq["InstanceName"] = v
}
if d.HasChange("ttl") {
update = true
if v, ok := d.GetOk("ttl"); ok {
updateDnsGtmInstanceGlobalConfigReq["Ttl"] = v
}
}
if d.HasChange("public_cname_mode") {
update = true
if v, ok := d.GetOk("public_cname_mode"); ok {
updateDnsGtmInstanceGlobalConfigReq["PublicCnameMode"] = v
}
}
if d.HasChange("public_rr") {
update = true
if v, ok := d.GetOk("public_rr"); ok {
updateDnsGtmInstanceGlobalConfigReq["PublicRr"] = v
}
}
if d.HasChange("public_user_domain_name") {
update = true
if v, ok := d.GetOk("public_user_domain_name"); ok {
updateDnsGtmInstanceGlobalConfigReq["PublicUserDomainName"] = v
}
}
if d.HasChange("public_zone_name") {
update = true
if v, ok := d.GetOk("public_zone_name"); ok {
updateDnsGtmInstanceGlobalConfigReq["PublicZoneName"] = v
}
}
if d.HasChange("cname_type") {
update = true
if v, ok := d.GetOk("cname_type"); ok {
updateDnsGtmInstanceGlobalConfigReq["CnameType"] = v
}
}
if update {
if v, ok := d.GetOkExists("force_update"); ok {
updateDnsGtmInstanceGlobalConfigReq["ForceUpdate"] = v
}
if v, ok := d.GetOk("lang"); ok {
updateDnsGtmInstanceGlobalConfigReq["Lang"] = v
}
action := "UpdateDnsGtmInstanceGlobalConfig"
conn, err := client.NewAlidnsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, updateDnsGtmInstanceGlobalConfigReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, updateDnsGtmInstanceGlobalConfigReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("alert_config")
d.SetPartial("alert_group")
d.SetPartial("cname_type")
d.SetPartial("instance_name")
d.SetPartial("public_cname_mode")
d.SetPartial("public_rr")
d.SetPartial("public_user_domain_name")
d.SetPartial("public_zone_name")
d.SetPartial("ttl")
}
d.Partial(false)
return resourceAlicloudAlidnsGtmInstanceRead(d, meta)
}
func resourceAlicloudAlidnsGtmInstanceDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudAlidnsGtmInstance. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudAlidnsInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAlidnsInstanceCreate,
Read: resourceAlicloudAlidnsInstanceRead,
Update: resourceAlicloudAlidnsInstanceUpdate,
Delete: resourceAlicloudAlidnsInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"dns_security": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"advanced", "basic", "no"}, false),
},
"domain_numbers": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"payment_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Subscription"}, false),
Default: "Subscription",
},
"period": {
Type: schema.TypeInt,
Optional: true,
},
"renew_period": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if fmt.Sprint(d.Get("renewal_status")) == "ManualRenewal" {
return true
}
return false
},
},
"renewal_status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"AutoRenewal", "ManualRenewal"}, false),
},
"version_code": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"version_enterprise_advanced", "version_enterprise_basic", "version_personal"}, false),
},
"version_name": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudAlidnsInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateInstance"
request := make(map[string]interface{})
conn, err := client.NewBssopenapiClient()
if err != nil {
return WrapError(err)
}
request["SubscriptionType"] = d.Get("payment_type")
if v, ok := d.GetOk("period"); ok {
request["Period"] = v
}
request["ProductCode"] = "dns"
request["ProductType"] = "alidns_pre"
if v, ok := d.GetOk("renew_period"); ok {
request["RenewPeriod"] = v
}
if v, ok := d.GetOk("renewal_status"); ok {
request["RenewalStatus"] = v
}
request["Parameter"] = []map[string]string{
{
"Code": "DNSSecurity",
"Value": d.Get("dns_security").(string),
},
{
"Code": "DomainNumbers",
"Value": d.Get("domain_numbers").(string),
},
{
"Code": "Version",
"Value": d.Get("version_code").(string),
},
}
request["ClientToken"] = buildClientToken("CreateInstance")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-14"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"NotApplicable"}) {
conn.Endpoint = String(connectivity.BssOpenAPIEndpointInternational)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_alidns_instance", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return WrapErrorf(fmt.Errorf("%v", response), DefaultErrorMsg, "alicloud_alidns_instance", action, AlibabaCloudSdkGoERROR)
}
responseData := response["Data"].(map[string]interface{})
d.SetId(fmt.Sprint(responseData["InstanceId"]))
return resourceAlicloudAlidnsInstanceRead(d, meta)
}
func resourceAlicloudAlidnsInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alidnsService := AlidnsService{client}
object, err := alidnsService.DescribeAlidnsInstance(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_alidns_instance alidnsService.DescribeAlidnsInstance Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("dns_security", convertDnsSecurityResponse(object["DnsSecurity"]))
d.Set("domain_numbers", object["BindDomainCount"])
d.Set("version_code", object["VersionCode"])
d.Set("version_name", object["VersionName"])
res, err := alidnsService.QueryAvailableInstances(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("payment_type", res["SubscriptionType"])
d.Set("renewal_status", res["RenewStatus"])
if fmt.Sprint(res["RenewalDurationUnit"]) == "M" {
d.Set("renew_period", formatInt(res["RenewalDuration"]))
} else {
d.Set("renew_period", formatInt(res["RenewalDuration"])*12)
}
return nil
}
func resourceAlicloudAlidnsInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return resourceAlicloudAlidnsInstanceRead(d, meta)
}
func resourceAlicloudAlidnsInstanceDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudAlidnsInstance. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
func convertDnsSecurityResponse(source interface{}) interface{} {
switch source {
case "DNS Anti-DDoS Advanced":
return "advanced"
case "DNS Anti-DDoS Basic":
return "basic"
case "Not Required":
return "no"
}
return source
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudAlidnsMonitorConfig() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAlidnsMonitorConfigCreate,
Read: resourceAlicloudAlidnsMonitorConfigRead,
Update: resourceAlicloudAlidnsMonitorConfigUpdate,
Delete: resourceAlicloudAlidnsMonitorConfigDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"addr_pool_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"evaluation_count": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3}),
},
"interval": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntInSlice([]int{60}),
},
"isp_city_node": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"city_code": {
Type: schema.TypeString,
Required: true,
},
"isp_code": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"lang": {
Type: schema.TypeString,
Optional: true,
},
"monitor_extend_info": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.ValidateJsonString,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
equal, _ := compareJsonTemplateAreEquivalent(old, new)
return equal
},
},
"protocol_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"HTTP", "HTTPS", "PING", "TCP"}, false),
},
"timeout": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntInSlice([]int{2000, 3000, 5000, 10000}),
},
},
}
}
func resourceAlicloudAlidnsMonitorConfigCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AddDnsGtmMonitor"
request := make(map[string]interface{})
conn, err := client.NewAlidnsClient()
if err != nil {
return WrapError(err)
}
request["AddrPoolId"] = d.Get("addr_pool_id")
request["EvaluationCount"] = d.Get("evaluation_count")
request["Interval"] = d.Get("interval")
if v, ok := d.GetOk("isp_city_node"); ok {
for i, ispCityNode := range v.(*schema.Set).List() {
ispCityNodeArg := ispCityNode.(map[string]interface{})
request[fmt.Sprintf("IspCityNode.%d.CityCode", i+1)] = ispCityNodeArg["city_code"]
request[fmt.Sprintf("IspCityNode.%d.IspCode", i+1)] = ispCityNodeArg["isp_code"]
}
}
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
request["MonitorExtendInfo"] = d.Get("monitor_extend_info")
request["ProtocolType"] = d.Get("protocol_type")
request["Timeout"] = d.Get("timeout")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_alidns_monitor_config", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["MonitorConfigId"]))
return resourceAlicloudAlidnsMonitorConfigRead(d, meta)
}
func resourceAlicloudAlidnsMonitorConfigRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alidnsService := AlidnsService{client}
object, err := alidnsService.DescribeAlidnsMonitorConfig(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_alidns_monitor_config alidnsService.DescribeAlidnsMonitorConfig Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
if v, ok := object["EvaluationCount"]; ok {
d.Set("evaluation_count", formatInt(v))
}
if v, ok := object["Interval"]; ok {
d.Set("interval", formatInt(v))
}
d.Set("monitor_extend_info", object["MonitorExtendInfo"])
d.Set("protocol_type", object["ProtocolType"])
if v, ok := object["Timeout"]; ok {
d.Set("timeout", formatInt(v))
}
if ispCityNodesList, ok := object["IspCityNodes"]; ok {
ispCityNodesArg := ispCityNodesList.(map[string]interface{})
if ispCityNodeConfig, ok := ispCityNodesArg["IspCityNode"]; ok {
ispCityNodeConfigArgs := ispCityNodeConfig.([]interface{})
ispCityNodesMaps := make([]map[string]interface{}, 0)
for _, ispCityNodeMapArgitem := range ispCityNodeConfigArgs {
ispCityNodeMapArg := ispCityNodeMapArgitem.(map[string]interface{})
ispCityNodesMap := map[string]interface{}{}
ispCityNodesMap["city_code"] = ispCityNodeMapArg["CityCode"]
ispCityNodesMap["isp_code"] = ispCityNodeMapArg["IspCode"]
ispCityNodesMaps = append(ispCityNodesMaps, ispCityNodesMap)
}
d.Set("isp_city_node", ispCityNodesMaps)
}
}
return nil
}
func resourceAlicloudAlidnsMonitorConfigUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"MonitorConfigId": d.Id(),
}
if d.HasChange("isp_city_node") {
update = true
}
if v, ok := d.GetOk("isp_city_node"); ok {
for i, ispCityNode := range v.(*schema.Set).List() {
ispCityNodeArg := ispCityNode.(map[string]interface{})
request[fmt.Sprintf("IspCityNode.%d.CityCode", i+1)] = ispCityNodeArg["city_code"]
request[fmt.Sprintf("IspCityNode.%d.IspCode", i+1)] = ispCityNodeArg["isp_code"]
}
}
if d.HasChange("monitor_extend_info") {
update = true
}
request["MonitorExtendInfo"] = d.Get("monitor_extend_info")
if d.HasChange("protocol_type") {
update = true
}
request["ProtocolType"] = d.Get("protocol_type")
if d.HasChange("evaluation_count") {
update = true
request["EvaluationCount"] = d.Get("evaluation_count")
}
if d.HasChange("interval") {
update = true
request["Interval"] = d.Get("interval")
}
if d.HasChange("timeout") {
update = true
request["Timeout"] = d.Get("timeout")
}
if update {
action := "UpdateDnsGtmMonitor"
conn, err := client.NewAlidnsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudAlidnsMonitorConfigRead(d, meta)
}
func resourceAlicloudAlidnsMonitorConfigDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudAlidnsMonitorConfig. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
package alicloud
import (
"fmt"
"log"
"strconv"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/alidns"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudAlidnsRecord() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAlidnsRecordCreate,
Read: resourceAlicloudAlidnsRecordRead,
Update: resourceAlicloudAlidnsRecordUpdate,
Delete: resourceAlicloudAlidnsRecordDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(4 * time.Minute),
Delete: schema.DefaultTimeout(6 * time.Minute),
},
Schema: map[string]*schema.Schema{
"domain_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"lang": {
Type: schema.TypeString,
Optional: true,
},
"line": {
Type: schema.TypeString,
Optional: true,
Default: "default",
},
"priority": {
Type: schema.TypeInt,
Optional: true,
DiffSuppressFunc: dnsPriorityDiffSuppressFunc,
},
"rr": {
Type: schema.TypeString,
Required: true,
},
"remark": {
Type: schema.TypeString,
Optional: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"ENABLE", "DISABLE"}, false),
Default: "ENABLE",
},
"ttl": {
Type: schema.TypeInt,
Optional: true,
Default: 600,
},
"type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"A", "NS", "MX", "TXT", "CNAME", "SRV", "AAAA", "CAA", "REDIRECT_URL", "FORWORD_URL"}, false),
},
"user_client_ip": {
Type: schema.TypeString,
Optional: true,
},
"value": {
Type: schema.TypeString,
Required: true,
DiffSuppressFunc: dnsValueDiffSuppressFunc,
},
},
}
}
func resourceAlicloudAlidnsRecordCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := alidns.CreateAddDomainRecordRequest()
request.DomainName = d.Get("domain_name").(string)
if v, ok := d.GetOk("lang"); ok {
request.Lang = v.(string)
}
if v, ok := d.GetOk("line"); ok {
line := v.(string)
if line != "default" && d.Get("type").(string) == "FORWORD_URL" {
return WrapError(Error("The ForwordURLRecord only support default line."))
}
request.Line = line
}
if v, ok := d.GetOk("priority"); !ok && d.Get("type").(string) == "MX" {
return WrapError(Error("'priority': required field when 'type' is MX."))
} else if ok {
request.Priority = requests.Integer(strconv.Itoa(v.(int)))
}
request.RR = d.Get("rr").(string)
if v, ok := d.GetOk("ttl"); ok {
request.TTL = requests.NewInteger(v.(int))
}
request.Type = d.Get("type").(string)
if v, ok := d.GetOk("user_client_ip"); ok {
request.UserClientIp = v.(string)
}
request.Value = d.Get("value").(string)
wait := incrementalWait(3*time.Second, 10*time.Second)
err := resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
raw, err := client.WithAlidnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.AddDomainRecord(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InternalError", "LastOperationNotFinished"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw)
response, _ := raw.(*alidns.AddDomainRecordResponse)
d.SetId(fmt.Sprintf("%v", response.RecordId))
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_alidns_record", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return resourceAlicloudAlidnsRecordUpdate(d, meta)
}
func resourceAlicloudAlidnsRecordRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alidnsService := AlidnsService{client}
object, err := alidnsService.DescribeAlidnsRecord(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_alidns_record alidnsService.DescribeAlidnsRecord Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("domain_name", object.DomainName)
d.Set("line", object.Line)
d.Set("priority", object.Priority)
d.Set("rr", object.RR)
d.Set("status", object.Status)
d.Set("ttl", object.TTL)
d.Set("type", object.Type)
d.Set("value", object.Value)
return nil
}
func resourceAlicloudAlidnsRecordUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
d.Partial(true)
update := false
request := alidns.CreateSetDomainRecordStatusRequest()
request.RecordId = d.Id()
if d.HasChange("status") {
update = true
}
request.Status = d.Get("status").(string)
if !d.IsNewResource() && d.HasChange("lang") {
update = true
}
request.Lang = d.Get("lang").(string)
if !d.IsNewResource() && d.HasChange("user_client_ip") {
update = true
}
request.UserClientIp = d.Get("user_client_ip").(string)
if update {
raw, err := client.WithAlidnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.SetDomainRecordStatus(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("status")
d.SetPartial("lang")
d.SetPartial("user_client_ip")
}
update = false
updateDomainRecordRemarkReq := alidns.CreateUpdateDomainRecordRemarkRequest()
updateDomainRecordRemarkReq.RecordId = d.Id()
updateDomainRecordRemarkReq.Lang = d.Get("lang").(string)
if d.HasChange("remark") {
update = true
}
updateDomainRecordRemarkReq.Remark = d.Get("remark").(string)
updateDomainRecordRemarkReq.UserClientIp = d.Get("user_client_ip").(string)
if update {
raw, err := client.WithAlidnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.UpdateDomainRecordRemark(updateDomainRecordRemarkReq)
})
addDebug(updateDomainRecordRemarkReq.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), updateDomainRecordRemarkReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("remark")
}
update = false
updateDomainRecordReq := alidns.CreateUpdateDomainRecordRequest()
updateDomainRecordReq.RecordId = d.Id()
if !d.IsNewResource() && d.HasChange("rr") {
update = true
}
updateDomainRecordReq.RR = d.Get("rr").(string)
if !d.IsNewResource() && d.HasChange("type") {
update = true
}
updateDomainRecordReq.Type = d.Get("type").(string)
if !d.IsNewResource() && d.HasChange("value") {
update = true
}
updateDomainRecordReq.Value = d.Get("value").(string)
updateDomainRecordReq.Lang = d.Get("lang").(string)
if !d.IsNewResource() && d.HasChange("line") {
update = true
}
updateDomainRecordReq.Line = d.Get("line").(string)
if updateDomainRecordReq.Type == "MX" {
if !d.IsNewResource() && d.HasChange("priority") {
update = true
}
updateDomainRecordReq.Priority = requests.NewInteger(d.Get("priority").(int))
}
if !d.IsNewResource() && d.HasChange("ttl") {
update = true
}
updateDomainRecordReq.TTL = requests.NewInteger(d.Get("ttl").(int))
updateDomainRecordReq.UserClientIp = d.Get("user_client_ip").(string)
if update {
raw, err := client.WithAlidnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.UpdateDomainRecord(updateDomainRecordReq)
})
addDebug(updateDomainRecordReq.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), updateDomainRecordReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("rr")
d.SetPartial("type")
d.SetPartial("value")
d.SetPartial("line")
d.SetPartial("ttl")
}
d.Partial(false)
return resourceAlicloudAlidnsRecordRead(d, meta)
}
func resourceAlicloudAlidnsRecordDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := alidns.CreateDeleteDomainRecordRequest()
request.RecordId = d.Id()
if v, ok := d.GetOk("lang"); ok {
request.Lang = v.(string)
}
if v, ok := d.GetOk("user_client_ip"); ok {
request.UserClientIp = v.(string)
}
wait := incrementalWait(3*time.Second, 10*time.Second)
err := resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
raw, err := client.WithAlidnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.DeleteDomainRecord(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InternalError", "RecordForbidden.DNSChange"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"DomainRecordNotBelongToUser"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/alikafka"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudAlikafkaConsumerGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAlikafkaConsumerGroupCreate,
Update: resourceAlicloudAlikafkaConsumerGroupUpdate,
Read: resourceAlicloudAlikafkaConsumerGroupRead,
Delete: resourceAlicloudAlikafkaConsumerGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"consumer_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(1, 64),
},
"tags": tagsSchema(),
},
}
}
func resourceAlicloudAlikafkaConsumerGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alikafkaService := AlikafkaService{client}
instanceId := d.Get("instance_id").(string)
regionId := client.RegionId
consumerId := d.Get("consumer_id").(string)
request := alikafka.CreateCreateConsumerGroupRequest()
request.InstanceId = instanceId
request.RegionId = regionId
request.ConsumerId = consumerId
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.CreateConsumerGroup(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_alikafka_consumer_group", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetId(instanceId + ":" + consumerId)
return resourceAlicloudAlikafkaConsumerGroupUpdate(d, meta)
}
func resourceAlicloudAlikafkaConsumerGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alikafkaService := AlikafkaService{client}
object, err := alikafkaService.DescribeAlikafkaConsumerGroup(d.Id())
if err != nil {
// Handle exceptions
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_id", object.InstanceId)
d.Set("consumer_id", object.ConsumerId)
tags, err := alikafkaService.DescribeTags(d.Id(), nil, TagResourceConsumerGroup)
if err != nil {
return WrapError(err)
}
d.Set("tags", alikafkaService.tagsToMap(tags))
return nil
}
func resourceAlicloudAlikafkaConsumerGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alikafkaService := AlikafkaService{client}
if err := alikafkaService.setInstanceTags(d, TagResourceConsumerGroup); err != nil {
return WrapError(err)
}
return resourceAlicloudAlikafkaConsumerGroupRead(d, meta)
}
func resourceAlicloudAlikafkaConsumerGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alikafkaService := AlikafkaService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
instanceId := parts[0]
consumerId := parts[1]
request := alikafka.CreateDeleteConsumerGroupRequest()
request.ConsumerId = consumerId
request.InstanceId = instanceId
request.RegionId = client.RegionId
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.DeleteConsumerGroup(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(alikafkaService.WaitForAlikafkaConsumerGroup(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"errors"
"strconv"
"time"
"github.com/denverdino/aliyungo/common"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/alikafka"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudAlikafkaInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAlikafkaInstanceCreate,
Read: resourceAlicloudAlikafkaInstanceRead,
Update: resourceAlicloudAlikafkaInstanceUpdate,
Delete: resourceAlicloudAlikafkaInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringLenBetween(3, 64),
},
"topic_quota": {
Type: schema.TypeInt,
Required: true,
},
"disk_type": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
},
"disk_size": {
Type: schema.TypeInt,
Required: true,
},
"deploy_type": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
},
"io_max": {
Type: schema.TypeInt,
Required: true,
},
"paid_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{string(common.PrePaid), string(common.PostPaid)}, false),
Default: PostPaid,
},
"spec_type": {
Type: schema.TypeString,
Optional: true,
Default: "normal",
},
"eip_max": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"security_group": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"vswitch_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"service_version": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"config": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.ValidateJsonString,
DiffSuppressFunc: alikafkaInstanceConfigDiffSuppressFunc,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
"end_point": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
},
}
}
func resourceAlicloudAlikafkaInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alikafkaService := AlikafkaService{client}
vpcService := VpcService{client}
regionId := client.RegionId
topicQuota := d.Get("topic_quota").(int)
diskType := d.Get("disk_type").(int)
diskSize := d.Get("disk_size").(int)
deployType := d.Get("deploy_type").(int)
ioMax := d.Get("io_max").(int)
vswitchId := d.Get("vswitch_id").(string)
paidType := d.Get("paid_type").(string)
specType := d.Get("spec_type").(string)
// Get vswitch info by vswitchId
vsw, err := vpcService.DescribeVSwitch(vswitchId)
if err != nil {
return WrapError(err)
}
// 1. Create order
createOrderReq := alikafka.CreateCreatePostPayOrderRequest()
createOrderReq.RegionId = regionId
createOrderReq.TopicQuota = requests.NewInteger(topicQuota)
createOrderReq.DiskType = strconv.Itoa(diskType)
createOrderReq.DiskSize = requests.NewInteger(diskSize)
createOrderReq.DeployType = requests.NewInteger(deployType)
createOrderReq.IoMax = requests.NewInteger(ioMax)
createOrderReq.PaidType = requests.NewInteger(1)
createOrderReq.SpecType = specType
if paidType == string(PrePaid) {
createOrderReq.PaidType = requests.NewInteger(0)
}
if v, ok := d.GetOk("eip_max"); ok {
createOrderReq.EipMax = requests.NewInteger(v.(int))
}
var createOrderResp *alikafka.CreatePostPayOrderResponse
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.CreatePostPayOrder(createOrderReq)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL", "ONS_SYSTEM_ERROR"}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(createOrderReq.GetActionName(), raw, createOrderReq.RpcRequest, createOrderReq)
v, _ := raw.(*alikafka.CreatePostPayOrderResponse)
createOrderResp = v
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_alikafka_instance", createOrderReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
alikafkaInstanceVO, err := alikafkaService.DescribeAlikafkaInstanceByOrderId(createOrderResp.OrderId, 60)
if err != nil {
return WrapError(err)
}
instanceId := alikafkaInstanceVO.InstanceId
d.SetId(instanceId)
// 3. Start instance
startInstanceReq := alikafka.CreateStartInstanceRequest()
startInstanceReq.RegionId = regionId
startInstanceReq.InstanceId = instanceId
startInstanceReq.VpcId = vsw.VpcId
startInstanceReq.VSwitchId = vswitchId
startInstanceReq.ZoneId = vsw.ZoneId
if _, ok := d.GetOk("eip_max"); ok {
startInstanceReq.IsEipInner = requests.NewBoolean(true)
startInstanceReq.DeployModule = "eip"
}
if v, ok := d.GetOk("name"); ok {
startInstanceReq.Name = v.(string)
}
if v, ok := d.GetOk("security_group"); ok {
startInstanceReq.SecurityGroup = v.(string)
}
if v, ok := d.GetOk("service_version"); ok {
startInstanceReq.ServiceVersion = v.(string)
}
if v, ok := d.GetOk("config"); ok {
startInstanceReq.Config = v.(string)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.StartInstance(startInstanceReq)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(startInstanceReq.GetActionName(), raw, startInstanceReq.RpcRequest, startInstanceReq)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_alikafka_instance", startInstanceReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
// 3. wait until running
err = alikafkaService.WaitForAlikafkaInstance(d.Id(), Running, DefaultLongTimeout)
if err != nil {
return WrapError(err)
}
return resourceAlicloudAlikafkaInstanceUpdate(d, meta)
}
func resourceAlicloudAlikafkaInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alikafkaService := AlikafkaService{client}
object, err := alikafkaService.DescribeAlikafkaInstance(d.Id())
if err != nil {
// Handle exceptions
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", object.Name)
d.Set("topic_quota", object.TopicNumLimit)
d.Set("disk_type", object.DiskType)
d.Set("disk_size", object.DiskSize)
d.Set("deploy_type", object.DeployType)
d.Set("io_max", object.IoMax)
d.Set("eip_max", object.EipMax)
d.Set("vpc_id", object.VpcId)
d.Set("vswitch_id", object.VSwitchId)
d.Set("zone_id", object.ZoneId)
d.Set("paid_type", PostPaid)
d.Set("spec_type", object.SpecType)
d.Set("security_group", object.SecurityGroup)
d.Set("end_point", object.EndPoint)
// object.UpgradeServiceDetailInfo.UpgradeServiceDetailInfoVO[0].Current2OpenSourceVersion can guaranteed not to be null
d.Set("service_version", object.UpgradeServiceDetailInfo.Current2OpenSourceVersion)
d.Set("config", object.AllConfig)
if object.PaidType == 0 {
d.Set("paid_type", PrePaid)
}
tags, err := alikafkaService.DescribeTags(d.Id(), nil, TagResourceInstance)
if err != nil {
return WrapError(err)
}
d.Set("tags", alikafkaService.tagsToMap(tags))
return nil
}
func resourceAlicloudAlikafkaInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alikafkaService := AlikafkaService{client}
d.Partial(true)
if err := alikafkaService.setInstanceTags(d, TagResourceInstance); err != nil {
return WrapError(err)
}
if d.IsNewResource() {
d.Partial(false)
return resourceAlicloudAlikafkaInstanceRead(d, meta)
}
// Process change instance name.
if d.HasChange("name") {
var name string
if v, ok := d.GetOk("name"); ok {
name = v.(string)
}
modifyInstanceNameReq := alikafka.CreateModifyInstanceNameRequest()
modifyInstanceNameReq.RegionId = client.RegionId
modifyInstanceNameReq.InstanceId = d.Id()
modifyInstanceNameReq.InstanceName = name
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.ModifyInstanceName(modifyInstanceNameReq)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(modifyInstanceNameReq.GetActionName(), raw, modifyInstanceNameReq.RpcRequest, modifyInstanceNameReq)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), modifyInstanceNameReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("name")
}
// Process paid type change, note only support change from post to pre pay.
if d.HasChange("paid_type") {
o, n := d.GetChange("paid_type")
oldPaidType := o.(string)
newPaidType := n.(string)
oldPaidTypeInt := 1
newPaidTypeInt := 1
if oldPaidType == string(PrePaid) {
oldPaidTypeInt = 0
}
if newPaidType == string(PrePaid) {
newPaidTypeInt = 0
}
if oldPaidTypeInt == 1 && newPaidTypeInt == 0 {
convertPostPayOrderReq := alikafka.CreateConvertPostPayOrderRequest()
convertPostPayOrderReq.InstanceId = d.Id()
convertPostPayOrderReq.RegionId = client.RegionId
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.ConvertPostPayOrder(convertPostPayOrderReq)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(convertPostPayOrderReq.GetActionName(), raw, convertPostPayOrderReq.RpcRequest, convertPostPayOrderReq)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), convertPostPayOrderReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
// Make sure convert success
object, err := alikafkaService.DescribeAlikafkaInstance(d.Id())
if err != nil {
return WrapError(err)
}
err = alikafkaService.WaitForAlikafkaInstanceUpdated(d.Id(), object.TopicNumLimit,
object.DiskSize, object.IoMax, object.EipMax, newPaidTypeInt, object.SpecType, DefaultTimeoutMedium)
if err != nil {
return WrapError(err)
}
} else {
return WrapError(errors.New("paid type only support change from post pay to pre pay"))
}
d.SetPartial("paid_type")
}
attributeUpdate := false
upgradeReq := alikafka.CreateUpgradePostPayOrderRequest()
upgradeReq.RegionId = client.RegionId
upgradeReq.InstanceId = d.Id()
upgradeReq.TopicQuota = requests.NewInteger(d.Get("topic_quota").(int))
upgradeReq.DiskSize = requests.NewInteger(d.Get("disk_size").(int))
upgradeReq.IoMax = requests.NewInteger(d.Get("io_max").(int))
upgradeReq.SpecType = d.Get("spec_type").(string)
if d.HasChange("topic_quota") || d.HasChange("disk_size") || d.HasChange("io_max") || d.HasChange("spec_type") {
attributeUpdate = true
}
eipMax := 0
if v, ok := d.GetOk("eip_max"); ok {
eipMax = v.(int)
}
if d.HasChange("eip_max") {
if v, ok := d.GetOk("eip_max"); ok {
eipMax = v.(int)
}
upgradeReq.EipMax = requests.NewInteger(eipMax)
attributeUpdate = true
}
if attributeUpdate {
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.UpgradePostPayOrder(upgradeReq)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(upgradeReq.GetActionName(), raw, upgradeReq.RpcRequest, upgradeReq)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), upgradeReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("topic_quota")
d.SetPartial("disk_size")
d.SetPartial("io_max")
d.SetPartial("spec_type")
d.SetPartial("eip_max")
}
paidType := 1
if d.Get("paid_type").(string) == string(PrePaid) {
paidType = 0
}
err := alikafkaService.WaitForAlikafkaInstanceUpdated(d.Id(), d.Get("topic_quota").(int), d.Get("disk_size").(int),
d.Get("io_max").(int), eipMax, paidType, d.Get("spec_type").(string), DefaultTimeoutMedium)
if err != nil {
return WrapError(err)
}
err = alikafkaService.WaitForAlikafkaInstance(d.Id(), Running, 6000)
if err != nil {
return WrapError(err)
}
if d.HasChange("service_version") {
var serviceVersion string
if v, ok := d.GetOk("service_version"); ok {
serviceVersion = v.(string)
}
upgradeInstanceVersionReq := alikafka.CreateUpgradeInstanceVersionRequest()
upgradeInstanceVersionReq.RegionId = client.RegionId
upgradeInstanceVersionReq.InstanceId = d.Id()
upgradeInstanceVersionReq.TargetVersion = serviceVersion
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.UpgradeInstanceVersion(upgradeInstanceVersionReq)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
// means no need to update version
if IsExpectedErrors(err, []string{"ONS_INIT_ENV_ERROR"}) {
return nil
}
return resource.NonRetryableError(err)
}
addDebug(upgradeInstanceVersionReq.GetActionName(), raw, upgradeInstanceVersionReq.RpcRequest, upgradeInstanceVersionReq)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), upgradeInstanceVersionReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
// wait for upgrade task be invoke
time.Sleep(60 * time.Second)
// upgrade service may be last a long time
err = alikafkaService.WaitForAlikafkaInstance(d.Id(), Running, 10000)
if err != nil {
return WrapError(err)
}
d.SetPartial("service_version")
}
if d.HasChange("config") {
var config string
if v, ok := d.GetOk("config"); ok {
config = v.(string)
}
upgradeInstanceConfigReq := alikafka.CreateUpdateInstanceConfigRequest()
upgradeInstanceConfigReq.RegionId = client.RegionId
upgradeInstanceConfigReq.InstanceId = d.Id()
upgradeInstanceConfigReq.Config = config
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.UpdateInstanceConfig(upgradeInstanceConfigReq)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(upgradeInstanceConfigReq.GetActionName(), raw, upgradeInstanceConfigReq.RpcRequest, upgradeInstanceConfigReq)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), upgradeInstanceConfigReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
// wait for upgrade task be invoke
time.Sleep(60 * time.Second)
err = alikafkaService.WaitForAlikafkaInstance(d.Id(), Running, 6000)
if err != nil {
return WrapError(err)
}
d.SetPartial("config")
}
d.Partial(false)
return resourceAlicloudAlikafkaInstanceRead(d, meta)
}
func resourceAlicloudAlikafkaInstanceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alikafkaService := AlikafkaService{client}
// Pre paid instance can not be release.
if d.Get("paid_type").(string) == string(PrePaid) {
return nil
}
request := alikafka.CreateReleaseInstanceRequest()
request.InstanceId = d.Id()
request.RegionId = client.RegionId
request.ReleaseIgnoreTime = requests.NewBoolean(true)
request.ForceDeleteInstance = requests.NewBoolean(true)
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.ReleaseInstance(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(alikafkaService.WaitForAllAlikafkaNodeRelease(d.Id(), "released", DefaultTimeoutMedium))
}
package alicloud
import (
"fmt"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/alikafka"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudAlikafkaSaslAcl() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAlikafkaSaslAclCreate,
Read: resourceAlicloudAlikafkaSaslAclRead,
Delete: resourceAlicloudAlikafkaSaslAclDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"username": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(1, 64),
},
"acl_resource_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Group", "Topic"}, false),
},
"acl_resource_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(1, 64),
},
"acl_resource_pattern_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"LITERAL", "PREFIXED"}, false),
},
"acl_operation_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Read", "Write"}, false),
},
"host": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudAlikafkaSaslAclCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alikafkaService := AlikafkaService{client}
instanceId := d.Get("instance_id").(string)
regionId := client.RegionId
username := d.Get("username").(string)
aclResourceType := d.Get("acl_resource_type").(string)
aclResourceName := d.Get("acl_resource_name").(string)
aclResourcePatternType := d.Get("acl_resource_pattern_type").(string)
aclOperationType := d.Get("acl_operation_type").(string)
request := alikafka.CreateCreateAclRequest()
request.InstanceId = instanceId
request.RegionId = regionId
request.Username = username
request.AclResourceType = aclResourceType
request.AclResourceName = aclResourceName
request.AclResourcePatternType = aclResourcePatternType
request.AclOperationType = aclOperationType
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.CreateAcl(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
time.Sleep(2 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_alikafka_sasl_acl", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
// Server may have cache, sleep a while.
time.Sleep(60 * time.Second)
d.SetId(fmt.Sprintf("%s:%s:%s:%s:%s:%s", instanceId, username, aclResourceType, aclResourceName, aclResourcePatternType, aclOperationType))
return resourceAlicloudAlikafkaSaslAclRead(d, meta)
}
func resourceAlicloudAlikafkaSaslAclRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alikafkaService := AlikafkaService{client}
parts, err := ParseResourceId(d.Id(), 6)
if err != nil {
return WrapError(err)
}
object, err := alikafkaService.DescribeAlikafkaSaslAcl(d.Id())
if err != nil {
// Handle exceptions
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_id", parts[0])
d.Set("username", object.Username)
d.Set("acl_resource_type", object.AclResourceType)
d.Set("acl_resource_name", object.AclResourceName)
d.Set("acl_resource_pattern_type", object.AclResourcePatternType)
d.Set("acl_operation_type", object.AclOperationType)
d.Set("host", object.Host)
return nil
}
func resourceAlicloudAlikafkaSaslAclDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alikafkaService := AlikafkaService{client}
parts, err := ParseResourceId(d.Id(), 6)
if err != nil {
return WrapError(err)
}
instanceId := parts[0]
username := parts[1]
aclResourceType := parts[2]
aclResourceName := parts[3]
aclResourcePatternType := parts[4]
aclOperationType := parts[5]
request := alikafka.CreateDeleteAclRequest()
request.RegionId = client.RegionId
request.InstanceId = instanceId
request.Username = username
request.AclResourceType = aclResourceType
request.AclResourceName = aclResourceName
request.AclResourcePatternType = aclResourcePatternType
request.AclOperationType = aclOperationType
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.DeleteAcl(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
// Server may have cache, sleep a while.
time.Sleep(60 * time.Second)
return WrapError(alikafkaService.WaitForAlikafkaSaslAcl(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/alikafka"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudAlikafkaSaslUser() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAlikafkaSaslUserCreate,
Read: resourceAlicloudAlikafkaSaslUserRead,
Update: resourceAlicloudAlikafkaSaslUserUpdate,
Delete: resourceAlicloudAlikafkaSaslUserDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"username": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(1, 64),
},
"password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
ValidateFunc: validation.StringLenBetween(1, 64),
},
"kms_encrypted_password": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: kmsDiffSuppressFunc,
},
"kms_encryption_context": {
Type: schema.TypeMap,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("kms_encrypted_password").(string) == ""
},
Elem: schema.TypeString,
},
},
}
}
func resourceAlicloudAlikafkaSaslUserCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alikafkaService := AlikafkaService{client}
instanceId := d.Get("instance_id").(string)
regionId := client.RegionId
username := d.Get("username").(string)
password := d.Get("password").(string)
kmsPassword := d.Get("kms_encrypted_password").(string)
if password == "" && kmsPassword == "" {
return WrapError(Error("One of the 'password' and 'kms_encrypted_password' should be set."))
}
request := alikafka.CreateCreateSaslUserRequest()
request.InstanceId = instanceId
request.RegionId = regionId
request.Username = username
if password != "" {
request.Password = password
} else {
kmsService := KmsService{client}
decryptResp, err := kmsService.Decrypt(kmsPassword, d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request.Password = decryptResp
}
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.CreateSaslUser(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
time.Sleep(2 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_alikafka_sasl_user", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
// Server may have cache, sleep a while.
time.Sleep(2 * time.Second)
d.SetId(instanceId + ":" + username)
return resourceAlicloudAlikafkaSaslUserUpdate(d, meta)
}
func resourceAlicloudAlikafkaSaslUserRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alikafkaService := AlikafkaService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
object, err := alikafkaService.DescribeAlikafkaSaslUser(d.Id())
if err != nil {
// Handle exceptions
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_id", parts[0])
d.Set("username", object.Username)
return nil
}
func resourceAlicloudAlikafkaSaslUserUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alikafkaService := AlikafkaService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
instanceId := parts[0]
username := parts[1]
if d.HasChange("password") || d.HasChange("kms_encrypted_password") {
request := alikafka.CreateCreateSaslUserRequest()
request.InstanceId = instanceId
request.RegionId = client.RegionId
request.Username = username
password := d.Get("password").(string)
kmsPassword := d.Get("kms_encrypted_password").(string)
if password == "" && kmsPassword == "" {
return WrapError(Error("One of the 'password' and 'kms_encrypted_password' should be set."))
}
if password != "" {
request.Password = password
} else {
kmsService := KmsService{client}
decryptResp, err := kmsService.Decrypt(kmsPassword, d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request.Password = decryptResp
}
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.CreateSaslUser(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
time.Sleep(2 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_alikafka_sasl_user", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
// Server may have cache, sleep a while.
time.Sleep(1000)
}
return resourceAlicloudAlikafkaSaslUserRead(d, meta)
}
func resourceAlicloudAlikafkaSaslUserDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alikafkaService := AlikafkaService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
instanceId := parts[0]
username := parts[1]
request := alikafka.CreateDeleteSaslUserRequest()
request.RegionId = client.RegionId
request.InstanceId = instanceId
request.Username = username
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.DeleteSaslUser(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(alikafkaService.WaitForAlikafkaSaslUser(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"errors"
"strconv"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/alikafka"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudAlikafkaTopic() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAlikafkaTopicCreate,
Update: resourceAlicloudAlikafkaTopicUpdate,
Read: resourceAlicloudAlikafkaTopicRead,
Delete: resourceAlicloudAlikafkaTopicDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"topic": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(1, 64),
},
"local_topic": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: false,
},
"compact_topic": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: false,
},
"partition_num": {
Type: schema.TypeInt,
Optional: true,
Default: 12,
ValidateFunc: validation.IntBetween(0, 360),
},
"remark": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(1, 64),
},
"tags": tagsSchema(),
},
}
}
func resourceAlicloudAlikafkaTopicCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alikafkaService := AlikafkaService{client}
instanceId := d.Get("instance_id").(string)
regionId := client.RegionId
topic := d.Get("topic").(string)
request := alikafka.CreateCreateTopicRequest()
request.InstanceId = instanceId
request.RegionId = regionId
request.Topic = topic
if v, ok := d.GetOk("local_topic"); ok {
request.LocalTopic = requests.NewBoolean(v.(bool))
}
if v, ok := d.GetOk("compact_topic"); ok {
request.CompactTopic = requests.NewBoolean(v.(bool))
}
if v, ok := d.GetOk("partition_num"); ok {
request.PartitionNum = strconv.Itoa(v.(int))
}
if v, ok := d.GetOk("remark"); ok {
request.Remark = v.(string)
}
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.CreateTopic(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_alikafka_topic", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetId(instanceId + ":" + topic)
// wait topic status change from Creating to running
stateConf := BuildStateConf([]string{"Creating"}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, alikafkaService.KafkaTopicStatusRefreshFunc(d.Id()))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudAlikafkaTopicUpdate(d, meta)
}
func resourceAlicloudAlikafkaTopicUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alikafkaService := AlikafkaService{client}
d.Partial(true)
if err := alikafkaService.setInstanceTags(d, TagResourceTopic); err != nil {
return WrapError(err)
}
if d.IsNewResource() {
d.Partial(false)
return resourceAlicloudAlikafkaTopicRead(d, meta)
}
instanceId := d.Get("instance_id").(string)
if d.HasChange("remark") {
remark := d.Get("remark").(string)
topic := d.Get("topic").(string)
modifyRemarkRequest := alikafka.CreateModifyTopicRemarkRequest()
modifyRemarkRequest.InstanceId = instanceId
modifyRemarkRequest.RegionId = client.RegionId
modifyRemarkRequest.Topic = topic
modifyRemarkRequest.Remark = remark
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.ModifyTopicRemark(modifyRemarkRequest)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(modifyRemarkRequest.GetActionName(), raw, modifyRemarkRequest.RpcRequest, modifyRemarkRequest)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), modifyRemarkRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("remark")
}
if d.HasChange("partition_num") {
o, n := d.GetChange("partition_num")
oldPartitionNum := o.(int)
newPartitionNum := n.(int)
if newPartitionNum < oldPartitionNum {
return WrapError(errors.New("partition_num only support adjust to a greater value."))
} else {
topic := d.Get("topic").(string)
modifyPartitionReq := alikafka.CreateModifyPartitionNumRequest()
modifyPartitionReq.InstanceId = instanceId
modifyPartitionReq.RegionId = client.RegionId
modifyPartitionReq.Topic = topic
modifyPartitionReq.AddPartitionNum = requests.NewInteger(newPartitionNum - oldPartitionNum)
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.ModifyPartitionNum(modifyPartitionReq)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(modifyPartitionReq.GetActionName(), raw, modifyPartitionReq.RpcRequest, modifyPartitionReq)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), modifyPartitionReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("partition_num")
}
}
d.Partial(false)
return resourceAlicloudAlikafkaTopicRead(d, meta)
}
func resourceAlicloudAlikafkaTopicRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alikafkaService := AlikafkaService{client}
object, err := alikafkaService.DescribeAlikafkaTopic(d.Id())
if err != nil {
// Handle exceptions
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_id", object.InstanceId)
d.Set("topic", object.Topic)
d.Set("local_topic", object.LocalTopic)
d.Set("compact_topic", object.CompactTopic)
d.Set("partition_num", object.PartitionNum)
d.Set("remark", object.Remark)
tags, err := alikafkaService.DescribeTags(d.Id(), nil, TagResourceTopic)
if err != nil {
return WrapError(err)
}
d.Set("tags", alikafkaService.tagsToMap(tags))
return nil
}
func resourceAlicloudAlikafkaTopicDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
alikafkaService := AlikafkaService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
instanceId := parts[0]
topic := parts[1]
request := alikafka.CreateDeleteTopicRequest()
request.Topic = topic
request.InstanceId = instanceId
request.RegionId = client.RegionId
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.DeleteTopic(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(alikafkaService.WaitForAlikafkaTopic(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudAmqpBinding() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAmqpBindingCreate,
Read: resourceAlicloudAmqpBindingRead,
Delete: resourceAlicloudAmqpBindingDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"argument": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"x-match:all", "x-match:any"}, false),
},
"binding_key": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"binding_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"EXCHANGE", "QUEUE"}, false),
},
"destination_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"source_exchange": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"virtual_host_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudAmqpBindingCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateBinding"
request := make(map[string]interface{})
conn, err := client.NewOnsproxyClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("argument"); ok {
request["Argument"] = v
}
request["BindingKey"] = d.Get("binding_key")
request["BindingType"] = d.Get("binding_type")
request["DestinationName"] = d.Get("destination_name")
request["InstanceId"] = d.Get("instance_id")
request["SourceExchange"] = d.Get("source_exchange")
request["VirtualHost"] = d.Get("virtual_host_name")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_amqp_binding", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["InstanceId"], ":", request["VirtualHost"], ":", request["SourceExchange"], ":", request["DestinationName"]))
return resourceAlicloudAmqpBindingRead(d, meta)
}
func resourceAlicloudAmqpBindingRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
amqpOpenService := AmqpOpenService{client}
object, err := amqpOpenService.DescribeAmqpBinding(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_amqp_binding amqpOpenService.DescribeAmqpBinding Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 4)
if err != nil {
return WrapError(err)
}
d.Set("destination_name", parts[3])
d.Set("instance_id", parts[0])
d.Set("source_exchange", parts[2])
d.Set("virtual_host_name", parts[1])
d.Set("argument", object["Argument"])
d.Set("binding_key", object["BindingKey"])
d.Set("binding_type", object["BindingType"])
return nil
}
func resourceAlicloudAmqpBindingDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 4)
if err != nil {
return WrapError(err)
}
action := "DeleteBinding"
var response map[string]interface{}
conn, err := client.NewOnsproxyClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DestinationName": parts[3],
"InstanceId": parts[0],
"SourceExchange": parts[2],
"VirtualHost": parts[1],
}
request["BindingKey"] = d.Get("binding_key")
request["BindingType"] = d.Get("binding_type")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudAmqpExchange() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAmqpExchangeCreate,
Read: resourceAlicloudAmqpExchangeRead,
Update: resourceAlicloudAmqpExchangeUpdate,
Delete: resourceAlicloudAmqpExchangeDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"alternate_exchange": {
Type: schema.TypeString,
Optional: true,
},
"auto_delete_state": {
Type: schema.TypeBool,
Required: true,
ForceNew: true,
},
"exchange_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"exchange_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"DIRECT", "FANOUT", "HEADERS", "TOPIC"}, false),
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"internal": {
Type: schema.TypeBool,
Required: true,
},
"virtual_host_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudAmqpExchangeCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateExchange"
request := make(map[string]interface{})
conn, err := client.NewOnsproxyClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("alternate_exchange"); ok {
request["AlternateExchange"] = v
}
request["AutoDeleteState"] = d.Get("auto_delete_state")
request["ExchangeName"] = d.Get("exchange_name")
request["ExchangeType"] = d.Get("exchange_type")
request["InstanceId"] = d.Get("instance_id")
request["Internal"] = d.Get("internal")
request["VirtualHost"] = d.Get("virtual_host_name")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_amqp_exchange", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["InstanceId"], ":", request["VirtualHost"], ":", request["ExchangeName"]))
return resourceAlicloudAmqpExchangeRead(d, meta)
}
func resourceAlicloudAmqpExchangeRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
amqpOpenService := AmqpOpenService{client}
object, err := amqpOpenService.DescribeAmqpExchange(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_amqp_exchange amqpOpenService.DescribeAmqpExchange Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
d.Set("exchange_name", parts[2])
d.Set("instance_id", parts[0])
d.Set("virtual_host_name", parts[1])
d.Set("auto_delete_state", object["AutoDeleteState"])
d.Set("exchange_type", object["ExchangeType"])
return nil
}
func resourceAlicloudAmqpExchangeUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return resourceAlicloudAmqpExchangeRead(d, meta)
}
func resourceAlicloudAmqpExchangeDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
action := "DeleteExchange"
var response map[string]interface{}
conn, err := client.NewOnsproxyClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ExchangeName": parts[2],
"InstanceId": parts[0],
"VirtualHost": parts[1],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudAmqpInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAmqpInstanceCreate,
Read: resourceAlicloudAmqpInstanceRead,
Update: resourceAlicloudAmqpInstanceUpdate,
Delete: resourceAlicloudAmqpInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(60 * time.Minute),
},
Schema: map[string]*schema.Schema{
"instance_name": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"instance_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"professional", "vip"}, false),
},
"logistics": {
Type: schema.TypeString,
Optional: true,
},
"max_eip_tps": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOkExists("support_eip"); ok && v.(bool) {
return false
}
return true
},
},
"max_tps": {
Type: schema.TypeString,
Required: true,
},
"modify_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Downgrade", "Upgrade"}, false),
},
"payment_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"Subscription"}, false),
},
"period": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{1, 12, 2, 24, 3, 6}),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("payment_type"); ok && v.(string) == "Subscription" {
return false
}
return true
},
},
"queue_capacity": {
Type: schema.TypeString,
Required: true,
},
"renewal_duration": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{1, 12, 2, 3, 6}),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("payment_type"); ok && v.(string) == "Subscription" {
if v, ok := d.GetOk("renewal_status"); ok && v.(string) == "AutoRenewal" {
return false
}
}
return true
},
},
"renewal_duration_unit": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Month", "Year"}, false),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("payment_type"); ok && v.(string) == "Subscription" {
if v, ok := d.GetOk("renewal_status"); ok && v.(string) == "AutoRenewal" {
return false
}
}
return true
},
},
"renewal_status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"AutoRenewal", "ManualRenewal", "NotRenewal"}, false),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("payment_type"); ok && v.(string) == "Subscription" {
return false
}
return true
},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"storage_size": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("instance_type"); ok && v.(string) == "vip" {
return false
}
return true
},
},
"support_eip": {
Type: schema.TypeBool,
Required: true,
},
},
}
}
func resourceAlicloudAmqpInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateInstance"
request := make(map[string]interface{})
parameterMapList := make([]map[string]interface{}, 0)
conn, err := client.NewBssopenapiClient()
if err != nil {
return WrapError(err)
}
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "InstanceType",
"Value": d.Get("instance_type"),
})
if v, ok := d.GetOk("logistics"); ok {
request["Logistics"] = v
}
if v, ok := d.GetOk("max_eip_tps"); ok {
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "MaxEipTps",
"Value": v,
})
} else if v, ok := d.GetOkExists("support_eip"); ok && v.(bool) {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is %v ", "max_eip_tps", "support_eip", d.Get("support_eip")))
}
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "MaxTps",
"Value": d.Get("max_tps"),
})
request["SubscriptionType"] = d.Get("payment_type")
if v, ok := d.GetOk("period"); ok {
request["Period"] = v
}
request["ProductCode"] = "ons"
request["ProductType"] = "ons_onsproxy_pre"
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "QueueCapacity",
"Value": d.Get("queue_capacity"),
})
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "Region",
"Value": client.RegionId,
})
if v, ok := d.GetOk("renewal_duration"); ok {
request["RenewPeriod"] = v
} else if v, ok := d.GetOk("renewal_status"); ok && v.(string) == "AutoRenewal" {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is %v ", "renewal_duration", "renewal_status", d.Get("renewal_status")))
}
if v, ok := d.GetOk("renewal_status"); ok {
request["RenewalStatus"] = v
}
if v, ok := d.GetOk("storage_size"); ok {
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "StorageSize",
"Value": v,
})
}
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "SupportEip",
"Value": convertAmqpInstanceSupportEipRequest(d.Get("support_eip").(bool)),
})
request["Parameter"] = parameterMapList
request["ClientToken"] = buildClientToken("CreateInstance")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-14"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"NotApplicable"}) {
conn.Endpoint = String(connectivity.BssOpenAPIEndpointInternational)
request["ProductType"] = "ons_onsproxy_public_intl"
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_amqp_instance", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
responseData := response["Data"].(map[string]interface{})
d.SetId(fmt.Sprint(responseData["InstanceId"]))
amqpOpenService := AmqpOpenService{client}
stateConf := BuildStateConf([]string{}, []string{"SERVING"}, d.Timeout(schema.TimeoutCreate), 10*time.Second, amqpOpenService.AmqpInstanceStateRefreshFunc(d.Id(), []string{"EXPIRED"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudAmqpInstanceUpdate(d, meta)
}
func resourceAlicloudAmqpInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
amqpOpenService := AmqpOpenService{client}
object, err := amqpOpenService.DescribeAmqpInstance(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_amqp_instance amqpOpenService.DescribeAmqpInstance Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_name", object["InstanceName"])
d.Set("instance_type", convertAmqpInstanceInstanceTypeResponse(object["InstanceType"]))
d.Set("status", object["Status"])
d.Set("support_eip", object["SupportEIP"])
bssOpenApiService := BssOpenApiService{client}
queryAvailableInstancesObject, err := bssOpenApiService.QueryAvailableInstances(d.Id(), "ons", "ons_onsproxy_pre", "ons_onsproxy_public_intl")
if err != nil {
return WrapError(err)
}
d.Set("payment_type", queryAvailableInstancesObject["SubscriptionType"])
if v, ok := queryAvailableInstancesObject["RenewalDuration"]; ok && fmt.Sprint(v) != "0" {
d.Set("renewal_duration", formatInt(v))
}
d.Set("renewal_duration_unit", convertAmqpInstanceRenewalDurationUnitResponse(object["RenewalDurationUnit"]))
d.Set("renewal_status", queryAvailableInstancesObject["RenewStatus"])
return nil
}
func resourceAlicloudAmqpInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewBssopenapiClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"InstanceId": d.Id(),
}
if d.HasChange("instance_name") {
update = true
}
if v, ok := d.GetOk("instance_name"); ok {
request["InstanceName"] = v
}
if update {
action := "UpdateInstanceName"
conn, err := client.NewOnsproxyClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetPartial("instance_name")
}
update = false
setRenewalReq := map[string]interface{}{
"InstanceIDs": d.Id(),
}
if !d.IsNewResource() && d.HasChange("renewal_status") {
update = true
}
if v, ok := d.GetOk("renewal_status"); ok {
setRenewalReq["RenewalStatus"] = v
}
if !d.IsNewResource() && d.HasChange("renewal_duration") {
update = true
}
if v, ok := d.GetOk("renewal_duration"); ok {
setRenewalReq["RenewalPeriod"] = v
}
if !d.IsNewResource() && d.HasChange("payment_type") {
update = true
setRenewalReq["SubscriptionType"] = d.Get("payment_type")
}
setRenewalReq["ProductCode"] = "ons"
setRenewalReq["ProductType"] = "ons_onsproxy_pre"
if d.HasChange("renewal_duration_unit") {
update = true
if v, ok := d.GetOk("renewal_duration_unit"); ok {
setRenewalReq["RenewalPeriodUnit"] = convertAmqpInstanceRenewalDurationUnitRequest(v.(string))
} else if v, ok := d.GetOk("renewal_status"); ok && v.(string) == "AutoRenewal" {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is %v ", "renewal_duration_unit", "renewal_status", d.Get("renewal_status")))
}
setRenewalReq["RenewalStatus"] = d.Get("renewal_status")
}
if update {
action := "SetRenewal"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-14"), StringPointer("AK"), nil, setRenewalReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"NotApplicable"}) {
conn.Endpoint = String(connectivity.BssOpenAPIEndpointInternational)
setRenewalReq["ProductType"] = "ons_onsproxy_public_intl"
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, setRenewalReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetPartial("renewal_status")
d.SetPartial("payment_type")
d.SetPartial("renewal_duration")
d.SetPartial("renewal_duration_unit")
}
update = false
modifyInstanceReq := map[string]interface{}{
"InstanceId": d.Id(),
}
parameterMapList := make([]map[string]interface{}, 0)
if !d.IsNewResource() && d.HasChange("max_tps") {
update = true
}
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "MaxTps",
"Value": d.Get("max_tps"),
})
modifyInstanceReq["SubscriptionType"] = d.Get("payment_type")
modifyInstanceReq["ProductCode"] = "ons"
if !d.IsNewResource() && d.HasChange("queue_capacity") {
update = true
}
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "QueueCapacity",
"Value": d.Get("queue_capacity"),
})
if !d.IsNewResource() && d.HasChange("support_eip") {
update = true
}
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "SupportEip",
"Value": convertAmqpInstanceSupportEipRequest(d.Get("support_eip").(bool)),
})
if !d.IsNewResource() && d.HasChange("max_eip_tps") {
update = true
}
if v, ok := d.GetOk("max_eip_tps"); ok {
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "MaxEipTps",
"Value": v,
})
} else if v, ok := d.GetOkExists("support_eip"); ok && v.(bool) {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is %v ", "max_eip_tps", "support_eip", d.Get("support_eip")))
}
modifyInstanceReq["ProductType"] = "ons_onsproxy_pre"
if !d.IsNewResource() && d.HasChange("storage_size") {
update = true
}
if v, ok := d.GetOk("storage_size"); ok {
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "StorageSize",
"Value": v,
})
}
modifyInstanceReq["Parameter"] = parameterMapList
if update {
if v, ok := d.GetOk("modify_type"); ok {
modifyInstanceReq["ModifyType"] = v
}
action := "ModifyInstance"
request["ClientToken"] = buildClientToken("ModifyInstance")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-14"), StringPointer("AK"), nil, modifyInstanceReq, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"NotApplicable"}) {
conn.Endpoint = String(connectivity.BssOpenAPIEndpointInternational)
modifyInstanceReq["ProductType"] = "ons_onsproxy_public_intl"
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyInstanceReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetPartial("max_tps")
d.SetPartial("payment_type")
d.SetPartial("queue_capacity")
d.SetPartial("support_eip")
d.SetPartial("max_eip_tps")
d.SetPartial("storage_size")
}
d.Partial(false)
return resourceAlicloudAmqpInstanceRead(d, meta)
}
func resourceAlicloudAmqpInstanceDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudAmqpInstance. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
func convertAmqpInstanceSupportEipRequest(source interface{}) interface{} {
switch source {
case false:
return "eip_false"
case true:
return "eip_true"
}
return ""
}
func convertAmqpInstanceInstanceTypeResponse(source interface{}) interface{} {
switch source {
case "PROFESSIONAL":
return "professional"
case "VIP":
return "vip"
}
return source
}
func convertAmqpInstanceRenewalDurationUnitResponse(source interface{}) interface{} {
switch source {
case "M":
return "Month"
case "Y":
return "Year"
}
return source
}
func convertAmqpInstanceRenewalDurationUnitRequest(source interface{}) interface{} {
switch source {
case "Month":
return "M"
case "Year":
return "Y"
}
return source
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudAmqpQueue() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAmqpQueueCreate,
Read: resourceAlicloudAmqpQueueRead,
Update: resourceAlicloudAmqpQueueUpdate,
Delete: resourceAlicloudAmqpQueueDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"auto_delete_state": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"auto_expire_state": {
Type: schema.TypeString,
Optional: true,
},
"dead_letter_exchange": {
Type: schema.TypeString,
Optional: true,
},
"dead_letter_routing_key": {
Type: schema.TypeString,
Optional: true,
},
"exclusive_state": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"max_length": {
Type: schema.TypeString,
Optional: true,
},
"maximum_priority": {
Type: schema.TypeInt,
Optional: true,
},
"message_ttl": {
Type: schema.TypeString,
Optional: true,
},
"queue_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"virtual_host_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudAmqpQueueCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateQueue"
request := make(map[string]interface{})
conn, err := client.NewOnsproxyClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("auto_delete_state"); ok {
request["AutoDeleteState"] = v
}
if v, ok := d.GetOk("auto_expire_state"); ok {
request["AutoExpireState"] = v
}
if v, ok := d.GetOk("dead_letter_exchange"); ok {
request["DeadLetterExchange"] = v
}
if v, ok := d.GetOk("dead_letter_routing_key"); ok {
request["DeadLetterRoutingKey"] = v
}
if v, ok := d.GetOkExists("exclusive_state"); ok {
request["ExclusiveState"] = v
}
request["InstanceId"] = d.Get("instance_id")
if v, ok := d.GetOk("max_length"); ok {
request["MaxLength"] = v
}
if v, ok := d.GetOk("maximum_priority"); ok {
request["MaximumPriority"] = v
}
if v, ok := d.GetOk("message_ttl"); ok {
request["MessageTTL"] = v
}
request["QueueName"] = d.Get("queue_name")
request["VirtualHost"] = d.Get("virtual_host_name")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_amqp_queue", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["InstanceId"], ":", request["VirtualHost"], ":", request["QueueName"]))
return resourceAlicloudAmqpQueueRead(d, meta)
}
func resourceAlicloudAmqpQueueRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
amqpOpenService := AmqpOpenService{client}
object, err := amqpOpenService.DescribeAmqpQueue(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_amqp_queue amqpOpenService.DescribeAmqpQueue Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
d.Set("instance_id", parts[0])
d.Set("queue_name", parts[2])
d.Set("virtual_host_name", parts[1])
d.Set("auto_delete_state", object["AutoDeleteState"])
d.Set("exclusive_state", object["ExclusiveState"])
return nil
}
func resourceAlicloudAmqpQueueUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return resourceAlicloudAmqpQueueRead(d, meta)
}
func resourceAlicloudAmqpQueueDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
action := "DeleteQueue"
var response map[string]interface{}
conn, err := client.NewOnsproxyClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"InstanceId": parts[0],
"QueueName": parts[2],
"VirtualHost": parts[1],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudAmqpVirtualHost() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAmqpVirtualHostCreate,
Read: resourceAlicloudAmqpVirtualHostRead,
Delete: resourceAlicloudAmqpVirtualHostDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"virtual_host_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudAmqpVirtualHostCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateVirtualHost"
request := make(map[string]interface{})
conn, err := client.NewOnsproxyClient()
if err != nil {
return WrapError(err)
}
request["InstanceId"] = d.Get("instance_id")
request["VirtualHost"] = d.Get("virtual_host_name")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_amqp_virtual_host", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["InstanceId"], ":", request["VirtualHost"]))
return resourceAlicloudAmqpVirtualHostRead(d, meta)
}
func resourceAlicloudAmqpVirtualHostRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
amqpOpenService := AmqpOpenService{client}
_, err := amqpOpenService.DescribeAmqpVirtualHost(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_amqp_virtual_host amqpOpenService.DescribeAmqpVirtualHost Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("instance_id", parts[0])
d.Set("virtual_host_name", parts[1])
return nil
}
func resourceAlicloudAmqpVirtualHostDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteVirtualHost"
var response map[string]interface{}
conn, err := client.NewOnsproxyClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"InstanceId": parts[0],
"VirtualHost": parts[1],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cloudapi"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAliyunApigatewayApi() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunApigatewayApiCreate,
Read: resourceAliyunApigatewayApiRead,
Update: resourceAliyunApigatewayApiUpdate,
Delete: resourceAliyunApigatewayApiDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name": {
Type: schema.TypeString,
Required: true,
},
"description": {
Type: schema.TypeString,
Required: true,
},
"auth_type": {
Type: schema.TypeString,
Required: true,
},
"request_config": {
Type: schema.TypeList,
Required: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"protocol": {
Type: schema.TypeString,
Required: true,
},
"method": {
Type: schema.TypeString,
Required: true,
},
"path": {
Type: schema.TypeString,
Required: true,
},
"mode": {
Type: schema.TypeString,
Required: true,
},
"body_format": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"service_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"MOCK", "HTTP-VPC", "FunctionCompute", "HTTP"}, false),
},
"http_service_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"address": {
Type: schema.TypeString,
Required: true,
},
"path": {
Type: schema.TypeString,
Required: true,
},
"method": {
Type: schema.TypeString,
Required: true,
},
"timeout": {
Type: schema.TypeInt,
Required: true,
},
"aone_name": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"http_vpc_service_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"path": {
Type: schema.TypeString,
Required: true,
},
"method": {
Type: schema.TypeString,
Required: true,
},
"timeout": {
Type: schema.TypeInt,
Required: true,
},
"aone_name": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"fc_service_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"region": {
Type: schema.TypeString,
Required: true,
},
"function_name": {
Type: schema.TypeString,
Required: true,
},
"service_name": {
Type: schema.TypeString,
Required: true,
},
"arn_role": {
Type: schema.TypeString,
Optional: true,
},
"timeout": {
Type: schema.TypeInt,
Required: true,
},
},
},
},
"mock_service_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"result": {
Type: schema.TypeString,
Required: true,
},
"aone_name": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"request_parameters": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"type": {
Type: schema.TypeString,
Required: true,
},
"required": {
Type: schema.TypeString,
Required: true,
},
"in": {
Type: schema.TypeString,
Required: true,
},
"in_service": {
Type: schema.TypeString,
Required: true,
},
"name_service": {
Type: schema.TypeString,
Required: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"default_value": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"constant_parameters": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"in": {
Type: schema.TypeString,
Required: true,
},
"value": {
Type: schema.TypeString,
Required: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"system_parameters": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"name_service": {
Type: schema.TypeString,
Required: true,
},
"in": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"stage_names": {
Type: schema.TypeSet,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"PRE", "RELEASE", "TEST"}, false),
},
Optional: true,
},
"api_id": {
Type: schema.TypeString,
Computed: true,
},
"force_nonce_check": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
},
}
}
func resourceAliyunApigatewayApiCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request, err := buildAliyunApiArgs(d, meta)
request.RegionId = client.RegionId
if err != nil {
return WrapError(err)
}
raw, err := client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.CreateApi(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_apigateway_api", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cloudapi.CreateApiResponse)
d.SetId(fmt.Sprintf("%s%s%s", request.GroupId, COLON_SEPARATED, response.ApiId))
if l, ok := d.GetOk("stage_names"); ok {
err = updateApiStages(d, l.(*schema.Set), meta)
if err != nil {
return WrapError(err)
}
}
return resourceAliyunApigatewayApiRead(d, meta)
}
func resourceAliyunApigatewayApiRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudApiService := CloudApiService{client}
request := cloudapi.CreateDescribeApiRequest()
request.RegionId = client.RegionId
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request.ApiId = parts[1]
request.GroupId = parts[0]
object, err := cloudApiService.DescribeApiGatewayApi(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
stageNames, err := getStageNameList(d, cloudApiService)
if err != nil {
if !NotFoundError(err) {
return WrapError(err)
}
}
if err := d.Set("stage_names", stageNames); err != nil {
return WrapError(err)
}
d.Set("api_id", object.ApiId)
d.Set("group_id", object.GroupId)
d.Set("name", object.ApiName)
d.Set("description", object.Description)
d.Set("auth_type", object.AuthType)
d.Set("force_nonce_check", object.ForceNonceCheck)
requestConfig := map[string]interface{}{}
requestConfig["protocol"] = object.RequestConfig.RequestProtocol
requestConfig["method"] = object.RequestConfig.RequestHttpMethod
requestConfig["path"] = object.RequestConfig.RequestPath
requestConfig["mode"] = object.RequestConfig.RequestMode
if object.RequestConfig.BodyFormat != "" {
requestConfig["body_format"] = object.RequestConfig.BodyFormat
}
if err := d.Set("request_config", []map[string]interface{}{requestConfig}); err != nil {
return WrapError(err)
}
if object.ServiceConfig.Mock == "TRUE" {
d.Set("service_type", "MOCK")
MockServiceConfig := map[string]interface{}{}
MockServiceConfig["result"] = object.ServiceConfig.MockResult
MockServiceConfig["aone_name"] = object.ServiceConfig.AoneAppName
if err := d.Set("mock_service_config", []map[string]interface{}{MockServiceConfig}); err != nil {
return WrapError(err)
}
} else if object.ServiceConfig.ServiceVpcEnable == "TRUE" {
d.Set("service_type", "HTTP-VPC")
vpcServiceConfig := map[string]interface{}{}
vpcServiceConfig["name"] = object.ServiceConfig.VpcConfig.Name
vpcServiceConfig["path"] = object.ServiceConfig.ServicePath
vpcServiceConfig["method"] = object.ServiceConfig.ServiceHttpMethod
vpcServiceConfig["timeout"] = object.ServiceConfig.ServiceTimeout
vpcServiceConfig["aone_name"] = object.ServiceConfig.AoneAppName
if err := d.Set("http_vpc_service_config", []map[string]interface{}{vpcServiceConfig}); err != nil {
return WrapError(err)
}
} else if object.ServiceConfig.ServiceProtocol == "FunctionCompute" {
d.Set("service_type", "FunctionCompute")
fcServiceConfig := map[string]interface{}{}
fcServiceConfig["region"] = object.ServiceConfig.FunctionComputeConfig.RegionId
fcServiceConfig["function_name"] = object.ServiceConfig.FunctionComputeConfig.FunctionName
fcServiceConfig["service_name"] = object.ServiceConfig.FunctionComputeConfig.ServiceName
fcServiceConfig["arn_role"] = object.ServiceConfig.FunctionComputeConfig.RoleArn
fcServiceConfig["timeout"] = object.ServiceConfig.ServiceTimeout
if err := d.Set("fc_service_config", []map[string]interface{}{fcServiceConfig}); err != nil {
return WrapError(err)
}
} else {
d.Set("service_type", "HTTP")
httpServiceConfig := map[string]interface{}{}
httpServiceConfig["address"] = object.ServiceConfig.ServiceAddress
httpServiceConfig["path"] = object.ServiceConfig.ServicePath
httpServiceConfig["method"] = object.ServiceConfig.ServiceHttpMethod
httpServiceConfig["timeout"] = object.ServiceConfig.ServiceTimeout
httpServiceConfig["aone_name"] = object.ServiceConfig.AoneAppName
if err := d.Set("http_service_config", []map[string]interface{}{httpServiceConfig}); err != nil {
return WrapError(err)
}
}
requestParams := []map[string]interface{}{}
for _, mapParam := range object.ServiceParametersMap.ServiceParameterMap {
param := map[string]interface{}{}
requestName := mapParam.RequestParameterName
serviceName := mapParam.ServiceParameterName
for _, serviceParam := range object.ServiceParameters.ServiceParameter {
if serviceParam.ServiceParameterName == serviceName {
param["name_service"] = serviceName
param["in_service"] = strings.ToUpper(serviceParam.Location)
break
}
}
for _, requestParam := range object.RequestParameters.RequestParameter {
if requestParam.ApiParameterName == requestName {
param["name"] = requestName
param["type"] = requestParam.ParameterType
param["required"] = requestParam.Required
param["in"] = requestParam.Location
if requestParam.Description != "" {
param["description"] = requestParam.Description
}
if requestParam.DefaultValue != "" {
param["default_value"] = requestParam.DefaultValue
}
break
}
}
requestParams = append(requestParams, param)
}
d.Set("request_parameters", requestParams)
constantParams := []map[string]interface{}{}
for _, constantParam := range object.ConstantParameters.ConstantParameter {
param := map[string]interface{}{}
param["name"] = constantParam.ServiceParameterName
param["in"] = constantParam.Location
param["value"] = constantParam.ConstantValue
if constantParam.Description != "" {
param["description"] = constantParam.Description
}
constantParams = append(constantParams, param)
}
d.Set("constant_parameters", constantParams)
SystemParams := []map[string]interface{}{}
for _, systemParam := range object.SystemParameters.SystemParameter {
param := map[string]interface{}{}
param["name"] = systemParam.ParameterName
param["in"] = systemParam.Location
param["name_service"] = systemParam.ServiceParameterName
}
d.Set("system_parameters", SystemParams)
return nil
}
func resourceAliyunApigatewayApiUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cloudapi.CreateModifyApiRequest()
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request.ApiId = parts[1]
request.GroupId = parts[0]
update := false
d.Partial(true)
if d.HasChange("name") || d.HasChange("description") || d.HasChange("auth_type") {
update = true
}
request.ApiName = d.Get("name").(string)
request.Description = d.Get("description").(string)
request.AuthType = d.Get("auth_type").(string)
if d.HasChange("force_nonce_check") {
update = true
}
if v, exist := d.GetOk("force_nonce_check"); exist {
request.ForceNonceCheck = requests.Boolean(strconv.FormatBool(v.(bool)))
}
var paramErr error
var paramConfig string
if d.HasChange("request_config") {
update = true
}
paramConfig, paramErr = requestConfigToJsonStr(d.Get("request_config").([]interface{}))
if paramErr != nil {
return paramErr
}
request.RequestConfig = paramConfig
if d.HasChange("service_type") || d.HasChange("http_service_config") || d.HasChange("http_vpc_service_config") || d.HasChange("mock_service_config") {
update = true
}
serviceConfig, err := serviceConfigToJsonStr(d)
if err != nil {
return WrapError(err)
}
request.ServiceConfig = serviceConfig
if d.HasChange("request_parameters") || d.HasChange("constant_parameters") || d.HasChange("system_parameters") {
update = true
}
rps, sps, spm, err := setParameters(d)
if err != nil {
return WrapError(err)
}
request.RequestParameters = string(rps)
request.ServiceParameters = string(sps)
request.ServiceParametersMap = string(spm)
if update {
request.ResultType = ResultType
request.ResultSample = ResultSample
request.Visibility = Visibility
request.AllowSignatureMethod = AllowSignatureMethod
request.WebSocketApiType = WebSocketApiType
raw, err := client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.ModifyApi(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("name")
d.SetPartial("description")
d.SetPartial("auth_type")
d.SetPartial("service_type")
d.SetPartial("http_service_config")
d.SetPartial("http_vpc_service_config")
d.SetPartial("fc_service_config")
d.SetPartial("mock_service_config")
d.SetPartial("request_parameters")
d.SetPartial("constant_parameters")
d.SetPartial("system_parameters")
}
if update || d.HasChange("stage_names") {
if l, ok := d.GetOk("stage_names"); ok {
err = updateApiStages(d, l.(*schema.Set), meta)
if err != nil {
return WrapError(err)
}
}
d.SetPartial("stage_names")
}
d.Partial(false)
return resourceAliyunApigatewayApiRead(d, meta)
}
func resourceAliyunApigatewayApiDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudApiService := CloudApiService{client}
request := cloudapi.CreateDeleteApiRequest()
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request.ApiId = parts[1]
request.GroupId = parts[0]
for _, stageName := range ApiGatewayStageNames {
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
err := cloudApiService.AbolishApi(d.Id(), stageName)
if err != nil {
if IsExpectedErrors(err, []string{"ConcurrencyLockTimeout"}) {
time.Sleep(3 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapError(err)
}
_, err = cloudApiService.DescribeDeployedApi(d.Id(), stageName)
if err != nil {
if !NotFoundError(err) {
return WrapError(err)
}
}
}
raw, err := client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.DeleteApi(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"NotFoundApi"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(cloudApiService.WaitForApiGatewayApi(d.Id(), Deleted, DefaultTimeout))
}
func buildAliyunApiArgs(d *schema.ResourceData, meta interface{}) (*cloudapi.CreateApiRequest, error) {
request := cloudapi.CreateCreateApiRequest()
request.GroupId = d.Get("group_id").(string)
request.Description = d.Get("description").(string)
request.ApiName = d.Get("name").(string)
request.AuthType = d.Get("auth_type").(string)
if v, exist := d.GetOk("force_nonce_check"); exist {
request.ForceNonceCheck = requests.Boolean(strconv.FormatBool(v.(bool)))
}
requestConfig, err := requestConfigToJsonStr(d.Get("request_config").([]interface{}))
if err != nil {
return request, WrapError(err)
}
request.RequestConfig = requestConfig
serviceConfig, err := serviceConfigToJsonStr(d)
if err != nil {
return request, WrapError(err)
}
request.ServiceConfig = serviceConfig
rps, sps, spm, err := setParameters(d)
if err != nil {
return request, WrapError(err)
}
request.RequestParameters = string(rps)
request.ServiceParameters = string(sps)
request.ServiceParametersMap = string(spm)
request.ResultType = ResultType
request.ResultSample = ResultSample
request.Visibility = Visibility
request.AllowSignatureMethod = AllowSignatureMethod
request.WebSocketApiType = WebSocketApiType
return request, WrapError(err)
}
func requestConfigToJsonStr(l []interface{}) (string, error) {
config := l[0].(map[string]interface{})
var requestConfig ApiGatewayRequestConfig
requestConfig.Protocol = config["protocol"].(string)
requestConfig.Path = config["path"].(string)
requestConfig.Method = config["method"].(string)
requestConfig.Mode = config["mode"].(string)
if v, ok := config["body_format"]; ok {
requestConfig.BodyFormat = v.(string)
}
configStr, err := json.Marshal(requestConfig)
return string(configStr), WrapError(err)
}
func getHttpServiceConfig(d *schema.ResourceData) ([]byte, error) {
var serviceConfig ApiGatewayServiceConfig
var l []interface{}
v, ok := d.GetOk("http_service_config")
if !ok {
return []byte{}, fmt.Errorf("Creating apigatway api error: http_service_config is null")
}
l = v.([]interface{})
config := l[0].(map[string]interface{})
serviceConfig.Protocol = "HTTP"
serviceConfig.Address = config["address"].(string)
serviceConfig.Path = config["path"].(string)
serviceConfig.Method = config["method"].(string)
serviceConfig.Timeout = config["timeout"].(int)
serviceConfig.MockEnable = "FALSE"
serviceConfig.VpcEnable = "FALSE"
serviceConfig.ContentTypeCategory = "CLIENT"
if v, ok := config["aone_name"]; ok {
serviceConfig.AoneName = v.(string)
}
configStr, err := json.Marshal(serviceConfig)
return configStr, WrapError(err)
}
func getHttpVpcServiceConfig(d *schema.ResourceData) ([]byte, error) {
var serviceConfig ApiGatewayServiceConfig
var l []interface{}
v, ok := d.GetOk("http_vpc_service_config")
if !ok {
return []byte{}, WrapError(Error("Creating apigatway api error: http_vpc_service_config is null"))
}
l = v.([]interface{})
config := l[0].(map[string]interface{})
serviceConfig.Protocol = "HTTP"
serviceConfig.VpcConfig.Name = config["name"].(string)
serviceConfig.Path = config["path"].(string)
serviceConfig.Method = config["method"].(string)
serviceConfig.Timeout = config["timeout"].(int)
serviceConfig.VpcEnable = "TRUE"
serviceConfig.MockEnable = "FALSE"
serviceConfig.ContentTypeCategory = "CLIENT"
if v, ok := config["aone_name"]; ok {
serviceConfig.AoneName = v.(string)
}
configStr, err := json.Marshal(serviceConfig)
return configStr, WrapError(err)
}
func getFcServiceConfig(d *schema.ResourceData) ([]byte, error) {
var serviceConfig ApiGatewayServiceConfig
var l []interface{}
v, ok := d.GetOk("fc_service_config")
if !ok {
return []byte{}, WrapError(Error("Creating apigatway api error: fc_service_config is null"))
}
l = v.([]interface{})
config := l[0].(map[string]interface{})
serviceConfig.Protocol = "FunctionCompute"
serviceConfig.FcConfig.Region = config["region"].(string)
serviceConfig.FcConfig.FunctionName = config["function_name"].(string)
serviceConfig.FcConfig.ServiceName = config["service_name"].(string)
serviceConfig.FcConfig.Arn = config["arn_role"].(string)
serviceConfig.Timeout = config["timeout"].(int)
serviceConfig.VpcEnable = "FALSE"
serviceConfig.MockEnable = "FALSE"
serviceConfig.ContentTypeCategory = "CLIENT"
if v, ok := config["aone_name"]; ok {
serviceConfig.AoneName = v.(string)
}
configStr, err := json.Marshal(serviceConfig)
return configStr, WrapError(err)
}
func getMockServiceConfig(d *schema.ResourceData) ([]byte, error) {
var serviceConfig ApiGatewayServiceConfig
var l []interface{}
v, ok := d.GetOk("mock_service_config")
if !ok {
return []byte{}, WrapError(Error("Creating apigatway api error: mock_service_config is null"))
}
l = v.([]interface{})
config := l[0].(map[string]interface{})
serviceConfig.Protocol = "HTTP"
serviceConfig.Method = "GET"
serviceConfig.MockResult = config["result"].(string)
serviceConfig.MockEnable = "TRUE"
serviceConfig.VpcEnable = "FALSE"
serviceConfig.Timeout = ApigatewayDefaultTimeout
serviceConfig.Address = ApigatewayDefaultAddress
if v, ok := config["aone_name"]; ok {
serviceConfig.AoneName = v.(string)
}
configStr, err := json.Marshal(serviceConfig)
return configStr, WrapError(err)
}
func serviceConfigToJsonStr(d *schema.ResourceData) (string, error) {
var err error
var configStr []byte
serviceType := d.Get("service_type").(string)
switch serviceType {
case "HTTP":
configStr, err = getHttpServiceConfig(d)
break
case "HTTP-VPC":
configStr, err = getHttpVpcServiceConfig(d)
break
case "FunctionCompute":
configStr, err = getFcServiceConfig(d)
break
case "MOCK":
configStr, err = getMockServiceConfig(d)
break
}
if err != nil {
return "", WrapError(err)
}
return string(configStr), nil
}
func setParameters(d *schema.ResourceData) (rps []byte, sps []byte, spm []byte, err error) {
requestParameters := make([]ApiGatewayRequestParam, 0)
serviceParameters := make([]ApiGatewayServiceParam, 0)
serviceParamMaps := make([]ApiGatewayParameterMap, 0)
requestParameters, serviceParameters, serviceParamMaps = setRequestParameters(d, requestParameters, serviceParameters, serviceParamMaps)
requestParameters, serviceParameters, serviceParamMaps = setConstantParameters(d, requestParameters, serviceParameters, serviceParamMaps)
requestParameters, serviceParameters, serviceParamMaps = setSystemParameters(d, requestParameters, serviceParameters, serviceParamMaps)
rps, err = json.Marshal(requestParameters)
if err != nil {
err = WrapError(err)
return
}
sps, err = json.Marshal(serviceParameters)
if err != nil {
err = WrapError(err)
return
}
spm, err = json.Marshal(serviceParamMaps)
if err != nil {
err = WrapError(err)
return
}
return rps, sps, spm, WrapError(err)
}
func setSystemParameters(d *schema.ResourceData, requestParameters []ApiGatewayRequestParam, serviceParameters []ApiGatewayServiceParam, serviceParamMaps []ApiGatewayParameterMap) ([]ApiGatewayRequestParam, []ApiGatewayServiceParam, []ApiGatewayParameterMap) {
if l, ok := d.GetOk("system_parameters"); ok {
for _, element := range l.(*schema.Set).List() {
var requestParam ApiGatewayRequestParam
var serviceParam ApiGatewayServiceParam
var serviceParamMap ApiGatewayParameterMap
request := element.(map[string]interface{})
nameRequest := request["name"].(string)
nameService := request["name_service"].(string)
in := request["in"].(string)
requestParam.Name = nameRequest
requestParam.ApiParameterName = nameRequest
requestParam.In = in
requestParam.Required = "REQUIRED"
requestParam.Type = "String"
requestParameters = append(requestParameters, requestParam)
serviceParam.Type = "String"
serviceParam.In = in
serviceParam.Name = nameService
serviceParam.Catalog = CatalogSystem
serviceParameters = append(serviceParameters, serviceParam)
serviceParamMap.RequestParamName = nameRequest
serviceParamMap.ServiceParamName = nameService
serviceParamMaps = append(serviceParamMaps, serviceParamMap)
}
}
return requestParameters, serviceParameters, serviceParamMaps
}
func setConstantParameters(d *schema.ResourceData, requestParameters []ApiGatewayRequestParam, serviceParameters []ApiGatewayServiceParam, serviceParamMaps []ApiGatewayParameterMap) ([]ApiGatewayRequestParam, []ApiGatewayServiceParam, []ApiGatewayParameterMap) {
if l, ok := d.GetOk("constant_parameters"); ok {
for _, element := range l.(*schema.Set).List() {
var requestParam ApiGatewayRequestParam
var serviceParam ApiGatewayServiceParam
var serviceParamMap ApiGatewayParameterMap
request := element.(map[string]interface{})
name := request["name"].(string)
in := request["in"].(string)
value := request["value"].(string)
requestParam.Name = name
requestParam.Required = "REQUIRED"
requestParam.ApiParameterName = name
requestParam.In = in
requestParam.Type = "String"
if description, ok := request["description"]; !ok {
requestParam.Description = description.(string)
}
requestParam.DefualtValue = value
requestParameters = append(requestParameters, requestParam)
serviceParam.In = in
serviceParam.Name = name
serviceParam.Catalog = CatalogConstant
serviceParameters = append(serviceParameters, serviceParam)
serviceParamMap.RequestParamName = name
serviceParamMap.ServiceParamName = name
serviceParamMaps = append(serviceParamMaps, serviceParamMap)
}
}
return requestParameters, serviceParameters, serviceParamMaps
}
func setRequestParameters(d *schema.ResourceData, requestParameters []ApiGatewayRequestParam, serviceParameters []ApiGatewayServiceParam, serviceParamMaps []ApiGatewayParameterMap) ([]ApiGatewayRequestParam, []ApiGatewayServiceParam, []ApiGatewayParameterMap) {
if l, ok := d.GetOk("request_parameters"); ok {
for _, element := range l.(*schema.Set).List() {
var requestParam ApiGatewayRequestParam
var serviceParam ApiGatewayServiceParam
var serviceParamMap ApiGatewayParameterMap
request := element.(map[string]interface{})
nameRequest := request["name"].(string)
paramType := request["type"].(string)
required := request["required"].(string)
in := request["in"].(string)
inService := request["in_service"].(string)
nameService := request["name_service"].(string)
if description, ok := request["description"]; ok {
requestParam.Description = description.(string)
}
if defaultValue, ok := request["default_value"]; ok {
requestParam.DefualtValue = defaultValue.(string)
}
requestParam.Name = nameRequest
requestParam.Required = required
requestParam.ApiParameterName = nameRequest
requestParam.In = in
requestParam.Type = paramType
requestParameters = append(requestParameters, requestParam)
serviceParam.Type = paramType
serviceParam.In = inService
serviceParam.Name = nameService
serviceParam.Catalog = CatalogRequest
serviceParameters = append(serviceParameters, serviceParam)
serviceParamMap.RequestParamName = nameRequest
serviceParamMap.ServiceParamName = nameService
serviceParamMaps = append(serviceParamMaps, serviceParamMap)
}
}
return requestParameters, serviceParameters, serviceParamMaps
}
func getStageNameList(d *schema.ResourceData, cloudApiService CloudApiService) ([]string, error) {
var stageNames []string
for _, stageName := range ApiGatewayStageNames {
_, err := cloudApiService.DescribeDeployedApi(d.Id(), stageName)
if err != nil {
if NotFoundError(err) {
continue
}
return nil, WrapError(err)
}
stageNames = append(stageNames, stageName)
}
return stageNames, nil
}
func updateApiStages(d *schema.ResourceData, stageNames *schema.Set, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudApiService := CloudApiService{client}
for _, stageName := range ApiGatewayStageNames {
if stageNames.Contains(stageName) {
err := cloudApiService.DeployedApi(d.Id(), stageName)
if err != nil {
return WrapError(err)
}
_, err = cloudApiService.DescribeDeployedApi(d.Id(), stageName)
if err != nil {
return WrapError(err)
}
} else {
err := cloudApiService.AbolishApi(d.Id(), stageName)
if err != nil {
return WrapError(err)
}
_, err = cloudApiService.DescribeDeployedApi(d.Id(), stageName)
if err != nil {
if !NotFoundError(err) {
return WrapError(err)
}
}
}
}
return nil
}
package alicloud
import (
"strconv"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cloudapi"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliyunApigatewayApp() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunApigatewayAppCreate,
Read: resourceAliyunApigatewayAppRead,
Update: resourceAliyunApigatewayAppUpdate,
Delete: resourceAliyunApigatewayAppDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"tags": tagsSchema(),
},
}
}
func resourceAliyunApigatewayAppCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cloudapi.CreateCreateAppRequest()
request.RegionId = client.RegionId
request.AppName = d.Get("name").(string)
if v, exist := d.GetOk("description"); exist {
request.Description = v.(string)
}
request.Description = d.Get("description").(string)
if err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.CreateApp(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"RepeatedCommit"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cloudapi.CreateAppResponse)
d.SetId(strconv.FormatInt(response.AppId, 10))
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_apigateway_app", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return resourceAliyunApigatewayAppUpdate(d, meta)
}
func resourceAliyunApigatewayAppRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudApiService := CloudApiService{client}
wait := incrementalWait(3*time.Second, 5*time.Second)
if err := resource.Retry(5*time.Minute, func() *resource.RetryError {
tags, err := cloudApiService.DescribeTags(d.Id(), nil, TagResourceApp)
if err != nil {
if IsExpectedErrors(err, []string{"NotFoundResourceId"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
d.Set("tags", cloudApiService.tagsToMap(tags))
return nil
}); err != nil {
return WrapError(err)
}
if err := resource.Retry(3*time.Second, func() *resource.RetryError {
object, err := cloudApiService.DescribeApiGatewayApp(d.Id())
if err != nil {
if NotFoundError(err) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
d.Set("name", object.AppName)
d.Set("description", object.Description)
return nil
}); err != nil {
return WrapError(err)
}
return nil
}
func resourceAliyunApigatewayAppUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudApiService := CloudApiService{client}
if err := cloudApiService.setInstanceTags(d, TagResourceApp); err != nil {
return WrapError(err)
}
if d.IsNewResource() {
d.Partial(false)
return resourceAliyunApigatewayAppRead(d, meta)
}
if d.HasChange("name") || d.HasChange("description") {
request := cloudapi.CreateModifyAppRequest()
request.RegionId = client.RegionId
request.AppId = requests.Integer(d.Id())
request.AppName = d.Get("name").(string)
if v, exist := d.GetOk("description"); exist {
request.Description = v.(string)
}
raw, err := client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.ModifyApp(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
time.Sleep(3 * time.Second)
return resourceAliyunApigatewayAppRead(d, meta)
}
func resourceAliyunApigatewayAppDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudApiService := CloudApiService{client}
request := cloudapi.CreateDeleteAppRequest()
request.RegionId = client.RegionId
request.AppId = requests.Integer(d.Id())
raw, err := client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.DeleteApp(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"NotFoundApp"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(cloudApiService.WaitForApiGatewayApp(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"fmt"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cloudapi"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAliyunApigatewayAppAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunApigatewayAppAttachmentCreate,
Read: resourceAliyunApigatewayAppAttachmentRead,
Delete: resourceAliyunApigatewayAppAttachmentDelete,
Schema: map[string]*schema.Schema{
"app_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"api_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"stage_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PRE", "RELEASE", "TEST"}, false),
},
},
}
}
func resourceAliyunApigatewayAppAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudApiService := CloudApiService{client}
apiId := d.Get("api_id").(string)
groupId := d.Get("group_id").(string)
stageName := d.Get("stage_name").(string)
appId := d.Get("app_id").(string)
request := cloudapi.CreateSetAppsAuthoritiesRequest()
request.RegionId = client.RegionId
request.GroupId = groupId
request.ApiId = apiId
request.AppIds = appId
request.StageName = stageName
raw, err := client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.SetAppsAuthorities(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_apigateway_app_attachment", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
id := fmt.Sprintf("%s%s%s%s%s%s%s", groupId, COLON_SEPARATED, apiId, COLON_SEPARATED, appId, COLON_SEPARATED, stageName)
err = cloudApiService.WaitForApiGatewayAppAttachment(id, Normal, DefaultTimeout)
if err != nil {
return WrapError(err)
}
d.SetId(id)
return resourceAliyunApigatewayAppAttachmentRead(d, meta)
}
func resourceAliyunApigatewayAppAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudApiService := CloudApiService{client}
_, err := cloudApiService.DescribeApiGatewayAppAttachment(d.Id())
if err != nil {
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 4)
if err != nil {
return WrapError(err)
}
d.Set("group_id", parts[0])
d.Set("api_id", parts[1])
d.Set("app_id", parts[2])
d.Set("stage_name", parts[3])
return nil
}
func resourceAliyunApigatewayAppAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudApiService := CloudApiService{client}
request := cloudapi.CreateRemoveAppsAuthoritiesRequest()
request.RegionId = client.RegionId
parts, err := ParseResourceId(d.Id(), 4)
if err != nil {
return WrapError(err)
}
request.GroupId = parts[0]
request.ApiId = parts[1]
request.AppIds = parts[2]
request.StageName = parts[3]
raw, err := client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.RemoveAppsAuthorities(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"NotFoundAuthorization"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(cloudApiService.WaitForApiGatewayAppAttachment(d.Id(), Deleted, DefaultLongTimeout))
}
package alicloud
import (
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cloudapi"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliyunApigatewayGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunApigatewayGroupCreate,
Read: resourceAliyunApigatewayGroupRead,
Update: resourceAliyunApigatewayGroupUpdate,
Delete: resourceAliyunApigatewayGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"description": {
Type: schema.TypeString,
Required: true,
},
"sub_domain": {
Type: schema.TypeString,
Computed: true,
},
"vpc_domain": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAliyunApigatewayGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cloudapi.CreateCreateApiGroupRequest()
request.RegionId = client.RegionId
request.GroupName = d.Get("name").(string)
request.Description = d.Get("description").(string)
if err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.CreateApiGroup(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"RepeatedCommit"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cloudapi.CreateApiGroupResponse)
d.SetId(response.GroupId)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_api_gateway_group", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return resourceAliyunApigatewayGroupRead(d, meta)
}
func resourceAliyunApigatewayGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudApiService := CloudApiService{client}
apiGroup, err := cloudApiService.DescribeApiGatewayGroup(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", apiGroup.GroupName)
d.Set("description", apiGroup.Description)
d.Set("sub_domain", apiGroup.SubDomain)
d.Set("vpc_domain", apiGroup.VpcDomain)
return nil
}
func resourceAliyunApigatewayGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
if d.HasChange("name") || d.HasChange("description") {
request := cloudapi.CreateModifyApiGroupRequest()
request.RegionId = client.RegionId
request.Description = d.Get("description").(string)
request.GroupName = d.Get("name").(string)
request.GroupId = d.Id()
raw, err := client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.ModifyApiGroup(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
return resourceAliyunApigatewayGroupRead(d, meta)
}
func resourceAliyunApigatewayGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudApiService := CloudApiService{client}
request := cloudapi.CreateDeleteApiGroupRequest()
request.RegionId = client.RegionId
request.GroupId = d.Id()
raw, err := client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.DeleteApiGroup(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(cloudApiService.WaitForApiGatewayGroup(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"fmt"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cloudapi"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliyunApigatewayVpc() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunApigatewayVpcAccessCreate,
Read: resourceAliyunApigatewayVpcAccessRead,
Delete: resourceAliyunApigatewayVpcAccessDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"vpc_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"port": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAliyunApigatewayVpcAccessCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cloudapi.CreateSetVpcAccessRequest()
request.RegionId = client.RegionId
request.Name = d.Get("name").(string)
request.VpcId = d.Get("vpc_id").(string)
request.InstanceId = d.Get("instance_id").(string)
request.Port = requests.NewInteger(d.Get("port").(int))
raw, err := client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.SetVpcAccess(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_api_gateway_vpc", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetId(fmt.Sprintf("%s%s%s%s%s%s%s", request.Name, COLON_SEPARATED, request.VpcId, COLON_SEPARATED, request.InstanceId, COLON_SEPARATED, request.Port))
return resourceAliyunApigatewayVpcAccessRead(d, meta)
}
func resourceAliyunApigatewayVpcAccessRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudApiService := CloudApiService{client}
vpc, err := cloudApiService.DescribeApiGatewayVpcAccess(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", vpc.Name)
d.Set("vpc_id", vpc.VpcId)
d.Set("instance_id", vpc.InstanceId)
d.Set("port", vpc.Port)
return nil
}
func resourceAliyunApigatewayVpcAccessDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cloudapi.CreateRemoveVpcAccessRequest()
request.RegionId = client.RegionId
request.VpcId = d.Get("vpc_id").(string)
request.InstanceId = d.Get("instance_id").(string)
request.Port = requests.NewInteger(d.Get("port").(int))
raw, err := client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.RemoveVpcAccess(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudArmsAlertContact() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudArmsAlertContactCreate,
Read: resourceAlicloudArmsAlertContactRead,
Update: resourceAlicloudArmsAlertContactUpdate,
Delete: resourceAlicloudArmsAlertContactDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"alert_contact_name": {
Type: schema.TypeString,
Optional: true,
},
"ding_robot_webhook_url": {
Type: schema.TypeString,
Optional: true,
},
"email": {
Type: schema.TypeString,
Optional: true,
},
"phone_num": {
Type: schema.TypeString,
Optional: true,
},
"system_noc": {
Type: schema.TypeBool,
Optional: true,
},
},
}
}
func resourceAlicloudArmsAlertContactCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateAlertContact"
request := make(map[string]interface{})
conn, err := client.NewArmsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("alert_contact_name"); ok {
request["ContactName"] = v
}
if v, ok := d.GetOk("ding_robot_webhook_url"); ok {
request["DingRobotWebhookUrl"] = v
} else if v, ok := d.GetOk("email"); ok && v.(string) == "" {
if v, ok := d.GetOk("phone_num"); ok && v.(string) == "" {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is %v and '%s' is %v ", "ding_robot_webhook_url", "email", d.Get("email"), "phone_num", d.Get("phone_num")))
}
}
if v, ok := d.GetOk("email"); ok {
request["Email"] = v
} else if v, ok := d.GetOk("ding_robot_webhook_url"); ok && v.(string) == "" {
if v, ok := d.GetOk("phone_num"); ok && v.(string) == "" {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is %v and '%s' is %v ", "email", "ding_robot_webhook_url", d.Get("ding_robot_webhook_url"), "phone_num", d.Get("phone_num")))
}
}
if v, ok := d.GetOk("phone_num"); ok {
request["PhoneNum"] = v
} else if v, ok := d.GetOk("ding_robot_webhook_url"); ok && v.(string) == "" {
if v, ok := d.GetOk("email"); ok && v.(string) == "" {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is %v and '%s' is %v ", "phone_num", "ding_robot_webhook_url", d.Get("ding_robot_webhook_url"), "email", d.Get("email")))
}
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOkExists("system_noc"); ok {
request["SystemNoc"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_arms_alert_contact", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["ContactId"]))
return resourceAlicloudArmsAlertContactRead(d, meta)
}
func resourceAlicloudArmsAlertContactRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
armsService := ArmsService{client}
object, err := armsService.DescribeArmsAlertContact(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_arms_alert_contact armsService.DescribeArmsAlertContact Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("alert_contact_name", object["ContactName"])
d.Set("ding_robot_webhook_url", object["DingRobot"])
d.Set("email", object["Email"])
d.Set("phone_num", object["Phone"])
d.Set("system_noc", object["SystemNoc"])
return nil
}
func resourceAlicloudArmsAlertContactUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"ContactId": d.Id(),
}
request["RegionId"] = client.RegionId
if d.HasChange("alert_contact_name") {
update = true
}
if v, ok := d.GetOk("alert_contact_name"); ok {
request["ContactName"] = v
}
if d.HasChange("ding_robot_webhook_url") {
update = true
}
if v, ok := d.GetOk("ding_robot_webhook_url"); ok {
request["DingRobotWebhookUrl"] = v
} else if v, ok := d.GetOk("email"); ok && v.(string) == "" {
if v, ok := d.GetOk("phone_num"); ok && v.(string) == "" {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is %v and '%s' is %v ", "ding_robot_webhook_url", "email", d.Get("email"), "phone_num", d.Get("phone_num")))
}
}
if d.HasChange("email") {
update = true
}
if v, ok := d.GetOk("email"); ok {
request["Email"] = v
} else if v, ok := d.GetOk("ding_robot_webhook_url"); ok && v.(string) == "" {
if v, ok := d.GetOk("phone_num"); ok && v.(string) == "" {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is %v and '%s' is %v ", "email", "ding_robot_webhook_url", d.Get("ding_robot_webhook_url"), "phone_num", d.Get("phone_num")))
}
}
if d.HasChange("phone_num") {
update = true
}
if v, ok := d.GetOk("phone_num"); ok {
request["PhoneNum"] = v
} else if v, ok := d.GetOk("ding_robot_webhook_url"); ok && v.(string) == "" {
if v, ok := d.GetOk("email"); ok && v.(string) == "" {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is %v and '%s' is %v ", "phone_num", "ding_robot_webhook_url", d.Get("ding_robot_webhook_url"), "email", d.Get("email")))
}
}
if d.HasChange("system_noc") || d.IsNewResource() {
update = true
}
if v, ok := d.GetOkExists("system_noc"); ok {
request["SystemNoc"] = v
}
if update {
action := "UpdateAlertContact"
conn, err := client.NewArmsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudArmsAlertContactRead(d, meta)
}
func resourceAlicloudArmsAlertContactDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteAlertContact"
var response map[string]interface{}
conn, err := client.NewArmsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ContactId": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudArmsAlertContactGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudArmsAlertContactGroupCreate,
Read: resourceAlicloudArmsAlertContactGroupRead,
Update: resourceAlicloudArmsAlertContactGroupUpdate,
Delete: resourceAlicloudArmsAlertContactGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"alert_contact_group_name": {
Type: schema.TypeString,
Required: true,
},
"contact_ids": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
}
}
func resourceAlicloudArmsAlertContactGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateAlertContactGroup"
request := make(map[string]interface{})
conn, err := client.NewArmsClient()
if err != nil {
return WrapError(err)
}
request["ContactGroupName"] = d.Get("alert_contact_group_name")
if v, ok := d.GetOk("contact_ids"); ok {
request["ContactIds"] = convertArrayToString(v.(*schema.Set).List(), " ")
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_arms_alert_contact_group", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["ContactGroupId"]))
return resourceAlicloudArmsAlertContactGroupRead(d, meta)
}
func resourceAlicloudArmsAlertContactGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
armsService := ArmsService{client}
object, err := armsService.DescribeArmsAlertContactGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_arms_alert_contact_group armsService.DescribeArmsAlertContactGroup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("alert_contact_group_name", object["ContactGroupName"])
contactIdsItems := make([]string, 0)
if contacts, ok := object["Contacts"]; ok && contacts != nil {
for _, contactsItem := range contacts.([]interface{}) {
if contactId, ok := contactsItem.(map[string]interface{})["ContactId"]; ok && contactId != nil {
contactIdsItems = append(contactIdsItems, fmt.Sprint(contactId))
}
}
}
d.Set("contact_ids", contactIdsItems)
return nil
}
func resourceAlicloudArmsAlertContactGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"ContactGroupId": d.Id(),
}
if d.HasChange("alert_contact_group_name") {
update = true
}
request["ContactGroupName"] = d.Get("alert_contact_group_name")
request["RegionId"] = client.RegionId
if d.HasChange("contact_ids") {
update = true
}
if v, ok := d.GetOk("contact_ids"); ok {
request["ContactIds"] = convertArrayToString(v.(*schema.Set).List(), " ")
}
if update {
action := "UpdateAlertContactGroup"
conn, err := client.NewArmsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudArmsAlertContactGroupRead(d, meta)
}
func resourceAlicloudArmsAlertContactGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteAlertContactGroup"
var response map[string]interface{}
conn, err := client.NewArmsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ContactGroupId": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudArmsDispatchRule() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudArmsDispatchRuleCreate,
Read: resourceAlicloudArmsDispatchRuleRead,
Update: resourceAlicloudArmsDispatchRuleUpdate,
Delete: resourceAlicloudArmsDispatchRuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"is_recover": {
Type: schema.TypeBool,
Optional: true,
},
"group_rules": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"group_id": {
Type: schema.TypeInt,
Computed: true,
},
"group_wait_time": {
Type: schema.TypeInt,
Required: true,
},
"group_interval": {
Type: schema.TypeInt,
Required: true,
},
"grouping_fields": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"repeat_interval": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
},
},
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("dispatch_type").(string) == "DISCARD_ALERT"
},
},
"dispatch_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"CREATE_ALERT", "DISCARD_ALERT"}, false),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"label_match_expression_grid": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"label_match_expression_groups": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"label_match_expressions": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Required: true,
},
"value": {
Type: schema.TypeString,
Required: true,
},
"operator": {
Type: schema.TypeString,
Required: true,
},
},
},
},
},
},
},
},
},
},
"notify_rules": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"notify_objects": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"notify_object_id": {
Type: schema.TypeString,
Required: true,
},
"notify_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"ARMS_CONTACT", "ARMS_CONTACT_GROUP"}, false),
},
"name": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"notify_channels": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("dispatch_type").(string) == "DISCARD_ALERT"
},
},
"dispatch_rule_name": {
Type: schema.TypeString,
Required: true,
},
},
}
}
func resourceAlicloudArmsDispatchRuleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateDispatchRule"
request := make(map[string]interface{})
conn, err := client.NewArmsClient()
if err != nil {
return WrapError(err)
}
dispatchRuleMap := make(map[string]interface{}, 0)
if v, ok := d.GetOk("is_recover"); ok {
dispatchRuleMap["isRecover"] = v
}
if v, ok := d.GetOk("group_rules"); ok {
groupRulesMaps := make([]map[string]interface{}, 0)
for _, groupRules := range v.(*schema.Set).List() {
groupRulesArg := groupRules.(map[string]interface{})
groupRulesMap := map[string]interface{}{
"groupWait": groupRulesArg["group_wait_time"],
"groupInterval": groupRulesArg["group_interval"],
"groupingFields": groupRulesArg["grouping_fields"],
"repeatInterval": groupRulesArg["repeat_interval"],
}
groupRulesMaps = append(groupRulesMaps, groupRulesMap)
}
dispatchRuleMap["groupRules"] = groupRulesMaps
}
if v, ok := d.GetOk("dispatch_type"); ok {
dispatchRuleMap["dispatchType"] = v
}
if v, ok := d.GetOk("label_match_expression_grid"); ok {
labelMatchExpressionGrid := v.(*schema.Set).List()[0]
labelMatchExpressionGridArg := labelMatchExpressionGrid.(map[string]interface{})
labelMatchExpressionGroupsMaps := make([]map[string]interface{}, 0)
for _, labelMatchExpressionGroups := range labelMatchExpressionGridArg["label_match_expression_groups"].(*schema.Set).List() {
labelMatchExpressionGroupsArg := labelMatchExpressionGroups.(map[string]interface{})
labelMatchExpressionsMaps := make([]map[string]interface{}, 0)
for _, labelMatchExpressions := range labelMatchExpressionGroupsArg["label_match_expressions"].(*schema.Set).List() {
labelMatchExpressionsArg := labelMatchExpressions.(map[string]interface{})
labelMatchExpressionsMap := map[string]interface{}{
"key": labelMatchExpressionsArg["key"],
"value": labelMatchExpressionsArg["value"],
"operator": labelMatchExpressionsArg["operator"],
}
labelMatchExpressionsMaps = append(labelMatchExpressionsMaps, labelMatchExpressionsMap)
}
labelMatchExpressionGroupsMaps = append(labelMatchExpressionGroupsMaps, map[string]interface{}{
"labelMatchExpressions": labelMatchExpressionsMaps,
})
}
dispatchRuleMap["labelMatchExpressionGrid"] = map[string]interface{}{
"labelMatchExpressionGroups": labelMatchExpressionGroupsMaps,
}
}
if v, ok := d.GetOk("notify_rules"); ok {
notifyRulesMaps := make([]map[string]interface{}, 0)
for _, notifyRules := range v.(*schema.Set).List() {
notifyRulesArg := notifyRules.(map[string]interface{})
notifyObjectsMaps := make([]map[string]interface{}, 0)
for _, notifyObjects := range notifyRulesArg["notify_objects"].(*schema.Set).List() {
notifyObjectsArg := notifyObjects.(map[string]interface{})
notifyObjectsMap := map[string]interface{}{
"notifyType": notifyObjectsArg["notify_type"],
"name": notifyObjectsArg["name"],
"notifyObjectId": notifyObjectsArg["notify_object_id"],
}
notifyObjectsMaps = append(notifyObjectsMaps, notifyObjectsMap)
}
notifyRulesMap := map[string]interface{}{
"notifyObjects": notifyObjectsMaps,
"notifyChannels": notifyRulesArg["notify_channels"].([]interface{}),
}
notifyRulesMaps = append(notifyRulesMaps, notifyRulesMap)
}
dispatchRuleMap["notifyRules"] = notifyRulesMaps
}
if v, ok := d.GetOk("dispatch_rule_name"); ok {
dispatchRuleMap["name"] = v
}
request["RegionId"] = client.RegionId
if v, err := convertMaptoJsonString(dispatchRuleMap); err != nil {
return WrapError(err)
} else {
request["DispatchRule"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_arms_dispatch_rule", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["DispatchRuleId"]))
return resourceAlicloudArmsDispatchRuleRead(d, meta)
}
func resourceAlicloudArmsDispatchRuleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
armsService := ArmsService{client}
object, err := armsService.DescribeArmsDispatchRule(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_arms_dispatch_rule armsService.DescribeArmsDispatchRule Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
if groupRulesList, ok := object["GroupRules"]; ok && groupRulesList != nil {
groupRulesMaps := make([]map[string]interface{}, 0)
for _, groupRulesListItem := range groupRulesList.([]interface{}) {
if groupRulesItemMap, ok := groupRulesListItem.(map[string]interface{}); ok {
groupRulesMap := make(map[string]interface{}, 0)
groupRulesMap["group_interval"] = groupRulesItemMap["GroupInterval"]
groupRulesMap["group_wait_time"] = groupRulesItemMap["GroupWaitTime"]
groupRulesMap["group_id"] = groupRulesItemMap["GroupId"]
groupRulesMap["grouping_fields"] = groupRulesItemMap["GroupingFields"]
groupRulesMap["repeat_interval"] = groupRulesItemMap["RepeatInterval"]
groupRulesMaps = append(groupRulesMaps, groupRulesMap)
}
}
d.Set("group_rules", groupRulesMaps)
}
d.Set("status", object["State"])
if labelMatchExpressionGrid, ok := object["LabelMatchExpressionGrid"]; ok && labelMatchExpressionGrid != nil {
labelMatchExpressionGridMaps := make([]map[string]interface{}, 0)
labelMatchExpressionGridMap := make(map[string]interface{})
labelMatchExpressionGroupsMaps := make([]map[string]interface{}, 0)
if v, ok := labelMatchExpressionGrid.(map[string]interface{})["LabelMatchExpressionGroups"]; ok && v != nil {
for _, labelMatchExpressionGroups := range v.([]interface{}) {
labelMatchExpressionGroupsMap := make(map[string]interface{})
labelMatchExpressionsMaps := make([]map[string]interface{}, 0)
if v, ok := labelMatchExpressionGroups.(map[string]interface{})["LabelMatchExpressions"]; ok && v != nil {
for _, labelMatchExpressions := range v.([]interface{}) {
labelMatchExpressionsArg := labelMatchExpressions.(map[string]interface{})
labelMatchExpressionsMap := make(map[string]interface{}, 0)
labelMatchExpressionsMap["operator"] = labelMatchExpressionsArg["Operator"]
labelMatchExpressionsMap["key"] = labelMatchExpressionsArg["Key"]
labelMatchExpressionsMap["value"] = labelMatchExpressionsArg["Value"]
labelMatchExpressionsMaps = append(labelMatchExpressionsMaps, labelMatchExpressionsMap)
}
}
labelMatchExpressionGroupsMap["label_match_expressions"] = labelMatchExpressionsMaps
labelMatchExpressionGroupsMaps = append(labelMatchExpressionGroupsMaps, labelMatchExpressionGroupsMap)
}
}
labelMatchExpressionGridMap["label_match_expression_groups"] = labelMatchExpressionGroupsMaps
labelMatchExpressionGridMaps = append(labelMatchExpressionGridMaps, labelMatchExpressionGridMap)
if err := d.Set("label_match_expression_grid", labelMatchExpressionGridMaps); err != nil {
return WrapError(err)
}
}
if notifyRulesList, ok := object["NotifyRules"]; ok && notifyRulesList != nil {
notifyRulesMaps := make([]map[string]interface{}, 0)
for _, notifyRulesListItem := range notifyRulesList.([]interface{}) {
if notifyRulesItemMap, ok := notifyRulesListItem.(map[string]interface{}); ok {
notifyRulesMap := make(map[string]interface{}, 0)
notifyObjectsMaps := make([]map[string]interface{}, 0)
for _, notifyObjects := range notifyRulesItemMap["NotifyObjects"].([]interface{}) {
notifyObjectsArg := notifyObjects.(map[string]interface{})
notifyObjectsMap := make(map[string]interface{}, 0)
notifyObjectsMap["notify_type"] = convertArmsDispatchRuleNotifyTypeResponse(notifyObjectsArg["NotifyType"])
notifyObjectsMap["notify_object_id"] = notifyObjectsArg["NotifyObjectId"]
notifyObjectsMap["name"] = notifyObjectsArg["Name"]
notifyObjectsMaps = append(notifyObjectsMaps, notifyObjectsMap)
}
notifyRulesMap["notify_objects"] = notifyObjectsMaps
notifyRulesMap["notify_channels"] = notifyRulesItemMap["NotifyChannels"]
notifyRulesMaps = append(notifyRulesMaps, notifyRulesMap)
}
}
d.Set("notify_rules", notifyRulesMaps)
}
d.Set("dispatch_rule_name", object["Name"])
return nil
}
func resourceAlicloudArmsDispatchRuleUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "UpdateDispatchRule"
request := make(map[string]interface{})
conn, err := client.NewArmsClient()
if err != nil {
return WrapError(err)
}
dispatchRuleMap := make(map[string]interface{}, 0)
dispatchRuleMap["isRecover"] = d.Get("is_recover")
dispatchRuleMap["ruleid"] = d.Id()
dispatchRuleMap["id"] = d.Id()
if _, ok := d.GetOk("group_rules"); ok {
oraw, nraw := d.GetChange("group_rules")
groupRulesMaps := make([]map[string]interface{}, 0)
groupId := 0
for _, groupRules := range oraw.(*schema.Set).List() {
groupRulesArg := groupRules.(map[string]interface{})
groupId = groupRulesArg["group_id"].(int)
}
for _, groupRules := range nraw.(*schema.Set).List() {
groupRulesArg := groupRules.(map[string]interface{})
groupRulesMap := map[string]interface{}{
"groupId": groupId,
"groupWait": groupRulesArg["group_wait_time"],
"groupInterval": groupRulesArg["group_interval"],
"groupingFields": groupRulesArg["grouping_fields"],
"repeatInterval": groupRulesArg["repeat_interval"],
}
groupRulesMaps = append(groupRulesMaps, groupRulesMap)
}
dispatchRuleMap["groupRules"] = groupRulesMaps
}
if v, ok := d.GetOk("dispatch_type"); ok {
dispatchRuleMap["dispatchType"] = v
}
if v, ok := d.GetOk("label_match_expression_grid"); ok {
labelMatchExpressionGrid := v.(*schema.Set).List()[0]
labelMatchExpressionGridArg := labelMatchExpressionGrid.(map[string]interface{})
labelMatchExpressionGroupsMaps := make([]map[string]interface{}, 0)
for _, labelMatchExpressionGroups := range labelMatchExpressionGridArg["label_match_expression_groups"].(*schema.Set).List() {
labelMatchExpressionGroupsArg := labelMatchExpressionGroups.(map[string]interface{})
labelMatchExpressionsMaps := make([]map[string]interface{}, 0)
for _, labelMatchExpressions := range labelMatchExpressionGroupsArg["label_match_expressions"].(*schema.Set).List() {
labelMatchExpressionsArg := labelMatchExpressions.(map[string]interface{})
labelMatchExpressionsMap := map[string]interface{}{
"key": labelMatchExpressionsArg["key"],
"value": labelMatchExpressionsArg["value"],
"operator": labelMatchExpressionsArg["operator"],
}
labelMatchExpressionsMaps = append(labelMatchExpressionsMaps, labelMatchExpressionsMap)
}
labelMatchExpressionGroupsMaps = append(labelMatchExpressionGroupsMaps, map[string]interface{}{
"labelMatchExpressions": labelMatchExpressionsMaps,
})
}
dispatchRuleMap["labelMatchExpressionGrid"] = map[string]interface{}{
"labelMatchExpressionGroups": labelMatchExpressionGroupsMaps,
}
}
if v, ok := d.GetOk("notify_rules"); ok {
notifyRulesMaps := make([]map[string]interface{}, 0)
for _, notifyRules := range v.(*schema.Set).List() {
notifyRulesArg := notifyRules.(map[string]interface{})
notifyObjectsMaps := make([]map[string]interface{}, 0)
for _, notifyObjects := range notifyRulesArg["notify_objects"].(*schema.Set).List() {
notifyObjectsArg := notifyObjects.(map[string]interface{})
notifyObjectsMap := map[string]interface{}{
"notifyType": notifyObjectsArg["notify_type"],
"name": notifyObjectsArg["name"],
"notifyObjectId": notifyObjectsArg["notify_object_id"],
}
notifyObjectsMaps = append(notifyObjectsMaps, notifyObjectsMap)
}
notifyRulesMap := map[string]interface{}{
"notifyObjects": notifyObjectsMaps,
"notifyChannels": notifyRulesArg["notify_channels"].([]interface{}),
}
notifyRulesMaps = append(notifyRulesMaps, notifyRulesMap)
}
dispatchRuleMap["notifyRules"] = notifyRulesMaps
}
if v, ok := d.GetOk("dispatch_rule_name"); ok {
dispatchRuleMap["name"] = v
}
request["RegionId"] = client.RegionId
if v, err := convertMaptoJsonString(dispatchRuleMap); err != nil {
return WrapError(err)
} else {
request["DispatchRule"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_arms_dispatch_rule", action, AlibabaCloudSdkGoERROR)
}
return resourceAlicloudArmsDispatchRuleRead(d, meta)
}
func resourceAlicloudArmsDispatchRuleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteDispatchRule"
var response map[string]interface{}
conn, err := client.NewArmsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"Id": d.Id(),
"RegionId": client.RegionId,
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func convertArmsDispatchRuleNotifyTypeResponse(source interface{}) interface{} {
switch source {
case "CONTACT":
return "ARMS_CONTACT"
case "CONTACT_GROUP":
return "ARMS_CONTACT_GROUP"
}
return source
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudArmsPrometheusAlertRule() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudArmsPrometheusAlertRuleCreate,
Read: resourceAlicloudArmsPrometheusAlertRuleRead,
Update: resourceAlicloudArmsPrometheusAlertRuleUpdate,
Delete: resourceAlicloudArmsPrometheusAlertRuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"annotations": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
},
"value": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"cluster_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"dispatch_rule_id": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("notify_type"); ok && v.(string) == "DISPATCH_RULE" {
return false
}
return true
},
},
"duration": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"expression": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"labels": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
},
"value": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"message": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"notify_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"ALERT_MANAGER", "DISPATCH_RULE"}, false),
},
"prometheus_alert_rule_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeInt,
Computed: true,
ForceNew: true,
},
"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
},
}
}
func resourceAlicloudArmsPrometheusAlertRuleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreatePrometheusAlertRule"
request := make(map[string]interface{})
conn, err := client.NewArmsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("annotations"); ok {
annotationsMaps := make([]map[string]interface{}, 0)
for _, annotations := range v.(*schema.Set).List() {
annotationsMap := annotations.(map[string]interface{})
annotationsMaps = append(annotationsMaps, annotationsMap)
}
if v, err := convertArrayObjectToJsonString(annotationsMaps); err == nil {
request["Annotations"] = v
} else {
return WrapError(err)
}
}
request["ClusterId"] = d.Get("cluster_id")
if v, ok := d.GetOk("dispatch_rule_id"); ok {
request["DispatchRuleId"] = v
}
request["Duration"] = d.Get("duration")
request["Expression"] = d.Get("expression")
if v, ok := d.GetOk("labels"); ok {
labelsMaps := make([]map[string]interface{}, 0)
for _, labels := range v.(*schema.Set).List() {
labelsMap := labels.(map[string]interface{})
labelsMaps = append(labelsMaps, labelsMap)
}
if v, err := convertArrayObjectToJsonString(labelsMaps); err == nil {
request["Labels"] = v
} else {
return WrapError(err)
}
}
request["Message"] = d.Get("message")
if v, ok := d.GetOk("notify_type"); ok {
request["NotifyType"] = v
}
request["AlertName"] = d.Get("prometheus_alert_rule_name")
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("type"); ok {
request["Type"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_arms_prometheus_alert_rule", action, AlibabaCloudSdkGoERROR)
}
responsePrometheusAlertRule := response["PrometheusAlertRule"].(map[string]interface{})
d.SetId(fmt.Sprint(request["ClusterId"], ":", responsePrometheusAlertRule["AlertId"]))
return resourceAlicloudArmsPrometheusAlertRuleRead(d, meta)
}
func resourceAlicloudArmsPrometheusAlertRuleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
armsService := ArmsService{client}
object, err := armsService.DescribeArmsPrometheusAlertRule(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_arms_prometheus_alert_rule armsService.DescribeArmsPrometheusAlertRule Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("cluster_id", parts[0])
d.Set("prometheus_alert_rule_id", parts[1])
if v, ok := object["Annotations"].([]interface{}); ok {
annotations := make([]map[string]interface{}, 0)
for _, val := range v {
item := val.(map[string]interface{})
if item["Name"] == "message" {
continue
}
temp := map[string]interface{}{
"name": item["Name"],
"value": item["Value"],
}
annotations = append(annotations, temp)
}
if err := d.Set("annotations", annotations); err != nil {
return WrapError(err)
}
}
d.Set("dispatch_rule_id", fmt.Sprint(formatInt(object["DispatchRuleId"])))
d.Set("duration", object["Duration"])
d.Set("expression", object["Expression"])
if v, ok := object["Labels"].([]interface{}); ok {
labels := make([]map[string]interface{}, 0)
for _, val := range v {
item := val.(map[string]interface{})
temp := map[string]interface{}{
"name": item["Name"],
"value": item["Value"],
}
labels = append(labels, temp)
}
if err := d.Set("labels", labels); err != nil {
return WrapError(err)
}
}
d.Set("message", object["Message"])
d.Set("notify_type", object["NotifyType"])
d.Set("prometheus_alert_rule_name", object["AlertName"])
d.Set("status", fmt.Sprint(formatInt(object["Status"])))
d.Set("type", object["Type"])
return nil
}
func resourceAlicloudArmsPrometheusAlertRuleUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"ClusterId": parts[0],
"AlertId": parts[1],
}
request["Duration"] = d.Get("duration")
if d.HasChange("duration") {
update = true
}
request["Expression"] = d.Get("expression")
if d.HasChange("expression") {
update = true
}
request["Message"] = d.Get("message")
if d.HasChange("message") {
update = true
}
request["AlertName"] = d.Get("prometheus_alert_rule_name")
if d.HasChange("prometheus_alert_rule_name") {
update = true
}
request["RegionId"] = client.RegionId
if d.HasChange("annotations") {
update = true
if v, ok := d.GetOk("annotations"); ok {
annotationsMaps := make([]map[string]interface{}, 0)
for _, annotations := range v.(*schema.Set).List() {
annotationsMap := annotations.(map[string]interface{})
annotationsMaps = append(annotationsMaps, annotationsMap)
}
if v, err := convertArrayObjectToJsonString(annotationsMaps); err == nil {
request["Annotations"] = v
} else {
return WrapError(err)
}
}
}
if d.HasChange("dispatch_rule_id") {
update = true
if v, ok := d.GetOk("dispatch_rule_id"); ok {
request["DispatchRuleId"] = v
}
}
if d.HasChange("labels") {
update = true
if v, ok := d.GetOk("labels"); ok {
labelsMaps := make([]map[string]interface{}, 0)
for _, labels := range v.(*schema.Set).List() {
labelsMap := labels.(map[string]interface{})
labelsMaps = append(labelsMaps, labelsMap)
}
if v, err := convertArrayObjectToJsonString(labelsMaps); err == nil {
request["Labels"] = v
} else {
return WrapError(err)
}
}
}
if d.HasChange("notify_type") {
update = true
if v, ok := d.GetOk("notify_type"); ok {
request["NotifyType"] = v
}
}
if update {
action := "UpdatePrometheusAlertRule"
conn, err := client.NewArmsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudArmsPrometheusAlertRuleRead(d, meta)
}
func resourceAlicloudArmsPrometheusAlertRuleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeletePrometheusAlertRule"
var response map[string]interface{}
conn, err := client.NewArmsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AlertId": parts[1],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudAutoProvisioningGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAutoProvisioningGroupCreate,
Read: resourceAlicloudAutoProvisioningGroupRead,
Update: resourceAlicloudAutoProvisioningGroupUpdate,
Delete: resourceAlicloudAutoProvisioningGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"total_target_capacity": {
Type: schema.TypeString,
Required: true,
},
"launch_template_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"auto_provisioning_group_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"auto_provisioning_group_type": {
Type: schema.TypeString,
Default: "maintain",
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"request", "maintain"}, false),
},
"spot_allocation_strategy": {
Type: schema.TypeString,
Default: "lowest-price",
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"lowest-price", "diversified"}, false),
},
"spot_instance_interruption_behavior": {
Type: schema.TypeString,
Default: "stop",
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"stop", "terminate"}, false),
},
"spot_instance_pools_to_use_count": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Computed: true,
},
"pay_as_you_go_allocation_strategy": {
Type: schema.TypeString,
Default: "lowest-price",
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"prioritized", "lowest-price"}, false),
},
"excess_capacity_termination_policy": {
Type: schema.TypeString,
Default: "no-termination",
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"no-termination", "termination"}, false),
},
"valid_from": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"valid_until": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"terminate_instances_with_expiration": {
Type: schema.TypeBool,
Default: false,
Optional: true,
},
"terminate_instances": {
Type: schema.TypeBool,
Default: false,
Optional: true,
ForceNew: true,
},
"max_spot_price": {
Type: schema.TypeFloat,
Optional: true,
Computed: true,
},
"pay_as_you_go_target_capacity": {
Type: schema.TypeString,
Optional: true,
},
"spot_target_capacity": {
Type: schema.TypeString,
Optional: true,
},
"default_target_capacity_type": {
Type: schema.TypeString,
Default: "Spot",
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Spot", "PayAsYouGo"}, false),
},
"launch_template_version": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"launch_template_config": {
Required: true,
ForceNew: true,
Type: schema.TypeList,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"instance_type": {
Type: schema.TypeString,
Optional: true,
},
"max_price": {
Type: schema.TypeString,
Required: true,
},
"vswitch_id": {
Type: schema.TypeString,
Required: true,
},
"weighted_capacity": {
Type: schema.TypeString,
Required: true,
},
"priority": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
},
},
},
},
}
}
func resourceAlicloudAutoProvisioningGroupCreate(d *schema.ResourceData, meta interface{}) error {
request, err := buildAlicloudAutoProvisioningGroupArgs(d, meta)
if err != nil {
return WrapError(err)
}
client := meta.(*connectivity.AliyunClient)
if err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.CreateAutoProvisioningGroup(request)
})
if err != nil {
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ecs.CreateAutoProvisioningGroupResponse)
d.SetId(response.AutoProvisioningGroupId)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_auto_provisioning_group", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return resourceAlicloudAutoProvisioningGroupRead(d, meta)
}
func resourceAlicloudAutoProvisioningGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
object, err := ecsService.DescribeAutoProvisioningGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_auto_provisioning_group ecsService.DescribeAutoProvisioningGroup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("auto_provisioning_group_name", object.AutoProvisioningGroupName)
d.Set("launch_template_id", object.LaunchTemplateId)
d.Set("auto_provisioning_group_type", object.AutoProvisioningGroupType)
d.Set("auto_provisioning_group_id", object.AutoProvisioningGroupId)
d.Set("create_time", object.CreationTime)
d.Set("excess_capacity_termination_policy", object.ExcessCapacityTerminationPolicy)
d.Set("terminate_instances_with_expiration", object.TerminateInstancesWithExpiration)
d.Set("max_spot_price", object.MaxSpotPrice)
d.Set("terminate_instances", object.TerminateInstances)
d.Set("valid_from", object.ValidFrom)
d.Set("valid_until", object.ValidUntil)
d.Set("status", object.Status)
d.Set("state", object.State)
d.Set("pay_as_you_go_target_capacity", fmt.Sprintf("%v", object.TargetCapacitySpecification.PayAsYouGoTargetCapacity))
d.Set("pay_as_you_go_allocation_strategy", object.PayAsYouGoOptions.AllocationStrategy)
d.Set("spot_target_capacity", fmt.Sprintf("%v", object.TargetCapacitySpecification.SpotTargetCapacity))
d.Set("spot_allocation_strategy", object.SpotOptions.AllocationStrategy)
d.Set("spot_instance_interruption_behavior", object.SpotOptions.InstanceInterruptionBehavior)
d.Set("spot_instance_pools_to_use_count", object.SpotOptions.InstancePoolsToUseCount)
d.Set("total_target_capacity", fmt.Sprintf("%v", object.TargetCapacitySpecification.TotalTargetCapacity))
d.Set("default_target_capacity_type", object.TargetCapacitySpecification.DefaultTargetCapacityType)
d.Set("launch_template_version", object.LaunchTemplateVersion)
launch_template_config := []map[string]interface{}{}
para := map[string]interface{}{}
for _, mappara := range object.LaunchTemplateConfigs.LaunchTemplateConfig {
para["instance_type"] = mappara.InstanceType
para["vswitch_id"] = mappara.VSwitchId
para["weighted_capacity"] = fmt.Sprintf("%v", mappara.WeightedCapacity)
para["max_price"] = fmt.Sprintf("%v", mappara.MaxPrice)
para["priority"] = fmt.Sprintf("%v", mappara.Priority)
}
launch_template_config = append(launch_template_config, para)
d.Set("launch_template_config", launch_template_config)
return nil
}
func resourceAlicloudAutoProvisioningGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ecs.CreateModifyAutoProvisioningGroupRequest()
request.RegionId = client.RegionId
request.AutoProvisioningGroupId = d.Id()
if d.HasChange("excess_capacity_termination_policy") {
if v, ok := d.GetOk("excess_capacity_termination_policy"); ok {
request.ExcessCapacityTerminationPolicy = v.(string)
}
}
if d.HasChange("default_target_capacity_type") {
if v, ok := d.GetOk("default_target_capacity_type"); ok {
request.DefaultTargetCapacityType = v.(string)
}
}
if d.HasChange("terminate_instances_with_expiration") {
request.TerminateInstancesWithExpiration = requests.NewBoolean(d.Get("terminate_instances_with_expiration").(bool))
}
if d.HasChange("max_spot_price") {
request.MaxSpotPrice = requests.NewFloat(d.Get("max_spot_price").(float64))
}
if d.HasChange("total_target_capacity") {
if v, ok := d.GetOk("total_target_capacity"); ok {
request.TotalTargetCapacity = v.(string)
}
}
if d.HasChange("pay_as_you_go_target_capacity") {
if v, ok := d.GetOk("pay_as_you_go_target_capacity"); ok {
request.PayAsYouGoTargetCapacity = v.(string)
}
}
if d.HasChange("spot_target_capacity") {
if v, ok := d.GetOk("spot_target_capacity"); ok {
request.SpotTargetCapacity = v.(string)
}
}
if d.HasChange("auto_provisioning_group_name") {
if v, ok := d.GetOk("auto_provisioning_group_name"); ok {
request.AutoProvisioningGroupName = v.(string)
}
}
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ModifyAutoProvisioningGroup(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return resourceAlicloudAutoProvisioningGroupRead(d, meta)
}
func resourceAlicloudAutoProvisioningGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
request := ecs.CreateDeleteAutoProvisioningGroupRequest()
request.RegionId = client.RegionId
request.AutoProvisioningGroupId = d.Id()
request.TerminateInstances = requests.NewBoolean(d.Get("terminate_instances").(bool))
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DeleteAutoProvisioningGroup(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidAutoProvisioningGroupId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(ecsService.WaitForAutoProvisioningGroup(d.Id(), Deleted, DefaultTimeoutMedium))
}
func buildAlicloudAutoProvisioningGroupArgs(d *schema.ResourceData, meta interface{}) (*ecs.CreateAutoProvisioningGroupRequest, error) {
client := meta.(*connectivity.AliyunClient)
request := ecs.CreateCreateAutoProvisioningGroupRequest()
request.RegionId = client.RegionId
request.LaunchTemplateId = d.Get("launch_template_id").(string)
request.TotalTargetCapacity = d.Get("total_target_capacity").(string)
if v, ok := d.GetOk("auto_provisioning_group_name"); ok && v.(string) != "" {
request.AutoProvisioningGroupName = v.(string)
}
if v, ok := d.GetOk("auto_provisioning_group_type"); ok && v.(string) != "" {
request.AutoProvisioningGroupType = v.(string)
}
if v, ok := d.GetOk("spot_allocation_strategy"); ok && v.(string) != "" {
request.SpotAllocationStrategy = v.(string)
}
if v, ok := d.GetOk("spot_instance_interruption_behavior"); ok && v.(string) != "" {
request.SpotInstanceInterruptionBehavior = v.(string)
}
if v, ok := d.GetOk("spot_instancePools_to_use_count"); ok && v.(string) != "" {
request.SpotInstancePoolsToUseCount = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("pay_as_you_go_allocation_strategy"); ok && v.(string) != "" {
request.PayAsYouGoAllocationStrategy = v.(string)
}
if v, ok := d.GetOk("excess_capacity_termination_policy"); ok && v.(string) != "" {
request.ExcessCapacityTerminationPolicy = v.(string)
}
if v, ok := d.GetOk("valid_from"); ok && v.(string) != "" {
request.ValidFrom = v.(string)
}
if v, ok := d.GetOk("valid_until"); ok && v.(string) != "" {
request.ValidUntil = v.(string)
}
if v, ok := d.GetOk("terminate_instances_with_expiration"); ok {
request.TerminateInstancesWithExpiration = requests.NewBoolean(v.(bool))
}
if v, ok := d.GetOk("terminate_instances"); ok {
request.TerminateInstances = requests.NewBoolean(v.(bool))
}
if v, ok := d.GetOk("max_spot_price"); ok && v.(float64) != 0.0 {
request.MaxSpotPrice = requests.NewFloat(v.(float64))
}
if v, ok := d.GetOk("pay_as_you_go_target_capacity"); ok && v.(string) != "" {
request.PayAsYouGoTargetCapacity = v.(string)
}
if v, ok := d.GetOk("spot_target_capacity"); ok && v.(string) != "" {
request.SpotTargetCapacity = v.(string)
}
if v, ok := d.GetOk("default_target_capacity_type"); ok && v.(string) != "" {
request.DefaultTargetCapacityType = v.(string)
}
if v, ok := d.GetOk("launch_template_version"); ok && v.(string) != "" {
request.LaunchTemplateVersion = v.(string)
}
if v, ok := d.GetOk("description"); ok && v.(string) != "" {
request.Description = v.(string)
}
configs := d.Get("launch_template_config")
confs := configs.([]interface{})
createConfigs := make([]ecs.CreateAutoProvisioningGroupLaunchTemplateConfig, 0, len(confs))
for _, c := range confs {
cc := c.(map[string]interface{})
conf := ecs.CreateAutoProvisioningGroupLaunchTemplateConfig{
MaxPrice: cc["max_price"].(string),
VSwitchId: cc["vswitch_id"].(string),
WeightedCapacity: cc["weighted_capacity"].(string),
}
if v, ok := cc["instance_type"]; ok && v.(string) != "" {
conf.InstanceType = cc["instance_type"].(string)
}
if v, ok := cc["priority"]; ok && v.(string) != "" {
conf.Priority = cc["priority"].(string)
}
createConfigs = append(createConfigs, conf)
}
request.LaunchTemplateConfig = &createConfigs
return request, nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudBastionhostHost() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudBastionhostHostCreate,
Read: resourceAlicloudBastionhostHostRead,
Update: resourceAlicloudBastionhostHostUpdate,
Delete: resourceAlicloudBastionhostHostDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"active_address_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"Private", "Public"}, false),
},
"comment": {
Type: schema.TypeString,
Optional: true,
},
"host_id": {
Type: schema.TypeString,
Computed: true,
},
"host_name": {
Type: schema.TypeString,
Required: true,
},
"host_private_address": {
Type: schema.TypeString,
Optional: true,
},
"host_public_address": {
Type: schema.TypeString,
Optional: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_region_id": {
Type: schema.TypeString,
Optional: true,
},
"os_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"Linux", "Windows"}, false),
},
"source": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Ecs", "Local", "Rds"}, false),
},
"source_instance_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudBastionhostHostCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateHost"
request := make(map[string]interface{})
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
request["ActiveAddressType"] = d.Get("active_address_type")
if v, ok := d.GetOk("comment"); ok {
request["Comment"] = v
}
request["HostName"] = d.Get("host_name")
if v, ok := d.GetOk("host_private_address"); ok {
request["HostPrivateAddress"] = v
}
if v, ok := d.GetOk("host_public_address"); ok {
request["HostPublicAddress"] = v
}
request["InstanceId"] = d.Get("instance_id")
if v, ok := d.GetOk("instance_region_id"); ok {
request["InstanceRegionId"] = v
}
request["OSType"] = d.Get("os_type")
request["RegionId"] = client.RegionId
request["Source"] = d.Get("source")
if v, ok := d.GetOk("source_instance_id"); ok {
request["SourceInstanceId"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_bastionhost_host", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["InstanceId"], ":", response["HostId"]))
return resourceAlicloudBastionhostHostRead(d, meta)
}
func resourceAlicloudBastionhostHostRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
yundunBastionhostService := YundunBastionhostService{client}
object, err := yundunBastionhostService.DescribeBastionhostHost(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_bastionhost_host yundunBastionhostService.DescribeBastionhostHost Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("host_id", parts[1])
d.Set("instance_id", parts[0])
d.Set("active_address_type", object["ActiveAddressType"])
d.Set("comment", object["Comment"])
d.Set("host_name", object["HostName"])
d.Set("host_private_address", object["HostPrivateAddress"])
d.Set("host_public_address", object["HostPublicAddress"])
d.Set("os_type", object["OSType"])
d.Set("source", object["Source"])
d.Set("source_instance_id", object["SourceInstanceId"])
return nil
}
func resourceAlicloudBastionhostHostUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Partial(true)
update := false
request := map[string]interface{}{
"HostIds": convertListToJsonString([]interface{}{parts[1]}),
"InstanceId": parts[0],
}
if d.HasChange("active_address_type") {
update = true
}
request["ActiveAddressType"] = d.Get("active_address_type")
request["RegionId"] = client.RegionId
if update {
action := "ModifyHostsActiveAddressType"
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("active_address_type")
}
update = false
modifyHostReq := map[string]interface{}{
"HostId": parts[1],
"InstanceId": parts[0],
}
if d.HasChange("comment") {
update = true
if v, ok := d.GetOk("comment"); ok {
modifyHostReq["Comment"] = v
}
}
if d.HasChange("host_name") {
update = true
modifyHostReq["HostName"] = d.Get("host_name")
}
if d.HasChange("host_private_address") {
update = true
if v, ok := d.GetOk("host_private_address"); ok {
modifyHostReq["HostPrivateAddress"] = v
}
}
if d.HasChange("host_public_address") {
update = true
if v, ok := d.GetOk("host_public_address"); ok {
modifyHostReq["HostPublicAddress"] = v
}
}
if d.HasChange("os_type") {
update = true
modifyHostReq["OSType"] = d.Get("os_type")
}
modifyHostReq["RegionId"] = client.RegionId
if update {
action := "ModifyHost"
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, modifyHostReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyHostReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("comment")
d.SetPartial("host_name")
d.SetPartial("host_private_address")
d.SetPartial("host_public_address")
d.SetPartial("os_type")
}
d.Partial(false)
return resourceAlicloudBastionhostHostRead(d, meta)
}
func resourceAlicloudBastionhostHostDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteHost"
var response map[string]interface{}
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"HostId": parts[1],
"InstanceId": parts[0],
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Commodity.BizError.InvalidStatus", "OBJECT_NOT_FOUND"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudBastionhostHostAccount() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudBastionhostHostAccountCreate,
Read: resourceAlicloudBastionhostHostAccountRead,
Update: resourceAlicloudBastionhostHostAccountUpdate,
Delete: resourceAlicloudBastionhostHostAccountDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"host_account_id": {
Type: schema.TypeString,
Computed: true,
},
"host_account_name": {
Type: schema.TypeString,
Required: true,
},
"host_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"pass_phrase": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("protocol_name"); ok && v.(string) == "SSH" {
return false
}
return true
},
},
"password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"private_key": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("protocol_name"); ok && v.(string) == "SSH" {
return false
}
return true
},
},
"protocol_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"RDP", "SSH"}, false),
},
},
}
}
func resourceAlicloudBastionhostHostAccountCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateHostAccount"
request := make(map[string]interface{})
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
request["HostAccountName"] = d.Get("host_account_name")
request["HostId"] = d.Get("host_id")
request["InstanceId"] = d.Get("instance_id")
if v, ok := d.GetOk("pass_phrase"); ok {
request["PassPhrase"] = v
}
if v, ok := d.GetOk("password"); ok {
request["Password"] = v
}
if v, ok := d.GetOk("private_key"); ok {
request["PrivateKey"] = v
}
request["ProtocolName"] = d.Get("protocol_name")
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_bastionhost_host_account", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["InstanceId"], ":", response["HostAccountId"]))
return resourceAlicloudBastionhostHostAccountRead(d, meta)
}
func resourceAlicloudBastionhostHostAccountRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
yundunBastionhostService := YundunBastionhostService{client}
object, err := yundunBastionhostService.DescribeBastionhostHostAccount(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_bastionhost_host_account yundunBastionhostService.DescribeBastionhostHostAccount Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("host_account_id", parts[1])
d.Set("instance_id", parts[0])
d.Set("host_account_name", object["HostAccountName"])
d.Set("host_id", object["HostId"])
d.Set("protocol_name", object["ProtocolName"])
return nil
}
func resourceAlicloudBastionhostHostAccountUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"HostAccountId": parts[1],
"InstanceId": parts[0],
}
if d.HasChange("host_account_name") {
update = true
request["HostAccountName"] = d.Get("host_account_name")
}
if d.HasChange("pass_phrase") {
update = true
if v, ok := d.GetOk("pass_phrase"); ok {
request["PassPhrase"] = v
}
}
if d.HasChange("password") {
update = true
if v, ok := d.GetOk("password"); ok {
request["Password"] = v
}
}
if d.HasChange("private_key") {
update = true
if v, ok := d.GetOk("private_key"); ok {
request["PrivateKey"] = v
}
}
request["RegionId"] = client.RegionId
if update {
action := "ModifyHostAccount"
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudBastionhostHostAccountRead(d, meta)
}
func resourceAlicloudBastionhostHostAccountDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteHostAccount"
var response map[string]interface{}
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"HostAccountId": parts[1],
"InstanceId": parts[0],
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Commodity.BizError.InvalidStatus", "OBJECT_NOT_FOUND"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudBastionhostHostAccountUserAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudBastionhostHostAccountUserAttachmentCreate,
Read: resourceAlicloudBastionhostHostAccountUserAttachmentRead,
Update: resourceAlicloudBastionhostHostAccountUserAttachmentUpdate,
Delete: resourceAlicloudBastionhostHostAccountUserAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"host_account_ids": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"host_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"user_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudBastionhostHostAccountUserAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
d.SetId(fmt.Sprint(d.Get("instance_id"), ":", d.Get("user_id"), ":", d.Get("host_id")))
return resourceAlicloudBastionhostHostAccountUserAttachmentUpdate(d, meta)
}
func resourceAlicloudBastionhostHostAccountUserAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
yundunBastionhostService := YundunBastionhostService{client}
object, err := yundunBastionhostService.DescribeBastionhostHostAccountUserAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_bastionhost_host_account_user_attachment yundunBastionhostService.DescribeBastionhostHostAccountUserAttachment Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
d.Set("host_id", parts[2])
d.Set("instance_id", parts[0])
d.Set("user_id", parts[1])
hostAccountIdsItems := make([]string, 0)
for _, item := range object {
itemMap := item.(map[string]interface{})
if v, ok := itemMap["IsAuthorized"]; !ok || !v.(bool) {
continue
}
if v, ok := itemMap["HostAccountId"]; ok && v != nil {
hostAccountIdsItems = append(hostAccountIdsItems, fmt.Sprint(v))
}
}
d.Set("host_account_ids", hostAccountIdsItems)
return nil
}
func resourceAlicloudBastionhostHostAccountUserAttachmentUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
if d.HasChange("host_account_ids") {
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
action := "AttachHostAccountsToUser"
request := make(map[string]interface{})
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
oraw, nraw := d.GetChange("host_account_ids")
request["InstanceId"] = parts[0]
request["RegionId"] = client.RegionId
request["UserId"] = parts[1]
if oraw != nil && len(oraw.(*schema.Set).List()) > 0 {
action = "DetachHostAccountsFromUser"
hostRequestMaps := make([]map[string]interface{}, 0)
hostRequestMap := make(map[string]interface{}, 0)
hostRequestMap["HostId"] = parts[2]
hostRequestMap["HostAccountIds"] = oraw.(*schema.Set).List()
hostRequestMaps = append(hostRequestMaps, hostRequestMap)
if v, err := convertListMapToJsonString(hostRequestMaps); err != nil {
return WrapError(err)
} else {
request["Hosts"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
_, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if nraw != nil && len(nraw.(*schema.Set).List()) > 0 {
action = "AttachHostAccountsToUser"
hostRequestMaps := make([]map[string]interface{}, 0)
hostRequestMap := make(map[string]interface{}, 0)
hostRequestMap["HostId"] = parts[2]
hostRequestMap["HostAccountIds"] = nraw.(*schema.Set).List()
hostRequestMaps = append(hostRequestMaps, hostRequestMap)
if v, err := convertListMapToJsonString(hostRequestMaps); err != nil {
return WrapError(err)
} else {
request["Hosts"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
_, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
}
return resourceAlicloudBastionhostHostAccountUserAttachmentRead(d, meta)
}
func resourceAlicloudBastionhostHostAccountUserAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
action := "DetachHostAccountsFromUser"
var response map[string]interface{}
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"InstanceId": parts[0],
"UserId": parts[1],
}
request["RegionId"] = client.RegionId
hostRequestMaps := make([]map[string]interface{}, 0)
hostRequestMap := make(map[string]interface{}, 0)
hostRequestMap["HostId"] = parts[2]
hostRequestMap["HostAccountIds"] = d.Get("host_account_ids").(*schema.Set).List()
hostRequestMaps = append(hostRequestMaps, hostRequestMap)
if v, err := convertListMapToJsonString(hostRequestMaps); err != nil {
return WrapError(err)
} else {
request["Hosts"] = v
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudBastionhostHostAccountUserGroupAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudBastionhostHostAccountUserGroupAttachmentCreate,
Read: resourceAlicloudBastionhostHostAccountUserGroupAttachmentRead,
Update: resourceAlicloudBastionhostHostAccountUserGroupAttachmentUpdate,
Delete: resourceAlicloudBastionhostHostAccountUserGroupAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"host_account_ids": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"host_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"user_group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudBastionhostHostAccountUserGroupAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
d.SetId(fmt.Sprint(d.Get("instance_id"), ":", d.Get("user_group_id"), ":", d.Get("host_id")))
return resourceAlicloudBastionhostHostAccountUserGroupAttachmentUpdate(d, meta)
}
func resourceAlicloudBastionhostHostAccountUserGroupAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
yundunBastionhostService := YundunBastionhostService{client}
object, err := yundunBastionhostService.DescribeBastionhostHostAccountUserGroupAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_bastionhost_host_account_user_attachment yundunBastionhostService.DescribeBastionhostHostAccountUserGroupAttachment Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
d.Set("host_id", parts[2])
d.Set("instance_id", parts[0])
d.Set("user_group_id", parts[1])
hostAccountIdsItems := make([]string, 0)
for _, item := range object {
itemMap := item.(map[string]interface{})
if v, ok := itemMap["IsAuthorized"]; !ok || !v.(bool) {
continue
}
if v, ok := itemMap["HostAccountId"]; ok && v != nil {
hostAccountIdsItems = append(hostAccountIdsItems, fmt.Sprint(v))
}
}
d.Set("host_account_ids", hostAccountIdsItems)
return nil
}
func resourceAlicloudBastionhostHostAccountUserGroupAttachmentUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
if d.HasChange("host_account_ids") {
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
action := "AttachHostAccountsToUserGroup"
request := make(map[string]interface{})
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
oraw, nraw := d.GetChange("host_account_ids")
request["InstanceId"] = parts[0]
request["RegionId"] = client.RegionId
request["UserGroupId"] = parts[1]
if oraw != nil && len(oraw.(*schema.Set).List()) > 0 {
action = "DetachHostAccountsFromUserGroup"
hostRequestMaps := make([]map[string]interface{}, 0)
hostRequestMap := make(map[string]interface{}, 0)
hostRequestMap["HostId"] = parts[2]
hostRequestMap["HostAccountIds"] = oraw.(*schema.Set).List()
hostRequestMaps = append(hostRequestMaps, hostRequestMap)
if v, err := convertListMapToJsonString(hostRequestMaps); err != nil {
return WrapError(err)
} else {
request["Hosts"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
_, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if nraw != nil && len(nraw.(*schema.Set).List()) > 0 {
action = "AttachHostAccountsToUserGroup"
hostRequestMaps := make([]map[string]interface{}, 0)
hostRequestMap := make(map[string]interface{}, 0)
hostRequestMap["HostId"] = parts[2]
hostRequestMap["HostAccountIds"] = nraw.(*schema.Set).List()
hostRequestMaps = append(hostRequestMaps, hostRequestMap)
if v, err := convertListMapToJsonString(hostRequestMaps); err != nil {
return WrapError(err)
} else {
request["Hosts"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
_, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
}
return resourceAlicloudBastionhostHostAccountUserGroupAttachmentRead(d, meta)
}
func resourceAlicloudBastionhostHostAccountUserGroupAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
action := "DetachHostAccountsFromUserGroup"
var response map[string]interface{}
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"InstanceId": parts[0],
"UserGroupId": parts[1],
}
request["RegionId"] = client.RegionId
hostRequestMaps := make([]map[string]interface{}, 0)
hostRequestMap := make(map[string]interface{}, 0)
hostRequestMap["HostId"] = parts[2]
hostRequestMap["HostAccountIds"] = d.Get("host_account_ids").(*schema.Set).List()
hostRequestMaps = append(hostRequestMaps, hostRequestMap)
if v, err := convertListMapToJsonString(hostRequestMaps); err != nil {
return WrapError(err)
} else {
request["Hosts"] = v
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudBastionhostHostAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudBastionhostHostAttachmentCreate,
Read: resourceAlicloudBastionhostHostAttachmentRead,
Delete: resourceAlicloudBastionhostHostAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"host_group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"host_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudBastionhostHostAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AddHostsToGroup"
request := make(map[string]interface{})
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
request["HostGroupId"] = d.Get("host_group_id")
request["HostIds"] = convertListToJsonString([]interface{}{d.Get("host_id")})
request["InstanceId"] = d.Get("instance_id")
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_bastionhost_host_attachment", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["InstanceId"], ":", request["HostGroupId"], ":", d.Get("host_id")))
return resourceAlicloudBastionhostHostAttachmentRead(d, meta)
}
func resourceAlicloudBastionhostHostAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
yundunBastionhostService := YundunBastionhostService{client}
_, err := yundunBastionhostService.DescribeBastionhostHostAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_bastionhost_host_attachment yundunBastionhostService.DescribeBastionhostHostAttachment Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
d.Set("host_group_id", parts[1])
d.Set("host_id", parts[2])
d.Set("instance_id", parts[0])
return nil
}
func resourceAlicloudBastionhostHostAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
action := "RemoveHostsFromGroup"
var response map[string]interface{}
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"HostGroupId": parts[1],
"HostIds": convertListToJsonString([]interface{}{parts[2]}),
"InstanceId": parts[0],
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudBastionhostHostGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudBastionhostHostGroupCreate,
Read: resourceAlicloudBastionhostHostGroupRead,
Update: resourceAlicloudBastionhostHostGroupUpdate,
Delete: resourceAlicloudBastionhostHostGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"comment": {
Type: schema.TypeString,
Optional: true,
},
"host_group_id": {
Type: schema.TypeString,
Computed: true,
},
"host_group_name": {
Type: schema.TypeString,
Required: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudBastionhostHostGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateHostGroup"
request := make(map[string]interface{})
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("comment"); ok {
request["Comment"] = v
}
request["HostGroupName"] = d.Get("host_group_name")
request["InstanceId"] = d.Get("instance_id")
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_bastionhost_host_group", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["InstanceId"], ":", response["HostGroupId"]))
return resourceAlicloudBastionhostHostGroupRead(d, meta)
}
func resourceAlicloudBastionhostHostGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
yundunBastionhostService := YundunBastionhostService{client}
object, err := yundunBastionhostService.DescribeBastionhostHostGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_bastionhost_host_group yundunBastionhostService.DescribeBastionhostHostGroup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("host_group_id", parts[1])
d.Set("instance_id", parts[0])
d.Set("comment", object["Comment"])
d.Set("host_group_name", object["HostGroupName"])
return nil
}
func resourceAlicloudBastionhostHostGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"HostGroupId": parts[1],
"InstanceId": parts[0],
}
if d.HasChange("comment") {
update = true
if v, ok := d.GetOk("comment"); ok {
request["Comment"] = v
}
}
if d.HasChange("host_group_name") {
update = true
request["HostGroupName"] = d.Get("host_group_name")
}
request["RegionId"] = client.RegionId
if update {
action := "ModifyHostGroup"
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudBastionhostHostGroupRead(d, meta)
}
func resourceAlicloudBastionhostHostGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteHostGroup"
var response map[string]interface{}
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"HostGroupId": parts[1],
"InstanceId": parts[0],
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"OBJECT_NOT_FOUND"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudBastionhostHostGroupAccountUserAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudBastionhostHostGroupAccountUserAttachmentCreate,
Read: resourceAlicloudBastionhostHostGroupAccountUserAttachmentRead,
Update: resourceAlicloudBastionhostHostGroupAccountUserAttachmentUpdate,
Delete: resourceAlicloudBastionhostHostGroupAccountUserAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"host_account_names": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"host_group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"user_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudBastionhostHostGroupAccountUserAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
d.SetId(fmt.Sprint(d.Get("instance_id"), ":", d.Get("user_id"), ":", d.Get("host_group_id")))
return resourceAlicloudBastionhostHostGroupAccountUserAttachmentUpdate(d, meta)
}
func resourceAlicloudBastionhostHostGroupAccountUserAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
yundunBastionhostService := YundunBastionhostService{client}
object, err := yundunBastionhostService.DescribeBastionhostHostGroupAccountUserAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_bastionhost_host_group_account_user_attachment yundunBastionhostService.DescribeBastionhostHostGroupAccountUserAttachment Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
d.Set("host_group_id", parts[2])
d.Set("instance_id", parts[0])
d.Set("user_id", parts[1])
d.Set("host_account_names", object)
return nil
}
func resourceAlicloudBastionhostHostGroupAccountUserAttachmentUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
if d.HasChange("host_account_names") {
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
action := "AttachHostGroupAccountsToUser"
request := make(map[string]interface{})
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
oraw, nraw := d.GetChange("host_account_names")
request["InstanceId"] = parts[0]
request["RegionId"] = client.RegionId
request["UserId"] = parts[1]
if oraw != nil && len(oraw.(*schema.Set).List()) > 0 {
action = "DetachHostGroupAccountsFromUser"
hostRequestMaps := make([]map[string]interface{}, 0)
hostRequestMap := make(map[string]interface{}, 0)
hostRequestMap["HostGroupId"] = parts[2]
hostRequestMap["HostAccountNames"] = oraw.(*schema.Set).List()
hostRequestMaps = append(hostRequestMaps, hostRequestMap)
if v, err := convertListMapToJsonString(hostRequestMaps); err != nil {
return WrapError(err)
} else {
request["HostGroups"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
_, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if nraw != nil && len(nraw.(*schema.Set).List()) > 0 {
action = "AttachHostGroupAccountsToUser"
hostRequestMaps := make([]map[string]interface{}, 0)
hostRequestMap := make(map[string]interface{}, 0)
hostRequestMap["HostGroupId"] = parts[2]
hostRequestMap["HostAccountNames"] = nraw.(*schema.Set).List()
hostRequestMaps = append(hostRequestMaps, hostRequestMap)
if v, err := convertListMapToJsonString(hostRequestMaps); err != nil {
return WrapError(err)
} else {
request["HostGroups"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
_, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
}
return resourceAlicloudBastionhostHostGroupAccountUserAttachmentRead(d, meta)
}
func resourceAlicloudBastionhostHostGroupAccountUserAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
action := "DetachHostGroupAccountsFromUser"
var response map[string]interface{}
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"InstanceId": parts[0],
"UserId": parts[1],
}
request["RegionId"] = client.RegionId
hostRequestMaps := make([]map[string]interface{}, 0)
hostRequestMap := make(map[string]interface{}, 0)
hostRequestMap["HostGroupId"] = parts[2]
hostRequestMap["HostAccountNames"] = d.Get("host_account_names").(*schema.Set).List()
hostRequestMaps = append(hostRequestMaps, hostRequestMap)
if v, err := convertListMapToJsonString(hostRequestMaps); err != nil {
return WrapError(err)
} else {
request["HostGroups"] = v
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudBastionhostHostGroupAccountUserGroupAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudBastionhostHostGroupAccountUserGroupAttachmentCreate,
Read: resourceAlicloudBastionhostHostGroupAccountUserGroupAttachmentRead,
Update: resourceAlicloudBastionhostHostGroupAccountUserGroupAttachmentUpdate,
Delete: resourceAlicloudBastionhostHostGroupAccountUserGroupAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"host_account_names": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"host_group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"user_group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudBastionhostHostGroupAccountUserGroupAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
d.SetId(fmt.Sprint(d.Get("instance_id"), ":", d.Get("user_group_id"), ":", d.Get("host_group_id")))
return resourceAlicloudBastionhostHostGroupAccountUserGroupAttachmentUpdate(d, meta)
}
func resourceAlicloudBastionhostHostGroupAccountUserGroupAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
yundunBastionhostService := YundunBastionhostService{client}
object, err := yundunBastionhostService.DescribeBastionhostHostGroupAccountUserGroupAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_bastionhost_host_group_account_user_group_attachment yundunBastionhostService.DescribeBastionhostHostGroupAccountUserGroupAttachment Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
d.Set("host_group_id", parts[2])
d.Set("instance_id", parts[0])
d.Set("user_group_id", parts[1])
d.Set("host_account_names", object)
return nil
}
func resourceAlicloudBastionhostHostGroupAccountUserGroupAttachmentUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
if d.HasChange("host_account_names") {
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
action := "AttachHostGroupAccountsToUserGroup"
request := make(map[string]interface{})
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
oraw, nraw := d.GetChange("host_account_names")
request["InstanceId"] = parts[0]
request["RegionId"] = client.RegionId
request["UserGroupId"] = parts[1]
if oraw != nil && len(oraw.(*schema.Set).List()) > 0 {
action = "DetachHostGroupAccountsFromUserGroup"
hostRequestMaps := make([]map[string]interface{}, 0)
hostRequestMap := make(map[string]interface{}, 0)
hostRequestMap["HostGroupId"] = parts[2]
hostRequestMap["HostAccountNames"] = oraw.(*schema.Set).List()
hostRequestMaps = append(hostRequestMaps, hostRequestMap)
if v, err := convertListMapToJsonString(hostRequestMaps); err != nil {
return WrapError(err)
} else {
request["HostGroups"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
_, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if nraw != nil && len(nraw.(*schema.Set).List()) > 0 {
action = "AttachHostGroupAccountsToUserGroup"
hostRequestMaps := make([]map[string]interface{}, 0)
hostRequestMap := make(map[string]interface{}, 0)
hostRequestMap["HostGroupId"] = parts[2]
hostRequestMap["HostAccountNames"] = nraw.(*schema.Set).List()
hostRequestMaps = append(hostRequestMaps, hostRequestMap)
if v, err := convertListMapToJsonString(hostRequestMaps); err != nil {
return WrapError(err)
} else {
request["HostGroups"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
_, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
}
return resourceAlicloudBastionhostHostGroupAccountUserGroupAttachmentRead(d, meta)
}
func resourceAlicloudBastionhostHostGroupAccountUserGroupAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
action := "DetachHostGroupAccountsFromUserGroup"
var response map[string]interface{}
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"InstanceId": parts[0],
"UserGroupId": parts[1],
}
request["RegionId"] = client.RegionId
hostRequestMaps := make([]map[string]interface{}, 0)
hostRequestMap := make(map[string]interface{}, 0)
hostRequestMap["HostGroupId"] = parts[2]
hostRequestMap["HostAccountNames"] = d.Get("host_account_names").(*schema.Set).List()
hostRequestMaps = append(hostRequestMaps, hostRequestMap)
if v, err := convertListMapToJsonString(hostRequestMaps); err != nil {
return WrapError(err)
} else {
request["HostGroups"] = v
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"strconv"
"time"
log "github.com/sirupsen/logrus"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudBastionhostInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudBastionhostInstanceCreate,
Read: resourceAlicloudBastionhostInstanceRead,
Update: resourceAlicloudBastionhostInstanceUpdate,
Delete: resourceAlicloudBastionhostInstanceDelete,
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
Update: schema.DefaultTimeout(20 * time.Minute),
Delete: schema.DefaultTimeout(1 * time.Minute),
},
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(1, 64),
},
"license_code": {
Type: schema.TypeString,
Required: true,
},
"period": {
Type: schema.TypeInt,
ValidateFunc: validation.IntInSlice([]int{1, 3, 6, 12, 24, 36}),
Optional: true,
},
"vswitch_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"security_group_ids": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"tags": tagsSchema(),
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
},
"enable_public_access": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
},
}
}
func resourceAlicloudBastionhostInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateInstance"
request := make(map[string]interface{})
parameterMapList := make([]map[string]interface{}, 0)
conn, err := client.NewBssopenapiClient()
if err != nil {
return WrapError(err)
}
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "NetworkType",
"Value": "vpc",
})
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "LicenseCode",
"Value": d.Get("license_code").(string),
})
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "PlanCode",
"Value": "cloudbastion",
})
request["SubscriptionType"] = "Subscription"
if v, ok := d.GetOk("period"); ok {
request["Period"] = v
}
request["ProductCode"] = "bastionhost"
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "RegionId",
"Value": client.RegionId,
})
request["Parameter"] = parameterMapList
request["ClientToken"] = buildClientToken("CreateInstance")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-14"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"NotApplicable"}) {
conn.Endpoint = String(connectivity.BssOpenAPIEndpointInternational)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_bastionhost_instance", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
responseData := response["Data"].(map[string]interface{})
d.SetId(fmt.Sprint(responseData["InstanceId"]))
bastionhostService := YundunBastionhostService{client}
// check RAM policy
if err := bastionhostService.ProcessRolePolicy(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
// wait for order complete
stateConf := BuildStateConf([]string{}, []string{"PENDING"}, d.Timeout(schema.TimeoutCreate), 20*time.Second, bastionhostService.BastionhostInstanceRefreshFunc(d.Id(), []string{"UPGRADING", "UPGRADE_FAILED", "CREATE_FAILED"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
rawSecurityGroupIds := d.Get("security_group_ids").([]interface{})
securityGroupIds := make([]string, len(rawSecurityGroupIds))
for index, rawSecurityGroupId := range rawSecurityGroupIds {
securityGroupIds[index] = rawSecurityGroupId.(string)
}
// start instance
if err := bastionhostService.StartBastionhostInstance(d.Id(), d.Get("vswitch_id").(string), securityGroupIds); err != nil {
return WrapError(err)
}
// wait for pending
stateConf = BuildStateConf([]string{"PENDING", "CREATING"}, []string{"RUNNING"}, d.Timeout(schema.TimeoutCreate), 600*time.Second, bastionhostService.BastionhostInstanceRefreshFunc(d.Id(), []string{"UPGRADING", "UPGRADE_FAILED", "CREATE_FAILED"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudBastionhostInstanceUpdate(d, meta)
}
func resourceAlicloudBastionhostInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
BastionhostService := YundunBastionhostService{client}
instance, err := BastionhostService.DescribeBastionhostInstance(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", instance["Description"])
d.Set("license_code", instance["LicenseCode"])
d.Set("vswitch_id", instance["VswitchId"])
d.Set("security_group_ids", instance["AuthorizedSecurityGroups"])
d.Set("enable_public_access", instance["PublicNetworkAccess"])
tags, err := BastionhostService.DescribeTags(d.Id(), nil, TagResourceInstance)
if err != nil {
return WrapError(err)
}
d.Set("tags", BastionhostService.tagsToMap(tags))
return nil
}
func resourceAlicloudBastionhostInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
bastionhostService := YundunBastionhostService{client}
d.Partial(true)
if d.HasChange("tags") {
if err := bastionhostService.setInstanceTags(d, TagResourceInstance); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
if d.HasChange("description") {
if err := bastionhostService.UpdateBastionhostInstanceDescription(d.Id(), d.Get("description").(string)); err != nil {
return WrapError(err)
}
d.SetPartial("description")
}
if d.HasChange("resource_group_id") {
if err := bastionhostService.UpdateResourceGroup(d.Id(), d.Get("resource_group_id").(string)); err != nil {
return WrapError(err)
}
d.SetPartial("resource_group_id")
}
if !d.IsNewResource() && d.HasChange("license_code") {
params := map[string]string{
"LicenseCode": "license_code",
}
if err := bastionhostService.UpdateInstanceSpec(params, d, meta); err != nil {
return WrapError(err)
}
stateConf := BuildStateConf([]string{"UPGRADING"}, []string{"PENDING", "RUNNING"}, d.Timeout(schema.TimeoutUpdate), 20*time.Second, bastionhostService.BastionhostInstanceRefreshFunc(d.Id(), []string{"CREATING", "UPGRADE_FAILED", "CREATE_FAILED"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("license_code")
}
if !d.IsNewResource() && d.HasChange("security_group_ids") {
securityGroupIds := d.Get("security_group_ids").([]interface{})
sgs := make([]string, 0, len(securityGroupIds))
for _, rawSecurityGroupId := range securityGroupIds {
sgs = append(sgs, rawSecurityGroupId.(string))
}
if err := bastionhostService.UpdateBastionhostSecurityGroups(d.Id(), sgs); err != nil {
return WrapError(err)
}
stateConf := BuildStateConf([]string{"UPGRADING"}, []string{"RUNNING"}, d.Timeout(schema.TimeoutUpdate), 20*time.Second, bastionhostService.BastionhostInstanceRefreshFunc(d.Id(), []string{"CREATING", "UPGRADE_FAILED", "CREATE_FAILED"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("security_group_ids")
}
if d.HasChange("enable_public_access") {
client := meta.(*connectivity.AliyunClient)
BastionhostService := YundunBastionhostService{client}
instance, err := BastionhostService.DescribeBastionhostInstance(d.Id())
if err != nil {
return WrapError(err)
}
target := strconv.FormatBool(d.Get("enable_public_access").(bool))
if strconv.FormatBool(instance["PublicNetworkAccess"].(bool)) != target {
if target == "false" {
err := BastionhostService.DisableInstancePublicAccess(d.Id())
if err != nil {
return WrapError(err)
}
} else {
err := BastionhostService.EnableInstancePublicAccess(d.Id())
if err != nil {
return WrapError(err)
}
}
}
d.SetPartial("enable_public_access")
}
d.Partial(false)
// wait for order complete
return resourceAlicloudBastionhostInstanceRead(d, meta)
}
func resourceAlicloudBastionhostInstanceDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceBastionhostInstance. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudBastionhostUser() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudBastionhostUserCreate,
Read: resourceAlicloudBastionhostUserRead,
Update: resourceAlicloudBastionhostUserUpdate,
Delete: resourceAlicloudBastionhostUserDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"comment": {
Type: schema.TypeString,
Optional: true,
},
"display_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"email": {
Type: schema.TypeString,
Optional: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"mobile": {
Type: schema.TypeString,
Optional: true,
},
"mobile_country_code": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"AE", "AU", "CH", "CN", "DE", "GB", "HK", "ID", "IN", "JP", "KR", "MO", "MY", "PH", "RU", "SE", "SG", "TW", "US"}, false),
},
"password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"source": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Local", "Ram"}, false),
},
"source_user_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Frozen", "Normal"}, false),
},
"user_id": {
Type: schema.TypeString,
Computed: true,
},
"user_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudBastionhostUserCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateUser"
request := make(map[string]interface{})
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("comment"); ok {
request["Comment"] = v
}
if v, ok := d.GetOk("display_name"); ok {
request["DisplayName"] = v
}
if v, ok := d.GetOk("email"); ok {
request["Email"] = v
}
request["InstanceId"] = d.Get("instance_id")
if v, ok := d.GetOk("mobile"); ok {
request["Mobile"] = v
} else if v, ok := d.GetOk("mobile_country_code"); ok && v.(string) == "" {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is %v ", "mobile", "mobile_country_code", d.Get("mobile_country_code")))
}
if v, ok := d.GetOk("mobile_country_code"); ok {
request["MobileCountryCode"] = v
}
if v, ok := d.GetOk("password"); ok {
request["Password"] = v
} else if v, ok := d.GetOk("source"); ok && v.(string) == "Local" {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is %v ", "password", "source", d.Get("source")))
}
request["RegionId"] = client.RegionId
request["Source"] = d.Get("source")
if v, ok := d.GetOk("source_user_id"); ok {
request["SourceUserId"] = v
} else if v, ok := d.GetOk("source"); ok && v.(string) == "Ram" {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is %v ", "source_user_id", "source", d.Get("source")))
}
request["UserName"] = d.Get("user_name")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_bastionhost_user", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["InstanceId"], ":", response["UserId"]))
return resourceAlicloudBastionhostUserUpdate(d, meta)
}
func resourceAlicloudBastionhostUserRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
yundunBastionhostService := YundunBastionhostService{client}
object, err := yundunBastionhostService.DescribeBastionhostUser(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_bastionhost_user yundunBastionhostService.DescribeBastionhostUser Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("instance_id", parts[0])
d.Set("user_id", parts[1])
d.Set("comment", object["Comment"])
d.Set("display_name", object["DisplayName"])
d.Set("email", object["Email"])
d.Set("mobile", object["Mobile"])
d.Set("mobile_country_code", object["MobileCountryCode"])
d.Set("source", object["Source"])
d.Set("source_user_id", object["SourceUserId"])
d.Set("status", convertArrayToString(object["UserState"], ""))
d.Set("user_name", object["UserName"])
return nil
}
func resourceAlicloudBastionhostUserUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
yundunBastionhostService := YundunBastionhostService{client}
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Partial(true)
update := false
request := map[string]interface{}{
"InstanceId": parts[0],
"UserId": parts[1],
}
if !d.IsNewResource() && d.HasChange("comment") {
update = true
if v, ok := d.GetOk("comment"); ok {
request["Comment"] = v
}
}
if !d.IsNewResource() && d.HasChange("display_name") {
update = true
if v, ok := d.GetOk("display_name"); ok {
request["DisplayName"] = v
}
}
if !d.IsNewResource() && d.HasChange("email") {
update = true
if v, ok := d.GetOk("email"); ok {
request["Email"] = v
}
}
if !d.IsNewResource() && d.HasChange("mobile") {
update = true
if v, ok := d.GetOk("mobile"); ok {
request["Mobile"] = v
} else if v, ok := d.GetOk("mobile_country_code"); ok && v.(string) == "" {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is %v ", "mobile", "mobile_country_code", d.Get("mobile_country_code")))
}
request["MobileCountryCode"] = d.Get("mobile_country_code")
}
if !d.IsNewResource() && d.HasChange("mobile_country_code") {
update = true
if v, ok := d.GetOk("mobile_country_code"); ok {
request["MobileCountryCode"] = v
}
}
if !d.IsNewResource() && d.HasChange("password") {
update = true
if v, ok := d.GetOk("password"); ok {
request["Password"] = v
} else if v, ok := d.GetOk("source"); ok && v.(string) == "Local" {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is %v ", "password", "source", d.Get("source")))
}
}
request["RegionId"] = client.RegionId
if update {
action := "ModifyUser"
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("comment")
d.SetPartial("display_name")
d.SetPartial("email")
d.SetPartial("mobile")
d.SetPartial("mobile_country_code")
d.SetPartial("password")
}
if d.HasChange("status") {
object, err := yundunBastionhostService.DescribeBastionhostUser(d.Id())
if err != nil {
return WrapError(err)
}
target := d.Get("status").(string)
if convertArrayToString(object["UserState"], "") != target {
if target == "Frozen" {
request := map[string]interface{}{
"InstanceId": parts[0],
"UserIds": convertListToJsonString([]interface{}{parts[1]}),
}
request["RegionId"] = client.RegionId
action := "LockUsers"
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if target == "Normal" {
request := map[string]interface{}{
"InstanceId": parts[0],
"UserIds": convertListToJsonString([]interface{}{parts[1]}),
}
request["RegionId"] = client.RegionId
action := "UnlockUsers"
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("status")
}
}
d.Partial(false)
return resourceAlicloudBastionhostUserRead(d, meta)
}
func resourceAlicloudBastionhostUserDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteUser"
var response map[string]interface{}
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"InstanceId": parts[0],
"UserId": parts[1],
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"OBJECT_NOT_FOUND"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudBastionhostUserAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudBastionhostUserAttachmentCreate,
Read: resourceAlicloudBastionhostUserAttachmentRead,
Delete: resourceAlicloudBastionhostUserAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"user_group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"user_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudBastionhostUserAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AddUsersToGroup"
request := make(map[string]interface{})
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
request["InstanceId"] = d.Get("instance_id")
request["RegionId"] = client.RegionId
request["UserGroupId"] = d.Get("user_group_id")
request["UserIds"] = convertListToJsonString([]interface{}{d.Get("user_id")})
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_bastionhost_user_attachment", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["InstanceId"], ":", request["UserGroupId"], ":", d.Get("user_id")))
return resourceAlicloudBastionhostUserAttachmentRead(d, meta)
}
func resourceAlicloudBastionhostUserAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
yundunBastionhostService := YundunBastionhostService{client}
_, err := yundunBastionhostService.DescribeBastionhostUserAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_bastionhost_user_attachment yundunBastionhostService.DescribeBastionhostUserAttachment Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
d.Set("instance_id", parts[0])
d.Set("user_group_id", parts[1])
d.Set("user_id", parts[2])
return nil
}
func resourceAlicloudBastionhostUserAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
action := "RemoveUsersFromGroup"
var response map[string]interface{}
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"InstanceId": parts[0],
"UserGroupId": parts[1],
"UserIds": convertListToJsonString([]interface{}{parts[2]}),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Commodity.BizError.InvalidStatus", "OBJECT_NOT_FOUND"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudBastionhostUserGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudBastionhostUserGroupCreate,
Read: resourceAlicloudBastionhostUserGroupRead,
Update: resourceAlicloudBastionhostUserGroupUpdate,
Delete: resourceAlicloudBastionhostUserGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"comment": {
Type: schema.TypeString,
Optional: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"user_group_id": {
Type: schema.TypeString,
Computed: true,
},
"user_group_name": {
Type: schema.TypeString,
Required: true,
},
},
}
}
func resourceAlicloudBastionhostUserGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateUserGroup"
request := make(map[string]interface{})
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("comment"); ok {
request["Comment"] = v
}
request["InstanceId"] = d.Get("instance_id")
request["RegionId"] = client.RegionId
request["UserGroupName"] = d.Get("user_group_name")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_bastionhost_user_group", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["InstanceId"], ":", response["UserGroupId"]))
return resourceAlicloudBastionhostUserGroupRead(d, meta)
}
func resourceAlicloudBastionhostUserGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
yundunBastionhostService := YundunBastionhostService{client}
object, err := yundunBastionhostService.DescribeBastionhostUserGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_bastionhost_user_group yundunBastionhostService.DescribeBastionhostUserGroup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("instance_id", parts[0])
d.Set("user_group_id", parts[1])
d.Set("comment", object["Comment"])
d.Set("user_group_name", object["UserGroupName"])
return nil
}
func resourceAlicloudBastionhostUserGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"InstanceId": parts[0],
"UserGroupId": parts[1],
}
if d.HasChange("comment") {
update = true
if v, ok := d.GetOk("comment"); ok {
request["Comment"] = v
}
}
request["RegionId"] = client.RegionId
if d.HasChange("user_group_name") {
update = true
request["UserGroupName"] = d.Get("user_group_name")
}
if update {
action := "ModifyUserGroup"
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudBastionhostUserGroupRead(d, meta)
}
func resourceAlicloudBastionhostUserGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteUserGroup"
var response map[string]interface{}
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"InstanceId": parts[0],
"UserGroupId": parts[1],
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"OBJECT_NOT_FOUND"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudBrainIndustrialPidLoop() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudBrainIndustrialPidLoopCreate,
Read: resourceAlicloudBrainIndustrialPidLoopRead,
Update: resourceAlicloudBrainIndustrialPidLoopUpdate,
Delete: resourceAlicloudBrainIndustrialPidLoopDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"pid_loop_configuration": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.ValidateJsonString,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
equal, _ := compareJsonTemplateAreEquivalent(old, new)
return equal
},
},
"pid_loop_dcs_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"standard"}, false),
},
"pid_loop_desc": {
Type: schema.TypeString,
Optional: true,
},
"pid_loop_is_crucial": {
Type: schema.TypeBool,
Required: true,
},
"pid_loop_name": {
Type: schema.TypeString,
Required: true,
},
"pid_loop_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"0", "1", "2", "3", "4", "5"}, false),
},
"pid_project_id": {
Type: schema.TypeString,
Required: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudBrainIndustrialPidLoopCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreatePidLoop"
request := make(map[string]interface{})
conn, err := client.NewAistudioClient()
if err != nil {
return WrapError(err)
}
request["PidLoopConfiguration"] = d.Get("pid_loop_configuration")
request["PidLoopDcsType"] = d.Get("pid_loop_dcs_type")
if v, ok := d.GetOk("pid_loop_desc"); ok {
request["PidLoopDesc"] = v
}
request["IsCrucialPidLoop"] = d.Get("pid_loop_is_crucial")
request["PidLoopName"] = d.Get("pid_loop_name")
request["PidLoopType"] = d.Get("pid_loop_type")
request["PidProjectId"] = d.Get("pid_project_id")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("CreatePidLoop")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_brain_industrial_pid_loop", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
return WrapError(Error("CreatePidLoop failed for " + response["Message"].(string)))
}
d.SetId(fmt.Sprint(response["PidLoopId"]))
return resourceAlicloudBrainIndustrialPidLoopRead(d, meta)
}
func resourceAlicloudBrainIndustrialPidLoopRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
brain_industrialService := Brain_industrialService{client}
object, err := brain_industrialService.DescribeBrainIndustrialPidLoop(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_brain_industrial_pid_loop brain_industrialService.DescribeBrainIndustrialPidLoop Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("pid_loop_configuration", object["PidLoopConfiguration"])
d.Set("pid_loop_dcs_type", object["PidLoopDcsType"])
d.Set("pid_loop_desc", object["PidLoopDesc"])
d.Set("pid_loop_is_crucial", object["PidLoopIsCrucial"])
d.Set("pid_loop_name", object["PidLoopName"])
d.Set("pid_loop_type", object["PidLoopType"])
d.Set("pid_project_id", object["PidProjectId"])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudBrainIndustrialPidLoopUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"PidLoopId": d.Id(),
}
if d.HasChange("pid_loop_configuration") {
update = true
}
request["PidLoopConfiguration"] = d.Get("pid_loop_configuration")
if d.HasChange("pid_loop_dcs_type") {
update = true
}
request["PidLoopDcsType"] = d.Get("pid_loop_dcs_type")
if d.HasChange("pid_loop_is_crucial") {
update = true
}
request["Crucial"] = d.Get("pid_loop_is_crucial")
if d.HasChange("pid_loop_name") {
update = true
}
request["PidLoopName"] = d.Get("pid_loop_name")
if d.HasChange("pid_loop_type") {
update = true
}
request["PidLoopType"] = d.Get("pid_loop_type")
if d.HasChange("pid_project_id") {
update = true
}
request["PidProjectId"] = d.Get("pid_project_id")
if d.HasChange("pid_loop_desc") {
update = true
request["PidLoopDesc"] = d.Get("pid_loop_desc")
}
if update {
action := "UpdatePidLoop"
conn, err := client.NewAistudioClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
return WrapError(Error("UpdatePidLoop failed for " + response["Message"].(string)))
}
}
return resourceAlicloudBrainIndustrialPidLoopRead(d, meta)
}
func resourceAlicloudBrainIndustrialPidLoopDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeletePidLoop"
var response map[string]interface{}
conn, err := client.NewAistudioClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"PidLoopId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
return WrapError(Error("DeletePidLoop failed for " + response["Message"].(string)))
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudBrainIndustrialPidOrganization() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudBrainIndustrialPidOrganizationCreate,
Read: resourceAlicloudBrainIndustrialPidOrganizationRead,
Update: resourceAlicloudBrainIndustrialPidOrganizationUpdate,
Delete: resourceAlicloudBrainIndustrialPidOrganizationDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"parent_pid_organization_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"pid_organization_name": {
Type: schema.TypeString,
Required: true,
},
},
}
}
func resourceAlicloudBrainIndustrialPidOrganizationCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreatePidOrganization"
request := make(map[string]interface{})
conn, err := client.NewAistudioClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("parent_pid_organization_id"); ok {
request["ParentOrganizationId"] = v
}
request["OrganizationName"] = d.Get("pid_organization_name")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("CreatePidOrganization")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_brain_industrial_pid_organization", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
return WrapError(Error("CreatePidOrganization failed for " + response["Message"].(string)))
}
d.SetId(fmt.Sprint(response["OrganizationId"]))
return resourceAlicloudBrainIndustrialPidOrganizationRead(d, meta)
}
func resourceAlicloudBrainIndustrialPidOrganizationRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
brain_industrialService := Brain_industrialService{client}
object, err := brain_industrialService.DescribeBrainIndustrialPidOrganization(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_brain_industrial_pid_organization brain_industrialService.DescribeBrainIndustrialPidOrganization Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("pid_organization_name", object["OrganizationName"])
return nil
}
func resourceAlicloudBrainIndustrialPidOrganizationUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
if d.HasChange("pid_organization_name") {
request := map[string]interface{}{
"OrganizationId": d.Id(),
}
request["OrganizationName"] = d.Get("pid_organization_name")
action := "UpdatePidOrganization"
conn, err := client.NewAistudioClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
return WrapError(Error("UpdatePidOrganization failed for " + response["Message"].(string)))
}
}
return resourceAlicloudBrainIndustrialPidOrganizationRead(d, meta)
}
func resourceAlicloudBrainIndustrialPidOrganizationDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeletePidOrganization"
var response map[string]interface{}
conn, err := client.NewAistudioClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"OrganizationId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
return WrapError(Error("DeletePidOrganization failed for " + response["Message"].(string)))
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudBrainIndustrialPidProject() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudBrainIndustrialPidProjectCreate,
Read: resourceAlicloudBrainIndustrialPidProjectRead,
Update: resourceAlicloudBrainIndustrialPidProjectUpdate,
Delete: resourceAlicloudBrainIndustrialPidProjectDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"pid_organization_id": {
Type: schema.TypeString,
Required: true,
},
"pid_project_desc": {
Type: schema.TypeString,
Optional: true,
},
"pid_project_name": {
Type: schema.TypeString,
Required: true,
},
},
}
}
func resourceAlicloudBrainIndustrialPidProjectCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreatePidProject"
request := make(map[string]interface{})
conn, err := client.NewAistudioClient()
if err != nil {
return WrapError(err)
}
request["PidOrganisationId"] = d.Get("pid_organization_id")
if v, ok := d.GetOk("pid_project_desc"); ok {
request["PidProjectDesc"] = v
}
request["PidProjectName"] = d.Get("pid_project_name")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("CreatePidProject")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_brain_industrial_pid_project", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
return WrapError(Error("CreatePidProject failed for " + response["Message"].(string)))
}
d.SetId(fmt.Sprint(response["PidProjectId"]))
return resourceAlicloudBrainIndustrialPidProjectRead(d, meta)
}
func resourceAlicloudBrainIndustrialPidProjectRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
brain_industrialService := Brain_industrialService{client}
object, err := brain_industrialService.DescribeBrainIndustrialPidProject(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_brain_industrial_pid_project brain_industrialService.DescribeBrainIndustrialPidProject Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("pid_organization_id", object["PidOrganisationId"])
d.Set("pid_project_desc", object["PidProjectDesc"])
d.Set("pid_project_name", object["PidProjectName"])
return nil
}
func resourceAlicloudBrainIndustrialPidProjectUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"PidProjectId": d.Id(),
}
if d.HasChange("pid_organization_id") {
update = true
}
request["PidOrganisationId"] = d.Get("pid_organization_id")
if d.HasChange("pid_project_desc") {
update = true
request["PidProjectDesc"] = d.Get("pid_project_desc")
}
if d.HasChange("pid_project_name") {
update = true
request["PidProjectName"] = d.Get("pid_project_name")
}
if update {
action := "UpdatePidProject"
conn, err := client.NewAistudioClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
return WrapError(Error("UpdatePidProject failed for " + response["Message"].(string)))
}
}
return resourceAlicloudBrainIndustrialPidProjectRead(d, meta)
}
func resourceAlicloudBrainIndustrialPidProjectDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeletePidProject"
var response map[string]interface{}
conn, err := client.NewAistudioClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"PidProjectId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
return WrapError(Error("DeletePidProject failed for " + response["Message"].(string)))
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCassandraBackupPlan() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCassandraBackupPlanCreate,
Read: resourceAlicloudCassandraBackupPlanRead,
Update: resourceAlicloudCassandraBackupPlanUpdate,
Delete: resourceAlicloudCassandraBackupPlanDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"active": {
Type: schema.TypeBool,
Computed: true,
Optional: true,
},
"backup_period": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"backup_time": {
Type: schema.TypeString,
Required: true,
},
"cluster_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"data_center_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"retention_period": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(1, 30),
},
},
}
}
func resourceAlicloudCassandraBackupPlanCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateBackupPlan"
request := make(map[string]interface{})
conn, err := client.NewCdsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("active"); ok {
request["Active"] = v
}
if v, ok := d.GetOk("backup_period"); ok {
request["BackupPeriod"] = v
}
request["BackupTime"] = d.Get("backup_time")
request["ClusterId"] = d.Get("cluster_id")
request["DataCenterId"] = d.Get("data_center_id")
if v, ok := d.GetOk("retention_period"); ok {
request["RetentionPeriod"] = v
}
request["ClientToken"] = buildClientToken("CreateBackupPlan")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cassandra_backup_plan", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["ClusterId"], ":", request["DataCenterId"]))
return resourceAlicloudCassandraBackupPlanRead(d, meta)
}
func resourceAlicloudCassandraBackupPlanRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cassandraService := CassandraService{client}
object, err := cassandraService.DescribeCassandraBackupPlan(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cassandra_backup_plan cassandraService.DescribeCassandraBackupPlan Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("cluster_id", parts[0])
d.Set("data_center_id", parts[1])
d.Set("active", object["Active"])
d.Set("backup_period", object["BackupPeriod"])
d.Set("backup_time", object["BackupTime"])
d.Set("retention_period", formatInt(object["RetentionPeriod"]))
return nil
}
func resourceAlicloudCassandraBackupPlanUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"ClusterId": parts[0],
"DataCenterId": parts[1],
}
if d.HasChange("backup_time") {
update = true
}
request["BackupTime"] = d.Get("backup_time")
if d.HasChange("active") || d.IsNewResource() {
update = true
request["Active"] = d.Get("active")
}
if d.HasChange("backup_period") {
update = true
request["BackupPeriod"] = d.Get("backup_period")
}
if d.HasChange("retention_period") {
update = true
request["RetentionPeriod"] = d.Get("retention_period")
}
if update {
action := "ModifyBackupPlan"
conn, err := client.NewCdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudCassandraBackupPlanRead(d, meta)
}
func resourceAlicloudCassandraBackupPlanDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteBackupPlan"
var response map[string]interface{}
conn, err := client.NewCdsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ClusterId": parts[0],
"DataCenterId": parts[1],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cassandra"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCassandraCluster() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCassandraClusterCreate,
Read: resourceAlicloudCassandraClusterRead,
Update: resourceAlicloudCassandraClusterUpdate,
Delete: resourceAlicloudCassandraClusterDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
Update: schema.DefaultTimeout(30 * time.Minute),
Delete: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"auto_renew": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: false,
},
"auto_renew_period": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 6, 12}),
},
"cluster_name": {
Type: schema.TypeString,
Optional: true,
},
"data_center_name": {
Type: schema.TypeString,
Optional: true,
},
"disk_size": {
Type: schema.TypeInt,
Optional: true,
},
"disk_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"instance_type": {
Type: schema.TypeString,
Required: true,
},
"maintain_end_time": {
Type: schema.TypeString,
Optional: true,
},
"maintain_start_time": {
Type: schema.TypeString,
Optional: true,
},
"major_version": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"node_count": {
Type: schema.TypeInt,
Required: true,
},
"password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"pay_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"period": {
Type: schema.TypeInt,
Optional: true,
},
"period_unit": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"enable_public": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"public_points": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"ip_white": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"security_groups": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"tags": tagsSchema(),
},
}
}
func resourceAlicloudCassandraClusterCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cassandraService := CassandraService{client}
request := cassandra.CreateCreateClusterRequest()
if v, ok := d.GetOkExists("auto_renew"); ok {
request.AutoRenew = requests.NewBoolean(v.(bool))
}
if v, ok := d.GetOk("auto_renew_period"); ok {
request.AutoRenewPeriod = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("cluster_name"); ok {
request.ClusterName = v.(string)
}
if v, ok := d.GetOk("data_center_name"); ok {
request.DataCenterName = v.(string)
}
if v, ok := d.GetOk("disk_size"); ok {
request.DiskSize = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("disk_type"); ok {
request.DiskType = v.(string)
}
request.InstanceType = d.Get("instance_type").(string)
request.MajorVersion = d.Get("major_version").(string)
request.NodeCount = requests.NewInteger(d.Get("node_count").(int))
if v, ok := d.GetOk("password"); ok {
request.Password = v.(string)
}
request.PayType = d.Get("pay_type").(string)
if v, ok := d.GetOk("period"); ok {
request.Period = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("period_unit"); ok {
request.PeriodUnit = v.(string)
}
request.RegionId = client.RegionId
request.VswitchId = d.Get("vswitch_id").(string)
request.ZoneId = d.Get("zone_id").(string)
vswitchId := Trim(d.Get("vswitch_id").(string))
if vswitchId != "" {
vpcService := VpcService{client}
request.VswitchId = vswitchId
// check vswitchId in zone
vsw, err := vpcService.DescribeVSwitch(vswitchId)
if err != nil {
return WrapError(err)
}
if request.ZoneId == "" {
request.ZoneId = vsw.ZoneId
}
request.VpcId = vsw.VpcId
}
raw, err := client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.CreateCluster(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cassandra_cluster", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ := raw.(*cassandra.CreateClusterResponse)
d.SetId(fmt.Sprintf("%v", response.ClusterId))
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 8*time.Minute, cassandraService.CassandraClusterStateRefreshFunc(d.Id(), []string{"CreateFailed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudCassandraClusterUpdate(d, meta)
}
func resourceAlicloudCassandraClusterRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cassandraService := CassandraService{client}
object, err := cassandraService.DescribeCassandraCluster(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cassandra_cluster cassandraService.DescribeCassandraCluster Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("id", object.ClusterId)
d.Set("cluster_name", object.ClusterName)
d.Set("maintain_end_time", object.MaintainEndTime)
d.Set("maintain_start_time", object.MaintainStartTime)
d.Set("major_version", object.MajorVersion)
d.Set("pay_type", object.PayType)
d.Set("status", object.Status)
d.Set("tags", cassandraService.tagsToMap(object.Tags.Tag))
firstDc, err := cassandraService.DescribeClusterDataCenter(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("zone_id", firstDc.ZoneId)
d.Set("vswitch_id", firstDc.VswitchId)
d.Set("data_center_name", firstDc.DataCenterName)
d.Set("data_center_id", firstDc.DataCenterId)
d.Set("disk_type", firstDc.DiskType)
d.Set("disk_size", firstDc.DiskSize)
d.Set("instance_type", firstDc.InstanceType)
d.Set("node_count", firstDc.NodeCount)
d.Set("auto_renew", firstDc.AutoRenewal)
if d.Get("auto_renew").(bool) {
d.Set("auto_renew_period", firstDc.AutoRenewPeriod)
} else {
if v, ok := d.GetOkExists("auto_renew_period"); ok {
d.Set("auto_renew_period", v.(int))
}
}
d.Set("enable_public", false)
d.Set("public_points", nil)
d.Set("security_groups", nil)
ipWhitelist, err := cassandraService.DescribeIpWhitelist(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("ip_white", strings.Join(ipWhitelist.IpList.IP, ","))
securityGroups, err := cassandraService.DescribeSecurityGroups(d.Id())
if err != nil {
return WrapError(err)
}
if len(securityGroups.SecurityGroupIds.SecurityGroupId) > 0 {
d.Set("security_groups", securityGroups.SecurityGroupIds.SecurityGroupId)
}
endPoints, err := cassandraService.DescribeCassandraEndpoints(d.Id())
if err != nil {
return WrapError(err)
}
for _, contactPoint := range endPoints.ContactPoints.ContactPoint {
if d.Get("zone_id").(string) == contactPoint.DataCenterId && len(contactPoint.PublicAddresses.PublicAddress) > 0 {
d.Set("enable_public", true)
d.Set("public_points", contactPoint.PublicAddresses.PublicAddress)
break
}
}
return nil
}
func resourceAlicloudCassandraClusterUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cassandraService := CassandraService{client}
d.Partial(true)
if err := cassandraService.setInstanceTags(d); err != nil {
return WrapError(err)
}
if d.HasChange("ip_white") {
modifyIpWhitelistGroupReq := cassandra.CreateModifyIpWhitelistGroupRequest()
modifyIpWhitelistGroupReq.ClusterId = d.Id()
modifyIpWhitelistGroupReq.IpList = d.Get("ip_white").(string)
modifyIpWhitelistGroupReq.GroupName = "default"
modifyIpWhitelistGroupReq.IpVersion = "4"
raw, err := client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.ModifyIpWhitelistGroup(modifyIpWhitelistGroupReq)
})
addDebug(modifyIpWhitelistGroupReq.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), modifyIpWhitelistGroupReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("ip_white")
}
if d.HasChange("security_groups") {
modifySecurityGroupsReq := cassandra.CreateModifySecurityGroupsRequest()
modifySecurityGroupsReq.ClusterId = d.Id()
securityGroups := d.Get("security_groups").([]interface{})
if securityGroups != nil && len(securityGroups) > 0 {
security_groups := strings.Join(expandStringList(securityGroups), ",")
modifySecurityGroupsReq.SecurityGroupIds = security_groups
} else {
modifySecurityGroupsReq.SecurityGroupIds = " "
}
raw, err := client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.ModifySecurityGroups(modifySecurityGroupsReq)
})
addDebug(modifySecurityGroupsReq.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), modifySecurityGroupsReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, cassandraService.CassandraClusterStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("security_groups")
}
if d.HasChange("enable_public") {
if d.Get("enable_public").(bool) {
request := cassandra.CreateAllocatePublicContactPointsRequest()
request.ClusterId = d.Id()
request.DataCenterId = d.Get("zone_id").(string)
raw, err := client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.AllocatePublicContactPoints(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, cassandraService.CassandraClusterStateRefreshFunc(d.Id(), []string{"AllocatePubConnFailed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
} else {
request := cassandra.CreateReleasePublicContactPointsRequest()
request.ClusterId = d.Id()
request.DataCenterId = d.Get("zone_id").(string)
raw, err := client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.ReleasePublicContactPoints(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, cassandraService.CassandraClusterStateRefreshFunc(d.Id(), []string{"ReleasePubConnFailed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.SetPartial("enable_public")
}
if (d.HasChange("maintain_end_time") || d.HasChange("maintain_start_time")) && d.Get("maintain_end_time").(string) != "" && d.Get("maintain_start_time").(string) != "" {
modifyInstanceMaintainTimeReq := cassandra.CreateModifyInstanceMaintainTimeRequest()
modifyInstanceMaintainTimeReq.ClusterId = d.Id()
modifyInstanceMaintainTimeReq.MaintainEndTime = d.Get("maintain_end_time").(string)
modifyInstanceMaintainTimeReq.MaintainStartTime = d.Get("maintain_start_time").(string)
raw, err := client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.ModifyInstanceMaintainTime(modifyInstanceMaintainTimeReq)
})
addDebug(modifyInstanceMaintainTimeReq.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), modifyInstanceMaintainTimeReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("maintain_end_time")
d.SetPartial("maintain_start_time")
}
if d.IsNewResource() {
d.Partial(false)
return resourceAlicloudCassandraClusterRead(d, meta)
}
if d.HasChange("cluster_name") {
request := cassandra.CreateModifyClusterRequest()
request.ClusterId = d.Id()
request.ClusterName = d.Get("cluster_name").(string)
raw, err := client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.ModifyCluster(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("cluster_name")
}
if d.HasChange("data_center_name") {
request := cassandra.CreateModifyDataCenterRequest()
request.ClusterId = d.Id()
request.DataCenterId = d.Get("zone_id").(string)
request.DataCenterName = d.Get("data_center_name").(string)
raw, err := client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.ModifyDataCenter(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("data_center_name")
}
update := false
modifyInstanceTypeReq := cassandra.CreateModifyInstanceTypeRequest()
modifyInstanceTypeReq.ClusterId = d.Id()
if d.HasChange("instance_type") {
update = true
}
modifyInstanceTypeReq.InstanceType = d.Get("instance_type").(string)
modifyInstanceTypeReq.DataCenterId = d.Get("zone_id").(string)
if update {
raw, err := client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.ModifyInstanceType(modifyInstanceTypeReq)
})
addDebug(modifyInstanceTypeReq.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), modifyInstanceTypeReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, cassandraService.CassandraClusterStateRefreshFunc(d.Id(), []string{"ModifyInstanceTypeFailed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("instance_type")
}
update = false
resizeDiskSizeReq := cassandra.CreateResizeDiskSizeRequest()
resizeDiskSizeReq.ClusterId = d.Id()
if d.HasChange("disk_size") {
update = true
}
resizeDiskSizeReq.DiskSize = requests.NewInteger(d.Get("disk_size").(int))
resizeDiskSizeReq.DataCenterId = d.Get("zone_id").(string)
if update {
raw, err := client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.ResizeDiskSize(resizeDiskSizeReq)
})
addDebug(resizeDiskSizeReq.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), resizeDiskSizeReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, cassandraService.CassandraClusterStateRefreshFunc(d.Id(), []string{"ResizeDiskSizeFailed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("disk_size")
}
update = false
resizeNodeCountReq := cassandra.CreateResizeNodeCountRequest()
resizeNodeCountReq.ClusterId = d.Id()
if d.HasChange("node_count") {
update = true
}
resizeNodeCountReq.NodeCount = requests.NewInteger(d.Get("node_count").(int))
resizeNodeCountReq.DataCenterId = d.Get("zone_id").(string)
if update {
raw, err := client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.ResizeNodeCount(resizeNodeCountReq)
})
addDebug(resizeNodeCountReq.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), resizeNodeCountReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, cassandraService.CassandraClusterStateRefreshFunc(d.Id(), []string{"ResizeNodeCountFailed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("node_count")
}
if d.HasChange("password") {
request := cassandra.CreateModifyAccountPasswordRequest()
request.ClusterId = d.Id()
request.Account = "cassandra"
request.Password = d.Get("password").(string)
raw, err := client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.ModifyAccountPassword(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("password")
}
d.Partial(false)
return resourceAlicloudCassandraClusterRead(d, meta)
}
func resourceAlicloudCassandraClusterDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cassandra.CreateDeleteClusterRequest()
request.ClusterId = d.Id()
raw, err := client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.DeleteCluster(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
if IsExpectedErrors(err, []string{"Cluster.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
cassandraService := CassandraService{client}
stateConf := BuildStateConf([]string{"Deleting"}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, cassandraService.CassandraClusterStateRefreshFunc(d.Id(), []string{"DeleteFailed"}))
_, err = stateConf.WaitForState()
return WrapError(err)
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cassandra"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCassandraDataCenter() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCassandraDataCenterCreate,
Read: resourceAlicloudCassandraDataCenterRead,
Update: resourceAlicloudCassandraDataCenterUpdate,
Delete: resourceAlicloudCassandraDataCenterDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
Update: schema.DefaultTimeout(30 * time.Minute),
Delete: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"auto_renew": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: false,
},
"auto_renew_period": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 4, 5, 6, 12}),
},
"cluster_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"data_center_id": {
Type: schema.TypeString,
Computed: true,
ForceNew: true,
},
"data_center_name": {
Type: schema.TypeString,
Optional: true,
},
"disk_size": {
Type: schema.TypeInt,
Optional: true,
},
"disk_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"instance_type": {
Type: schema.TypeString,
Required: true,
},
"node_count": {
Type: schema.TypeInt,
Required: true,
},
"pay_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"period": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 24, 36}),
},
"period_unit": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"enable_public": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"public_points": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
}
}
func resourceAlicloudCassandraDataCenterCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cassandraService := CassandraService{client}
request := cassandra.CreateCreateDataCenterRequest()
if v, ok := d.GetOkExists("auto_renew"); ok {
request.AutoRenew = requests.NewBoolean(v.(bool))
}
if v, ok := d.GetOk("auto_renew_period"); ok {
request.AutoRenewPeriod = requests.NewInteger(v.(int))
}
request.ClusterId = d.Get("cluster_id").(string)
if v, ok := d.GetOk("data_center_name"); ok {
request.DataCenterName = v.(string)
}
if v, ok := d.GetOk("disk_size"); ok {
request.DiskSize = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("disk_type"); ok {
request.DiskType = v.(string)
}
request.InstanceType = d.Get("instance_type").(string)
request.NodeCount = requests.NewInteger(d.Get("node_count").(int))
request.PayType = d.Get("pay_type").(string)
if v, ok := d.GetOk("period"); ok {
request.Period = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("period_unit"); ok {
request.PeriodUnit = v.(string)
}
request.RegionId = client.RegionId
request.VswitchId = d.Get("vswitch_id").(string)
request.ZoneId = d.Get("zone_id").(string)
vswitchId := Trim(d.Get("vswitch_id").(string))
if vswitchId != "" {
vpcService := VpcService{client}
request.VswitchId = vswitchId
// check vswitchId in zone
vsw, err := vpcService.DescribeVSwitch(vswitchId)
if err != nil {
return WrapError(err)
}
if request.ZoneId == "" {
request.ZoneId = vsw.ZoneId
}
request.VpcId = vsw.VpcId
}
raw, err := client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.CreateDataCenter(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cassandra_data_center", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ := raw.(*cassandra.CreateDataCenterResponse)
d.SetId(fmt.Sprintf("%v:%v", response.DataCenterId, request.ClusterId))
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 8*time.Minute, cassandraService.CassandraDataCenterStateRefreshFunc(d.Id(), []string{"CreateFailed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudCassandraDataCenterUpdate(d, meta)
}
func resourceAlicloudCassandraDataCenterRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cassandraService := CassandraService{client}
object, err := cassandraService.DescribeCassandraDataCenter(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cassandra_data_center cassandraService.DescribeCassandraDataCenter Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("id", fmt.Sprintf("%v:%v", object.DataCenterId, object.ClusterId))
d.Set("cluster_id", object.ClusterId)
d.Set("data_center_id", object.DataCenterId)
d.Set("data_center_name", object.DataCenterName)
d.Set("disk_size", object.DiskSize)
d.Set("disk_type", object.DiskType)
d.Set("instance_type", object.InstanceType)
d.Set("node_count", object.NodeCount)
d.Set("pay_type", object.PayType)
d.Set("status", object.Status)
d.Set("vswitch_id", object.VswitchId)
d.Set("zone_id", object.ZoneId)
d.Set("auto_renew", object.AutoRenewal)
if d.Get("auto_renew").(bool) {
d.Set("auto_renew_period", object.AutoRenewPeriod)
} else {
if v, ok := d.GetOkExists("auto_renew_period"); ok {
d.Set("auto_renew_period", v.(int))
}
}
d.Set("enable_public", false)
d.Set("public_points", nil)
endPoints, err := cassandraService.DescribeCassandraEndpoints(d.Id())
if err != nil {
return WrapError(err)
}
for _, contactPoint := range endPoints.ContactPoints.ContactPoint {
if object.ZoneId == contactPoint.DataCenterId && len(contactPoint.PublicAddresses.PublicAddress) > 0 {
d.Set("enable_public", true)
d.Set("public_points", contactPoint.PublicAddresses.PublicAddress)
break
}
}
return nil
}
func resourceAlicloudCassandraDataCenterUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cassandraService := CassandraService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Partial(true)
if (d.IsNewResource() && d.Get("enable_public") != nil && d.Get("enable_public").(bool)) || (!d.IsNewResource() && d.HasChange("enable_public")) {
if d.Get("enable_public").(bool) {
request := cassandra.CreateAllocatePublicContactPointsRequest()
request.ClusterId = parts[1]
request.DataCenterId = parts[0]
raw, err := client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.AllocatePublicContactPoints(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, cassandraService.CassandraDataCenterStateRefreshFunc(d.Id(), []string{"AllocatePubConnFailed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
} else {
request := cassandra.CreateReleasePublicContactPointsRequest()
request.ClusterId = parts[1]
request.DataCenterId = parts[0]
raw, err := client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.ReleasePublicContactPoints(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, cassandraService.CassandraDataCenterStateRefreshFunc(d.Id(), []string{"ReleasePubConnFailed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.SetPartial("enable_public")
}
if d.IsNewResource() {
d.Partial(false)
return resourceAlicloudCassandraDataCenterRead(d, meta)
}
if d.HasChange("data_center_name") {
request := cassandra.CreateModifyDataCenterRequest()
request.ClusterId = parts[1]
request.DataCenterId = parts[0]
request.DataCenterName = d.Get("data_center_name").(string)
raw, err := client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.ModifyDataCenter(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("data_center_name")
}
if d.HasChange("instance_type") {
request := cassandra.CreateModifyInstanceTypeRequest()
request.ClusterId = parts[1]
request.DataCenterId = parts[0]
request.InstanceType = d.Get("instance_type").(string)
raw, err := client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.ModifyInstanceType(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, cassandraService.CassandraDataCenterStateRefreshFunc(d.Id(), []string{"ModifyInstanceTypeFailed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("instance_type")
}
if d.HasChange("disk_size") {
request := cassandra.CreateResizeDiskSizeRequest()
request.ClusterId = parts[1]
request.DataCenterId = parts[0]
request.DiskSize = requests.NewInteger(d.Get("disk_size").(int))
raw, err := client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.ResizeDiskSize(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, cassandraService.CassandraDataCenterStateRefreshFunc(d.Id(), []string{"ResizeDiskSizeFailed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("disk_size")
}
if d.HasChange("node_count") {
request := cassandra.CreateResizeNodeCountRequest()
request.ClusterId = parts[1]
request.DataCenterId = parts[0]
request.NodeCount = requests.NewInteger(d.Get("node_count").(int))
raw, err := client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.ResizeNodeCount(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, cassandraService.CassandraDataCenterStateRefreshFunc(d.Id(), []string{"ResizeNodeCountFailed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("node_count")
}
d.Partial(false)
return resourceAlicloudCassandraDataCenterRead(d, meta)
}
func resourceAlicloudCassandraDataCenterDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request := cassandra.CreateDeleteDataCenterRequest()
request.ClusterId = parts[1]
request.DataCenterId = parts[0]
raw, err := client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.DeleteDataCenter(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
if IsExpectedErrors(err, []string{"DataCenter.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
cassandraService := CassandraService{client}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, cassandraService.CassandraClusterStateRefreshFunc(parts[1], []string{"DeleteOtherDataCenterFailed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, parts[1])
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCddcDedicatedHost() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCddcDedicatedHostCreate,
Read: resourceAlicloudCddcDedicatedHostRead,
Update: resourceAlicloudCddcDedicatedHostUpdate,
Delete: resourceAlicloudCddcDedicatedHostDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(20 * time.Minute),
Update: schema.DefaultTimeout(20 * time.Minute),
Delete: schema.DefaultTimeout(20 * time.Minute),
},
Schema: map[string]*schema.Schema{
"allocation_status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Allocatable", "Suspended"}, false),
},
"auto_renew": {
Type: schema.TypeBool,
Optional: true,
},
"dedicated_host_group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"dedicated_host_id": {
Type: schema.TypeString,
Computed: true,
},
"host_class": {
Type: schema.TypeString,
Required: true,
},
"host_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-zA_Z][a-zA-Z0-9_-]{1,63}`), "The name must be `1` to `64` characters in length and can contain letters, digits, underscores (_), and hyphens (-). The name must start with a letter."),
},
"image_category": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"WindowsWithMssqlEntAlwaysonLicense", "WindowsWithMssqlStdLicense", "WindowsWithMssqlEntLicense", "WindowsWithMssqlWebLicense", "AliLinux"}, false),
},
"os_password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"payment_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"Subscription"}, false),
},
"period": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Month", "Year", "Week"}, false),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
"used_time": {
Type: schema.TypeInt,
Optional: true,
},
"vswitch_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"zone_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudCddcDedicatedHostCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateDedicatedHost"
request := make(map[string]interface{})
conn, err := client.NewCddcClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("auto_renew"); ok {
request["AutoRenew"] = v
}
request["DedicatedHostGroupId"] = d.Get("dedicated_host_group_id")
request["HostClass"] = d.Get("host_class")
if v, ok := d.GetOk("host_name"); ok {
request["HostName"] = v
}
if v, ok := d.GetOk("image_category"); ok {
request["ImageCategory"] = v
}
if v, ok := d.GetOk("os_password"); ok {
request["OsPassword"] = v
}
request["PayType"] = convertCddcDedicatedPaymentTypeRequest(d.Get("payment_type").(string))
if v, ok := d.GetOk("period"); ok {
request["Period"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("used_time"); ok {
request["UsedTime"] = fmt.Sprint(v)
}
request["ZoneId"] = d.Get("zone_id")
if v, ok := d.GetOk("vswitch_id"); ok {
request["VSwitchId"] = v
}
request["ClientToken"] = buildClientToken("CreateDedicatedHost")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cddc_dedicated_host", action, AlibabaCloudSdkGoERROR)
}
responseDedicateHostList := response["DedicateHostList"].(map[string]interface{})
d.SetId(fmt.Sprint(request["DedicatedHostGroupId"], ":", responseDedicateHostList["DedicateHostList"].([]interface{})[0].(map[string]interface{})["DedicatedHostId"]))
cddcService := CddcService{client}
stateConf := BuildStateConf([]string{}, []string{"1"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, cddcService.CddcDedicatedHostStateRefreshFunc(d.Id(), []string{"5"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudCddcDedicatedHostUpdate(d, meta)
}
func resourceAlicloudCddcDedicatedHostRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cddcService := CddcService{client}
object, err := cddcService.DescribeCddcDedicatedHost(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cddc_dedicated_host cddcService.DescribeCddcDedicatedHost Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("dedicated_host_group_id", object["DedicatedHostGroupId"])
d.Set("host_class", object["HostClass"])
d.Set("host_name", object["HostName"])
d.Set("status", object["HostStatus"])
d.Set("vswitch_id", object["VSwitchId"])
d.Set("zone_id", object["ZoneId"])
d.Set("allocation_status", convertCddcAllocationStatusResponse(object["AllocationStatus"].(string)))
d.Set("dedicated_host_id", object["DedicatedHostId"])
listTagResourcesObject, err := cddcService.ListTagResources(d.Id(), "DEDICATEDHOST")
if err != nil {
return WrapError(err)
}
d.Set("tags", tagsToMap(listTagResourcesObject))
return nil
}
func resourceAlicloudCddcDedicatedHostUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cddcService := CddcService{client}
var response map[string]interface{}
d.Partial(true)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
if d.HasChange("tags") {
if err := cddcService.SetResourceTags(d, "DEDICATEDHOST"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
if d.HasChange("host_name") || d.HasChange("allocation_status") {
request := map[string]interface{}{
"DedicatedHostId": parts[1],
}
if v, ok := d.GetOk("host_name"); ok {
request["HostName"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("allocation_status"); ok {
request["AllocationStatus"] = convertCddcAllocationStatusRequest(v.(string))
}
action := "ModifyDedicatedHostAttribute"
conn, err := client.NewCddcClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"1"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, cddcService.CddcDedicatedHostStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("host_name")
}
if !d.IsNewResource() && d.HasChange("host_class") {
request := map[string]interface{}{
"DedicatedHostId": parts[1],
}
request["TargetClassCode"] = d.Get("host_class")
request["RegionId"] = client.RegionId
action := "ModifyDedicatedHostClass"
conn, err := client.NewCddcClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"1"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, cddcService.CddcDedicatedHostStateRefreshFunc(d.Id(), []string{"5"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("host_class")
}
d.Partial(false)
return resourceAlicloudCddcDedicatedHostRead(d, meta)
}
func resourceAlicloudCddcDedicatedHostDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resource AlicloudResourceCddcDedicatedHost. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
func convertCddcDedicatedPaymentTypeRequest(source string) string {
switch source {
case "Subscription":
return "Prepaid"
}
return source
}
func convertCddcAllocationStatusRequest(source string) string {
switch source {
case "Allocatable":
return "1"
case "Suspended":
return "0"
}
return source
}
func convertCddcAllocationStatusResponse(source string) string {
switch source {
case "1":
return "Allocatable"
case "0":
return "Suspended"
}
return source
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCddcDedicatedHostAccount() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCddcDedicatedHostAccountCreate,
Read: resourceAlicloudCddcDedicatedHostAccountRead,
Update: resourceAlicloudCddcDedicatedHostAccountUpdate,
Delete: resourceAlicloudCddcDedicatedHostAccountDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"account_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-z][a-z0-9_]{0,14}[a-z0-9]$`), "The account name must be 2 to 16 characters in length, and can contain lower case letters, digits, and underscore(_)."),
},
"account_password": {
Type: schema.TypeString,
Required: true,
Sensitive: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[\w!@#$%^&*()_+=]{6,32}$`), "The account password must be 6 to 32 characters in length, and can contain letters, digits, and special characters(!@#$%^&*()_+-=)."),
},
"account_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Admin", "Normal"}, false),
},
"dedicated_host_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudCddcDedicatedHostAccountCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateDedicatedHostAccount"
request := make(map[string]interface{})
conn, err := client.NewCddcClient()
if err != nil {
return WrapError(err)
}
request["AccountName"] = d.Get("account_name")
request["AccountPassword"] = d.Get("account_password")
if v, ok := d.GetOk("account_type"); ok {
request["AccountType"] = v
}
request["DedicatedHostId"] = d.Get("dedicated_host_id")
request["RegionId"] = client.RegionId
request["ClientToken"] = buildClientToken("CreateDedicatedHostAccount")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cddc_dedicated_host_account", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["DedicatedHostId"], ":", request["AccountName"]))
return resourceAlicloudCddcDedicatedHostAccountRead(d, meta)
}
func resourceAlicloudCddcDedicatedHostAccountRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cddcService := CddcService{client}
_, err := cddcService.DescribeCddcDedicatedHostAccount(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cddc_dedicated_host_account cddcService.DescribeCddcDedicatedHostAccount Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("account_name", parts[1])
d.Set("dedicated_host_id", parts[0])
return nil
}
func resourceAlicloudCddcDedicatedHostAccountUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AccountName": parts[1],
"DedicatedHostId": parts[0],
}
if d.HasChange("account_password") {
request["AccountPassword"] = d.Get("account_password")
}
request["RegionId"] = client.RegionId
action := "ModifyDedicatedHostAccount"
conn, err := client.NewCddcClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return resourceAlicloudCddcDedicatedHostAccountRead(d, meta)
}
func resourceAlicloudCddcDedicatedHostAccountDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteDedicatedHostAccount"
var response map[string]interface{}
conn, err := client.NewCddcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AccountName": parts[1],
"DedicatedHostId": parts[0],
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
// wait for complete async operation
time.Sleep(2 * time.Minute)
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCddcDedicatedHostGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCddcDedicatedHostGroupCreate,
Read: resourceAlicloudCddcDedicatedHostGroupRead,
Update: resourceAlicloudCddcDedicatedHostGroupUpdate,
Delete: resourceAlicloudCddcDedicatedHostGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"allocation_policy": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Evenly", "Intensively"}, false),
},
"cpu_allocation_ratio": {
Type: schema.TypeInt,
Computed: true,
Optional: true,
ValidateFunc: validation.IntBetween(100, 300),
},
"dedicated_host_group_desc": {
Type: schema.TypeString,
Optional: true,
},
"disk_allocation_ratio": {
Type: schema.TypeInt,
Computed: true,
Optional: true,
ValidateFunc: validation.IntBetween(100, 300),
},
"engine": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Redis", "SQLServer", "MySQL", "PostgreSQL", "MongoDB"}, false),
},
"host_replace_policy": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"mem_allocation_ratio": {
Type: schema.TypeInt,
Computed: true,
Optional: true,
ValidateFunc: validation.IntBetween(0, 100),
},
"vpc_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"open_permission": {
Type: schema.TypeBool,
Computed: true,
Optional: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudCddcDedicatedHostGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateDedicatedHostGroup"
request := make(map[string]interface{})
conn, err := client.NewCddcClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("allocation_policy"); ok {
request["AllocationPolicy"] = v
}
if v, ok := d.GetOk("cpu_allocation_ratio"); ok {
request["CpuAllocationRatio"] = v
}
if v, ok := d.GetOk("dedicated_host_group_desc"); ok {
request["DedicatedHostGroupDesc"] = v
}
if v, ok := d.GetOk("open_permission"); ok {
request["OpenPermission"] = convertCddcDedicatedHostGroupOpenPermissionRequest(v.(bool))
}
request["Engine"] = d.Get("engine")
if v, ok := d.GetOk("disk_allocation_ratio"); ok {
if d.Get("engine").(string) == "SQLServer" && v.(int) > 100 {
return WrapError(fmt.Errorf("disk_allocation_ratio needs to be less than 100 under the SQLServer"))
}
request["DiskAllocationRatio"] = v
}
if v, ok := d.GetOk("host_replace_policy"); ok {
request["HostReplacePolicy"] = v
}
if v, ok := d.GetOk("mem_allocation_ratio"); ok {
request["MemAllocationRatio"] = v
}
request["RegionId"] = client.RegionId
request["VPCId"] = d.Get("vpc_id")
request["ClientToken"] = buildClientToken("CreateDedicatedHostGroup")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cddc_dedicated_host_group", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["DedicatedHostGroupId"]))
return resourceAlicloudCddcDedicatedHostGroupRead(d, meta)
}
func resourceAlicloudCddcDedicatedHostGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cddcService := CddcService{client}
object, err := cddcService.DescribeCddcDedicatedHostGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cddc_dedicated_host_group cddcService.DescribeCddcDedicatedHostGroup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("allocation_policy", object["AllocationPolicy"])
if v, ok := object["CpuAllocationRatio"]; ok && fmt.Sprint(v) != "0" {
d.Set("cpu_allocation_ratio", formatInt(v))
}
d.Set("dedicated_host_group_desc", object["DedicatedHostGroupDesc"])
if v, ok := object["DiskAllocationRatio"]; ok && fmt.Sprint(v) != "0" {
d.Set("disk_allocation_ratio", formatInt(v))
}
d.Set("engine", switchEngine(object["Engine"].(string)))
d.Set("host_replace_policy", object["HostReplacePolicy"])
if v, ok := object["MemAllocationRatio"]; ok && fmt.Sprint(v) != "0" {
d.Set("mem_allocation_ratio", formatInt(v))
}
d.Set("vpc_id", object["VPCId"])
d.Set("open_permission", convertCddcDedicatedHostGroupOpenPermissionResponse(formatInt(object["OpenPermission"])))
return nil
}
func resourceAlicloudCddcDedicatedHostGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"DedicatedHostGroupId": d.Id(),
}
request["RegionId"] = client.RegionId
if d.HasChange("allocation_policy") {
update = true
if v, ok := d.GetOk("allocation_policy"); ok {
request["AllocationPolicy"] = v
}
}
if d.HasChange("cpu_allocation_ratio") {
update = true
if v, ok := d.GetOk("cpu_allocation_ratio"); ok {
request["CpuAllocationRatio"] = v
}
}
if d.HasChange("dedicated_host_group_desc") {
update = true
if v, ok := d.GetOk("dedicated_host_group_desc"); ok {
request["DedicatedHostGroupDesc"] = v
}
}
if d.HasChange("disk_allocation_ratio") {
update = true
if v, ok := d.GetOk("disk_allocation_ratio"); ok {
request["DiskAllocationRatio"] = v
}
}
if d.HasChange("host_replace_policy") {
update = true
if v, ok := d.GetOk("host_replace_policy"); ok {
request["HostReplacePolicy"] = v
}
}
if d.HasChange("mem_allocation_ratio") {
update = true
if v, ok := d.GetOk("mem_allocation_ratio"); ok {
request["MemAllocationRatio"] = v
}
}
if update {
action := "ModifyDedicatedHostGroupAttribute"
conn, err := client.NewCddcClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudCddcDedicatedHostGroupRead(d, meta)
}
func resourceAlicloudCddcDedicatedHostGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteDedicatedHostGroup"
var response map[string]interface{}
conn, err := client.NewCddcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DedicatedHostGroupId": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func switchEngine(engine string) string {
switch engine {
case "mysql":
engine = "MySQL"
case "redis":
engine = "Redis"
case "mssql":
engine = "SQLServer"
case "pgsql":
engine = "PostgreSQL"
case "mongodb":
engine = "MongoDB"
}
return engine
}
func convertCddcDedicatedHostGroupOpenPermissionRequest(source interface{}) interface{} {
switch source {
case true:
return 3
case false:
return 0
}
return 3
}
func convertCddcDedicatedHostGroupOpenPermissionResponse(source interface{}) interface{} {
switch source {
case 0:
return false
case 3:
return true
}
return false
}
package alicloud
import (
"fmt"
"regexp"
"strconv"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/denverdino/aliyungo/cdn"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCdnDomain() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCdnDomainCreate,
Read: resourceAlicloudCdnDomainRead,
Update: resourceAlicloudCdnDomainUpdate,
Delete: resourceAlicloudCdnDomainDelete,
Schema: map[string]*schema.Schema{
"domain_name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(5, 67),
},
"cdn_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{cdn.Web, cdn.Download, cdn.Video, cdn.LiveStream}, false),
},
"source_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{cdn.Ipaddr, cdn.Domain, cdn.OSS}, false),
Deprecated: "Use `alicloud_cdn_domain_new` configuration `sources` block `type` argument instead.",
},
"source_port": {
Type: schema.TypeInt,
Optional: true,
Default: 80,
// must be one 80 or 443.
ValidateFunc: validation.IntInSlice([]int{80, 443}),
Deprecated: "Use `alicloud_cdn_domain_new` configuration `sources` block `port` argument instead.",
},
"sources": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
MaxItems: 20,
Deprecated: "Use `alicloud_cdn_domain_new` configuration `sources` argument instead.",
},
"scope": {
Type: schema.TypeString,
Optional: true,
Computed: true,
// Domestic, Overseas, Global
ValidateFunc: validation.StringInSlice([]string{cdn.Domestic, cdn.Overseas, cdn.Global}, false),
},
// configs
"optimize_enable": {
Type: schema.TypeString,
Optional: true,
// must be 'on' or 'off'
ValidateFunc: validation.StringInSlice([]string{"on", "off"}, false),
Deprecated: "Use `alicloud_cdn_domain_config` configuration `function_name` and `function_args` arguments instead.",
},
"page_compress_enable": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"on", "off"}, false),
Deprecated: "Use `alicloud_cdn_domain_config` configuration `function_name` and `function_args` arguments instead.",
},
"range_enable": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"on", "off"}, false),
Deprecated: "Use `alicloud_cdn_domain_config` configuration `function_name` and `function_args` arguments instead.",
},
"video_seek_enable": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"on", "off"}, false),
Deprecated: "Use `alicloud_cdn_domain_config` configuration `function_name` and `function_args` arguments instead.",
},
"block_ips": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Deprecated: "Use `alicloud_cdn_domain_config` configuration `function_name` and `function_args` arguments instead.",
},
"parameter_filter_config": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeString,
Optional: true,
Default: "off",
ValidateFunc: validation.StringInSlice([]string{"on", "off"}, false),
},
"hash_key_args": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringDoesNotContainAny(",."),
},
MaxItems: 10,
},
},
},
MaxItems: 1,
Deprecated: "Use `alicloud_cdn_domain_config` configuration `function_name` and `function_args` arguments instead.",
},
"page_404_config": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"page_type": {
Type: schema.TypeString,
Optional: true,
Default: "default",
ValidateFunc: validation.StringInSlice([]string{"default", "charity", "other"}, false),
},
"custom_page_url": {
Type: schema.TypeString,
Optional: true,
},
"error_code": {
Type: schema.TypeString,
Computed: true,
},
},
},
MaxItems: 1,
Deprecated: "Use `alicloud_cdn_domain_config` configuration `function_name` and `function_args` arguments instead.",
},
"refer_config": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"refer_type": {
Type: schema.TypeString,
Optional: true,
Default: "block",
ValidateFunc: validation.StringInSlice([]string{"block", "allow"}, false),
},
"refer_list": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"allow_empty": {
Type: schema.TypeString,
Optional: true,
Default: "on",
ValidateFunc: validation.StringInSlice([]string{"on", "off"}, false),
},
},
},
MaxItems: 1,
Deprecated: "Use `alicloud_cdn_domain_config` configuration `function_name` and `function_args` arguments instead.",
},
"certificate_config": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"server_certificate": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"server_certificate_status": {
Type: schema.TypeString,
Default: "on",
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"on", "off"}, false),
},
"private_key": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
},
},
MaxItems: 1,
Deprecated: "Use `alicloud_cdn_domain_config` configuration `function_name` and `function_args` arguments instead.",
},
"auth_config": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"auth_type": {
Type: schema.TypeString,
Optional: true,
Default: "no_auth",
// must be one of ['no_auth', 'type_a', 'type_b', 'type_c']"
ValidateFunc: validation.StringInSlice([]string{"no_auth", "type_a", "type_b", "type_c"}, false),
},
"master_key": {
Type: schema.TypeString,
Optional: true,
Computed: true,
// can only consists of alphanumeric characters and can not be longer than 32 or less than 6 characters.
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-zA-Z0-9]{6,32}$`), "can only consists of alphanumeric characters and can not be longer than 32 or less than 6 characters."),
},
"slave_key": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-zA-Z0-9]{6,32}$`), "can only consists of alphanumeric characters and can not be longer than 32 or less than 6 characters."),
},
"timeout": {
Type: schema.TypeInt,
Optional: true,
Default: 1800,
},
},
},
MaxItems: 1,
Deprecated: "Use `alicloud_cdn_domain_config` configuration `function_name` and `function_args` arguments instead.",
},
"http_header_config": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"header_key": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{cdn.ContentType, cdn.CacheControl, cdn.ContentDisposition, cdn.ContentLanguage, cdn.Expires, cdn.AccessControlAllowMethods, cdn.AccessControlAllowOrigin, cdn.AccessControlMaxAge}, false),
},
"header_value": {
Type: schema.TypeString,
Required: true,
},
"header_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
MaxItems: 10,
Deprecated: "Use `alicloud_cdn_domain_config` configuration `function_name` and `function_args` arguments instead.",
},
"cache_config": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cache_content": {
Type: schema.TypeString,
Required: true,
},
"ttl": {
Type: schema.TypeInt,
Required: true,
},
"cache_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"suffix", "path"}, false),
},
"weight": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
ValidateFunc: validation.IntBetween(1, 99),
},
"cache_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
Deprecated: "Use `alicloud_cdn_domain_config` configuration `function_name` and `function_args` arguments instead.",
},
},
}
}
func resourceAlicloudCdnDomainCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
args := cdn.AddDomainRequest{
DomainName: d.Get("domain_name").(string),
CdnType: d.Get("cdn_type").(string),
SourcePort: d.Get("source_port").(int),
}
if v, ok := d.GetOk("scope"); ok {
args.Scope = v.(string)
}
if args.CdnType != cdn.LiveStream {
if v, ok := d.GetOk("sources"); ok && v.(*schema.Set).Len() > 0 {
sources := expandStringList(v.(*schema.Set).List())
args.Sources = strings.Join(sources, ",")
} else {
return fmt.Errorf("Sources is required when 'cdn_type' is not 'liveStream'.")
}
if v, ok := d.GetOk("source_type"); ok && v.(string) != "" {
args.SourceType = v.(string)
} else {
return fmt.Errorf("SourceType is required when 'cdn_type' is not 'liveStream'.")
}
}
_, err := client.WithCdnClient(func(cdnClient *cdn.CdnClient) (interface{}, error) {
return cdnClient.AddCdnDomain(args)
})
if err != nil {
return fmt.Errorf("AddCdnDomain got an error: %#v", err)
}
d.SetId(args.DomainName)
err = WaitForDomainStatus(d.Id(), Configuring, 60, meta)
if err != nil {
return fmt.Errorf("Timeout when Cdn Domain Available. Error: %#v", err)
}
return resourceAlicloudCdnDomainUpdate(d, meta)
}
func resourceAlicloudCdnDomainUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
d.Partial(true)
args := cdn.ModifyDomainRequest{
DomainName: d.Id(),
SourceType: d.Get("source_type").(string),
}
if !d.IsNewResource() {
attributeUpdate := false
if d.HasChange("source_type") {
d.SetPartial("source_type")
attributeUpdate = true
}
if d.HasChange("sources") {
d.SetPartial("sources")
sources := expandStringList(d.Get("sources").(*schema.Set).List())
args.Sources = strings.Join(sources, ",")
attributeUpdate = true
}
if d.HasChange("source_port") {
d.SetPartial("source_port")
args.SourcePort = d.Get("source_port").(int)
attributeUpdate = true
}
if attributeUpdate {
_, err := client.WithCdnClient(func(cdnClient *cdn.CdnClient) (interface{}, error) {
return cdnClient.ModifyCdnDomain(args)
})
if err != nil {
return fmt.Errorf("ModifyCdnDomain got an error: %#v", err)
}
}
}
// set optimize_enable 、range_enable、page_compress_enable and video_seek_enable
if err := enableConfigUpdate(client, d); err != nil {
return err
}
if d.HasChange("block_ips") {
d.SetPartial("block_ips")
blockIps := expandStringList(d.Get("block_ips").(*schema.Set).List())
args := cdn.IpBlackRequest{DomainName: d.Id(), BlockIps: strings.Join(blockIps, ",")}
_, err := client.WithCdnClient(func(cdnClient *cdn.CdnClient) (interface{}, error) {
return cdnClient.SetIpBlackListConfig(args)
})
if err != nil {
return err
}
}
if d.HasChange("parameter_filter_config") {
if err := queryStringConfigUpdate(client, d); err != nil {
return err
}
}
if d.HasChange("page_404_config") {
if err := page404ConfigUpdate(client, d); err != nil {
return err
}
}
if d.HasChange("refer_config") {
if err := referConfigUpdate(client, d); err != nil {
return err
}
}
if d.HasChange("auth_config") {
if err := authConfigUpdate(client, d); err != nil {
return err
}
}
if d.HasChange("http_header_config") {
if err := httpHeaderConfigUpdate(client, d); err != nil {
return err
}
}
if d.HasChange("cache_config") {
if err := cacheConfigUpdate(client, d); err != nil {
return err
}
}
if d.HasChange("certificate_config") {
if d.IsNewResource() {
err := WaitForDomainStatus(d.Id(), Online, 360, meta)
if err != nil {
return fmt.Errorf("Timeout when Cdn Domain Online. Error: %#v", err)
}
}
if err := certificateConfigUpdate(client, d); err != nil {
return err
}
}
d.Partial(false)
return resourceAlicloudCdnDomainRead(d, meta)
}
func resourceAlicloudCdnDomainRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
domain, err := DescribeDomainDetail(d.Id(), meta)
if err != nil {
return fmt.Errorf("DescribeDomainDetail got an error: %#v", err)
}
d.Set("domain_name", domain.DomainName)
d.Set("sources", domain.Sources.Source)
d.Set("cdn_type", domain.CdnType)
d.Set("source_type", domain.SourceType)
d.Set("scope", domain.Scope)
// get domain configs
describeConfigArgs := cdn.DomainConfigRequest{
DomainName: d.Id(),
}
raw, err := client.WithCdnClient(func(cdnClient *cdn.CdnClient) (interface{}, error) {
return cdnClient.DescribeDomainConfigs(describeConfigArgs)
})
if err != nil {
return fmt.Errorf("DescribeDomainConfigs got an error: %#v", err)
}
resp, _ := raw.(cdn.DomainConfigResponse)
configs := resp.DomainConfigs
queryStringConfig := configs.IgnoreQueryStringConfig
if _, ok := d.GetOk("parameter_filter_config"); ok {
config := make([]map[string]interface{}, 1)
config[0] = map[string]interface{}{
"enable": queryStringConfig.Enable,
"hash_key_args": strings.Split(queryStringConfig.HashKeyArgs, ","),
}
d.Set("parameter_filter_config", config)
}
if _, ok := d.GetOk("certificate_config"); ok {
ov := d.Get("certificate_config")
oldConfig := ov.([]interface{})
config := make([]map[string]interface{}, 1)
serverCertificateStatus := domain.ServerCertificateStatus
if serverCertificateStatus == "" {
serverCertificateStatus = "off"
}
config[0] = map[string]interface{}{
"server_certificate": domain.ServerCertificate,
"server_certificate_status": serverCertificateStatus,
}
if oldConfig != nil && len(oldConfig) > 0 {
val := oldConfig[0].(map[string]interface{})
config[0]["private_key"] = val["private_key"]
}
d.Set("certificate_config", config)
}
errorPageConfig := configs.ErrorPageConfig
if _, ok := d.GetOk("page_404_config"); ok {
config := make([]map[string]interface{}, 1)
config[0] = map[string]interface{}{
"page_type": errorPageConfig.PageType,
"error_code": errorPageConfig.ErrorCode,
"custom_page_url": errorPageConfig.CustomPageUrl,
}
if errorPageConfig.PageType == "" {
config[0]["page_type"] = "default"
}
d.Set("page_404_config", config)
}
referConfig := configs.RefererConfig
if _, ok := d.GetOk("refer_config"); ok {
config := make([]map[string]interface{}, 1)
config[0] = map[string]interface{}{
"refer_type": referConfig.ReferType,
"refer_list": strings.Split(referConfig.ReferList, ","),
"allow_empty": referConfig.AllowEmpty,
}
d.Set("refer_config", config)
}
authConfig := configs.ReqAuthConfig
if _, ok := d.GetOk("auth_config"); ok {
config := make([]map[string]interface{}, 1)
timeout, _ := strconv.Atoi(authConfig.TimeOut)
config[0] = map[string]interface{}{
"auth_type": authConfig.AuthType,
"master_key": authConfig.Key1,
"slave_key": authConfig.Key2,
"timeout": timeout,
}
d.Set("auth_config", config)
}
headerConfigs := configs.HttpHeaderConfigs.HttpHeaderConfig
httpHeaderConfigs := make([]map[string]interface{}, 0, len(headerConfigs))
for _, v := range headerConfigs {
val := make(map[string]interface{})
val["header_key"] = v.HeaderKey
val["header_value"] = v.HeaderValue
val["header_id"] = v.ConfigId
httpHeaderConfigs = append(httpHeaderConfigs, val)
}
d.Set("http_header_config", httpHeaderConfigs)
cacheConfigs := configs.CacheExpiredConfigs.CacheExpiredConfig
cacheExpiredConfigs := make([]map[string]interface{}, 0, len(cacheConfigs))
for _, v := range cacheConfigs {
val := make(map[string]interface{})
ttl, _ := strconv.Atoi(v.TTL)
weight, _ := strconv.Atoi(v.Weight)
val["cache_type"] = v.CacheType
val["cache_content"] = v.CacheContent
val["cache_id"] = v.ConfigId
val["weight"] = weight
val["ttl"] = ttl
cacheExpiredConfigs = append(cacheExpiredConfigs, val)
}
d.Set("cache_config", cacheExpiredConfigs)
d.Set("optimize_enable", configs.OptimizeConfig.Enable)
d.Set("page_compress_enable", configs.PageCompressConfig.Enable)
d.Set("range_enable", configs.RangeConfig.Enable)
d.Set("video_seek_enable", configs.VideoSeekConfig.Enable)
blocks := make([]string, 0)
if len(configs.CcConfig.BlockIps) > 0 {
blocks = strings.Split(configs.CcConfig.BlockIps, ",")
}
d.Set("block_ips", blocks)
return nil
}
func resourceAlicloudCdnDomainDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
args := cdn.DescribeDomainRequest{
DomainName: d.Id(),
}
return resource.Retry(5*time.Minute, func() *resource.RetryError {
_, err := client.WithCdnClient(func(cdnClient *cdn.CdnClient) (interface{}, error) {
return cdnClient.DeleteCdnDomain(args)
})
if err != nil {
if IsExpectedErrors(err, []string{"ServiceBusy"}) {
return resource.RetryableError(fmt.Errorf("The specified Domain is configuring, please retry later."))
}
return resource.NonRetryableError(fmt.Errorf("Error deleting cdn domain %s: %#v.", d.Id(), err))
}
return nil
})
}
func enableConfigUpdate(client *connectivity.AliyunClient, d *schema.ResourceData) error {
type configFunc func(req cdn.ConfigRequest) (cdn.CdnCommonResponse, error)
raw, _ := client.WithCdnClient(func(cdnClient *cdn.CdnClient) (interface{}, error) {
return map[string]configFunc{
"optimize_enable": cdnClient.SetOptimizeConfig,
"range_enable": cdnClient.SetRangeConfig,
"page_compress_enable": cdnClient.SetPageCompressConfig,
"video_seek_enable": cdnClient.SetVideoSeekConfig,
}, nil
})
relation, _ := raw.(map[string]configFunc)
for key, fn := range relation {
if d.HasChange(key) {
d.SetPartial(key)
args := cdn.ConfigRequest{
DomainName: d.Id(),
Enable: d.Get(key).(string),
}
if _, err := fn(args); err != nil {
return err
}
}
}
return nil
}
func queryStringConfigUpdate(client *connectivity.AliyunClient, d *schema.ResourceData) error {
valSet := d.Get("parameter_filter_config").(*schema.Set)
args := cdn.QueryStringConfigRequest{DomainName: d.Id()}
if valSet == nil || valSet.Len() == 0 {
args.Enable = "off"
_, err := client.WithCdnClient(func(cdnClient *cdn.CdnClient) (interface{}, error) {
return cdnClient.SetIgnoreQueryStringConfig(args)
})
if err != nil {
return err
}
return nil
}
val := valSet.List()[0].(map[string]interface{})
d.SetPartial("parameter_filter_config")
args.Enable = val["enable"].(string)
if v, ok := val["hash_key_args"]; ok && len(v.([]interface{})) > 0 {
hashKeyArgs := expandStringList(v.([]interface{}))
args.HashKeyArgs = strings.Join(hashKeyArgs, ",")
}
_, err := client.WithCdnClient(func(cdnClient *cdn.CdnClient) (interface{}, error) {
return cdnClient.SetIgnoreQueryStringConfig(args)
})
if err != nil {
return err
}
return nil
}
func page404ConfigUpdate(client *connectivity.AliyunClient, d *schema.ResourceData) error {
valSet := d.Get("page_404_config").(*schema.Set)
args := cdn.ErrorPageConfigRequest{DomainName: d.Id()}
if valSet == nil || valSet.Len() == 0 {
args.PageType = "default"
_, err := client.WithCdnClient(func(cdnClient *cdn.CdnClient) (interface{}, error) {
return cdnClient.SetErrorPageConfig(args)
})
if err != nil {
return err
}
return nil
}
val := valSet.List()[0].(map[string]interface{})
d.SetPartial("page_404_config")
args.PageType = val["page_type"].(string)
customPageUrl, ok := val["custom_page_url"]
if ok {
args.CustomPageUrl = customPageUrl.(string)
}
if args.PageType == "charity" && (ok && customPageUrl.(string) != CharityPageUrl || !ok) {
return fmt.Errorf("If 'page_type' value is 'charity', you must set 'custom_page_url' with '%s'.", CharityPageUrl)
}
if args.PageType == "default" && ok && customPageUrl.(string) != "" {
return fmt.Errorf("If 'page_type' value is 'default', you can not set 'custom_page_url'.")
}
if args.PageType == "other" && (!ok || customPageUrl.(string) == "") {
return fmt.Errorf("If 'page_type' value is 'other', you must set the value of 'custom_page_url'.")
}
_, err := client.WithCdnClient(func(cdnClient *cdn.CdnClient) (interface{}, error) {
return cdnClient.SetErrorPageConfig(args)
})
if err != nil {
return err
}
return nil
}
func referConfigUpdate(client *connectivity.AliyunClient, d *schema.ResourceData) error {
valSet := d.Get("refer_config").(*schema.Set)
args := cdn.ReferConfigRequest{DomainName: d.Id()}
if valSet == nil || valSet.Len() == 0 {
args.ReferType = "block"
args.AllowEmpty = "on"
_, err := client.WithCdnClient(func(cdnClient *cdn.CdnClient) (interface{}, error) {
return cdnClient.SetRefererConfig(args)
})
if err != nil {
return err
}
return nil
}
val := valSet.List()[0].(map[string]interface{})
d.SetPartial("refer_config")
args.ReferType = val["refer_type"].(string)
args.AllowEmpty = val["allow_empty"].(string)
if v, ok := val["refer_list"]; ok && len(v.([]interface{})) > 0 {
referList := expandStringList(v.([]interface{}))
args.ReferList = strings.Join(referList, ",")
}
_, err := client.WithCdnClient(func(cdnClient *cdn.CdnClient) (interface{}, error) {
return cdnClient.SetRefererConfig(args)
})
if err != nil {
return err
}
return nil
}
func authConfigUpdate(client *connectivity.AliyunClient, d *schema.ResourceData) error {
ov, nv := d.GetChange("auth_config")
oldConfig, newConfig := ov.(*schema.Set), nv.(*schema.Set)
args := cdn.ReqAuthConfigRequest{DomainName: d.Id()}
if newConfig == nil || newConfig.Len() == 0 {
args.AuthType = "no_auth"
_, err := client.WithCdnClient(func(cdnClient *cdn.CdnClient) (interface{}, error) {
return cdnClient.SetReqAuthConfig(args)
})
if err != nil {
return err
}
return nil
}
val := newConfig.List()[0].(map[string]interface{})
d.SetPartial("auth_config")
args.AuthType = val["auth_type"].(string)
args.Timeout = strconv.Itoa(val["timeout"].(int))
masterKey, okMasterKey := val["master_key"]
slaveKey, okSlaveKey := val["slave_key"]
if okMasterKey {
args.Key1 = masterKey.(string)
}
if okSlaveKey {
args.Key2 = slaveKey.(string)
}
if args.AuthType == "no_auth" {
if oldConfig == nil || oldConfig.Len() == 0 {
if okMasterKey || okSlaveKey {
return fmt.Errorf("If 'auth_type' value is 'no_auth', you can not set the value of 'master_key' and 'slave_key'.")
}
} else {
oldVal := oldConfig.List()[0].(map[string]interface{})
if oldVal["master_key"] != val["master_key"] || oldVal["slave_key"] != val["slave_key"] {
return fmt.Errorf("If 'auth_type' value is 'no_auth', you can not change the value of 'master_key' and 'slave_key'.")
}
}
} else {
if !okMasterKey || !okSlaveKey {
return fmt.Errorf("If 'auth_type' value is one of ['type_a', 'type_b', 'type_c'], you must set 'master_key' and 'slave_key' at one time.")
}
}
_, err := client.WithCdnClient(func(cdnClient *cdn.CdnClient) (interface{}, error) {
return cdnClient.SetReqAuthConfig(args)
})
if err != nil {
return err
}
return nil
}
func certificateConfigUpdate(client *connectivity.AliyunClient, d *schema.ResourceData) error {
ov, nv := d.GetChange("certificate_config")
oldConfig, newConfig := ov.([]interface{}), nv.([]interface{})
args := cdn.CertificateRequest{
DomainName: d.Id(),
}
if newConfig == nil || len(newConfig) == 0 {
args.ServerCertificateStatus = "off"
_, err := client.WithCdnClient(func(cdnClient *cdn.CdnClient) (interface{}, error) {
return cdnClient.SetDomainServerCertificate(args)
})
if err != nil {
return err
}
d.SetPartial("certificate_config")
return nil
}
val := newConfig[0].(map[string]interface{})
args.ServerCertificateStatus = val["server_certificate_status"].(string)
serverCertificate, okServerCertificate := val["server_certificate"]
privateKey, okPrivateKey := val["private_key"]
if okServerCertificate {
args.ServerCertificate = serverCertificate.(string)
}
if okPrivateKey {
args.PrivateKey = privateKey.(string)
}
if args.ServerCertificateStatus == "off" {
if oldConfig == nil || len(oldConfig) == 0 {
if okServerCertificate || okPrivateKey {
return fmt.Errorf("If 'server_certificate_status' value is 'off', you can not set the value of 'server_certificate' and 'private_key'.")
}
}
} else {
if !okServerCertificate || !okPrivateKey {
return fmt.Errorf("If 'server_certificate_status' value is 'on', you must set 'server_certificate', and 'private_key'")
}
}
_, err := client.WithCdnClient(func(cdnClient *cdn.CdnClient) (interface{}, error) {
return cdnClient.SetDomainServerCertificate(args)
})
if err != nil {
return err
}
d.SetPartial("certificate_config")
if okServerCertificate && args.ServerCertificateStatus != "off" {
err := WaitForServerCertificate(client, d.Id(), args.ServerCertificate, 360)
if err != nil {
return fmt.Errorf("Timeout waiting for Cdn server certificate. Error: %#v", err)
}
}
return nil
}
func httpHeaderConfigUpdate(client *connectivity.AliyunClient, d *schema.ResourceData) error {
ov, nv := d.GetChange("http_header_config")
oldConfigs := ov.(*schema.Set).List()
newConfigs := nv.(*schema.Set).List()
for _, v := range oldConfigs {
configId := v.(map[string]interface{})["header_id"].(string)
args := cdn.DeleteHttpHeaderConfigRequest{
DomainName: d.Id(),
ConfigID: configId,
}
_, err := client.WithCdnClient(func(cdnClient *cdn.CdnClient) (interface{}, error) {
return cdnClient.DeleteHttpHeaderConfig(args)
})
if err != nil {
return err
}
}
if len(newConfigs) == 0 {
return nil
}
for _, v := range newConfigs {
args := cdn.HttpHeaderConfigRequest{
DomainName: d.Id(),
HeaderKey: v.(map[string]interface{})["header_key"].(string),
HeaderValue: v.(map[string]interface{})["header_value"].(string),
}
_, err := client.WithCdnClient(func(cdnClient *cdn.CdnClient) (interface{}, error) {
return cdnClient.SetHttpHeaderConfig(args)
})
if err != nil {
return fmt.Errorf("SetHttpHeaderConfig got an error: %#v", err)
}
}
return nil
}
func cacheConfigUpdate(client *connectivity.AliyunClient, d *schema.ResourceData) error {
ov, nv := d.GetChange("cache_config")
oldConfigs := ov.(*schema.Set).List()
newConfigs := nv.(*schema.Set).List()
for _, v := range oldConfigs {
val := v.(map[string]interface{})
configId := val["cache_id"].(string)
args := cdn.DeleteCacheConfigRequest{
DomainName: d.Id(),
ConfigID: configId,
CacheType: val["cache_type"].(string),
}
_, err := client.WithCdnClient(func(cdnClient *cdn.CdnClient) (interface{}, error) {
return cdnClient.DeleteCacheExpiredConfig(args)
})
if err != nil {
return fmt.Errorf("DeleteCacheExpiredConfig got an error: %#v", err)
}
}
if len(newConfigs) == 0 {
return nil
}
for _, v := range newConfigs {
val := v.(map[string]interface{})
args := cdn.CacheConfigRequest{
DomainName: d.Id(),
CacheContent: val["cache_content"].(string),
TTL: strconv.Itoa(val["ttl"].(int)),
Weight: strconv.Itoa(val["weight"].(int)),
}
if err := setCacheExpiredConfig(args, val["cache_type"].(string), client); err != nil {
return err
}
}
return nil
}
func setCacheExpiredConfig(req cdn.CacheConfigRequest, cacheType string, client *connectivity.AliyunClient) (err error) {
if cacheType == "suffix" {
_, err = client.WithCdnClient(func(cdnClient *cdn.CdnClient) (interface{}, error) {
return cdnClient.SetFileCacheExpiredConfig(req)
})
} else {
_, err = client.WithCdnClient(func(cdnClient *cdn.CdnClient) (interface{}, error) {
return cdnClient.SetPathCacheExpiredConfig(req)
})
}
return
}
func describeDomainDetailClient(Id string, client *connectivity.AliyunClient) (domain cdn.DomainDetail, err error) {
args := cdn.DescribeDomainRequest{
DomainName: Id,
}
raw, e := client.WithCdnClient(func(cdnClient *cdn.CdnClient) (interface{}, error) {
return cdnClient.DescribeCdnDomainDetail(args)
})
if e != nil {
err = fmt.Errorf("DescribeCdnDomainDetail got an error: %#v", e)
return
}
response, _ := raw.(cdn.DomainResponse)
domain = response.GetDomainDetailModel
return
}
func DescribeDomainDetail(Id string, meta interface{}) (domain cdn.DomainDetail, err error) {
client := meta.(*connectivity.AliyunClient)
return describeDomainDetailClient(Id, client)
}
func WaitForDomainStatus(Id string, status Status, timeout int, meta interface{}) error {
if timeout <= 0 {
timeout = DefaultTimeout
}
for {
domain, err := DescribeDomainDetail(Id, meta)
if err != nil {
return err
}
if domain.DomainStatus == string(status) {
break
}
timeout = timeout - DefaultIntervalShort
if timeout <= 0 {
return GetTimeErrorFromString(GetTimeoutMessage("Domain", string(status)))
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func WaitForServerCertificate(client *connectivity.AliyunClient, Id string, serverCertificate string, timeout int) error {
if timeout <= 0 {
timeout = DefaultTimeout
}
for {
domain, err := describeDomainDetailClient(Id, client)
if err != nil {
return err
}
if strings.TrimSpace(domain.ServerCertificate) == strings.TrimSpace(serverCertificate) {
break
}
timeout = timeout - DefaultIntervalShort
if timeout <= 0 {
return GetTimeErrorFromString(GetTimeoutMessage("ServerCertificate", string(serverCertificate)))
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
package alicloud
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/hashcode"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCdnDomainConfig() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCdnDomainConfigCreate,
Read: resourceAlicloudCdnDomainConfigRead,
Update: resourceAlicloudCdnDomainConfigUpdate,
Delete: resourceAlicloudCdnDomainConfigDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"domain_name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(5, 67),
},
"function_name": {
Type: schema.TypeString,
Required: true,
},
"config_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"function_args": {
Type: schema.TypeSet,
Set: expirationCdnDomainConfigHash,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"arg_name": {
Type: schema.TypeString,
Required: true,
},
"arg_value": {
Type: schema.TypeString,
Required: true,
},
},
},
},
},
}
}
func resourceAlicloudCdnDomainConfigCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cdnService := &CdnService{client: client}
var response map[string]interface{}
conn, err := cdnService.client.NewCdnClient()
if err != nil {
return WrapError(err)
}
action := "BatchSetCdnDomainConfig"
config := make([]map[string]interface{}, 1)
functionArgs := d.Get("function_args").(*schema.Set).List()
args := make([]map[string]interface{}, len(functionArgs))
for key, value := range functionArgs {
arg := value.(map[string]interface{})
args[key] = map[string]interface{}{
"argName": arg["arg_name"],
"argValue": arg["arg_value"],
}
}
config[0] = map[string]interface{}{
"functionArgs": args,
"functionName": d.Get("function_name").(string),
}
bytconfig, _ := json.Marshal(config)
request := map[string]interface{}{
"RegionId": client.RegionId,
"DomainNames": d.Get("domain_name").(string),
"Functions": string(bytconfig),
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cdn_domain_config", action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.DomainConfigList.DomainConfigModel", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, "request.DomainNames", "$.DomainConfigList.DomainConfigModel", err)
}
if len(v.([]interface{})) != 1 {
return WrapErrorf(Error(GetNotFoundMessage("CDN", d.Get("function_name").(string))), DefaultErrorMsg, err)
}
val := v.([]interface{})[0].(map[string]interface{})
d.SetId(fmt.Sprintf("%s:%s:%s", val["DomainName"], val["FunctionName"], val["ConfigId"]))
stateConf := BuildStateConf([]string{}, []string{"success"}, d.Timeout(schema.TimeoutCreate), 30*time.Second, cdnService.CdnDomainConfigRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
err = cdnService.WaitForCdnDomain(d.Get("domain_name").(string), Online, DefaultTimeoutMedium)
if err != nil {
return WrapError(err)
}
return resourceAlicloudCdnDomainConfigRead(d, meta)
}
func resourceAlicloudCdnDomainConfigUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cdnService := &CdnService{client: client}
var response map[string]interface{}
conn, err := cdnService.client.NewCdnClient()
if err != nil {
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"RegionId": client.RegionId,
"DomainNames": parts[0],
}
update := false
if d.HasChange("function_args") {
update = true
config := make([]map[string]interface{}, 1)
functionArgs := d.Get("function_args").(*schema.Set).List()
args := make([]map[string]interface{}, len(functionArgs))
for key, value := range functionArgs {
arg := value.(map[string]interface{})
args[key] = map[string]interface{}{
"argName": arg["arg_name"],
"argValue": arg["arg_value"],
}
}
config[0] = map[string]interface{}{
"functionArgs": args,
"functionName": parts[1],
"configId": parts[2],
}
bytconfig, _ := json.Marshal(config)
request["Functions"] = string(bytconfig)
}
if update {
action := "BatchSetCdnDomainConfig"
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cdn_domain_config", action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.DomainConfigList.DomainConfigModel", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, "request.DomainNames", "$.DomainConfigList.DomainConfigModel", err)
}
if len(v.([]interface{})) > 1 {
return WrapErrorf(Error(GetNotFoundMessage("CDN", d.Get("function_name").(string))), DefaultErrorMsg, err)
}
stateConf := BuildStateConf([]string{}, []string{"success"}, d.Timeout(schema.TimeoutCreate), 30*time.Second, cdnService.CdnDomainConfigRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
err = cdnService.WaitForCdnDomain(d.Get("domain_name").(string), Online, DefaultTimeoutMedium)
if err != nil {
return WrapError(err)
}
return resourceAlicloudCdnDomainConfigRead(d, meta)
}
func resourceAlicloudCdnDomainConfigRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cdnService := &CdnService{client: client}
v, err := cdnService.DescribeCdnDomainConfig(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
val := v.(map[string]interface{})
args := make([]interface{}, 0)
if v, ok := val["FunctionArgs"].(map[string]interface{}); ok {
if tmp, exist := v["FunctionArg"].([]interface{}); exist {
args = tmp
}
}
var funArgs []map[string]string
for _, k := range args {
arg := k.(map[string]interface{})
// This two function args is extra, filter them to pass test check.
if arg["ArgName"] == "aliyun_id" || arg["ArgName"] == "scheme_origin_port" {
continue
}
// private_oss_tbl always is changed and used to enable Alibaba Cloud OSS Private Bucket Back to Source Authorization
if arg["ArgName"] == "private_oss_tbl" {
continue
}
funArgs = append(funArgs, map[string]string{
"arg_name": arg["ArgName"].(string),
"arg_value": arg["ArgValue"].(string),
})
}
parts := strings.Split(d.Id(), ":")
d.Set("domain_name", parts[0])
d.Set("function_name", parts[1])
d.Set("config_id", val["ConfigId"])
if len(parts) == 2 {
d.SetId(fmt.Sprintf("%s:%s:%s", parts[0], parts[1], val["ConfigId"]))
}
d.Set("status", val["Status"])
d.Set("function_args", funArgs)
return nil
}
func resourceAlicloudCdnDomainConfigDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cdnService := &CdnService{client: client}
_, err := cdnService.DescribeCdnDomainConfig(d.Id())
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
action := "DeleteSpecificConfig"
var response map[string]interface{}
conn, err := cdnService.client.NewCdnClient()
if err != nil {
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"RegionId": client.RegionId,
"DomainName": parts[0],
"ConfigId": parts[2],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func expirationCdnDomainConfigHash(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
if v, ok := m["arg_name"]; ok {
buf.WriteString(fmt.Sprintf("%s-", v.(string)))
}
if v, ok := m["arg_value"]; ok {
buf.WriteString(fmt.Sprintf("%s-", v.(string)))
}
return hashcode.String(buf.String())
}
package alicloud
import (
"encoding/json"
"strconv"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cdn"
cdn2 "github.com/denverdino/aliyungo/cdn"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCdnDomainNew() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCdnDomainCreateNew,
Read: resourceAlicloudCdnDomainReadNew,
Update: resourceAlicloudCdnDomainUpdateNew,
Delete: resourceAlicloudCdnDomainDeleteNew,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"domain_name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(5, 67),
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"cdn_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice(cdn2.CdnTypes, false),
},
"sources": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"content": {
Type: schema.TypeString,
Required: true,
},
"type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice(cdn2.SourceTypes, false),
},
"port": {
Type: schema.TypeInt,
Optional: true,
Default: 80,
ValidateFunc: validation.IntInSlice([]int{80, 443}),
},
"priority": {
Type: schema.TypeInt,
Optional: true,
Default: 20,
ValidateFunc: validation.IntBetween(0, 100),
},
"weight": {
Type: schema.TypeInt,
Optional: true,
Default: 10,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("sources"); ok && len(v.(*schema.Set).List()) > 0 {
sources := make([]map[string]interface{}, len(v.(*schema.Set).List()))
byteSources, _ := json.Marshal(v.(*schema.Set).List())
json.Unmarshal(byteSources, &sources)
for _, source := range sources {
if source["type"].(string) == "ipaddr" && formatInt(source["weight"]) != 10 {
return true
}
}
}
return false
},
ValidateFunc: validation.IntBetween(0, 100),
},
},
},
},
"certificate_config": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"server_certificate": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"server_certificate_status": {
Type: schema.TypeString,
Default: "on",
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"on", "off"}, false),
},
"private_key": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"force_set": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"1", "0"}, false),
},
"cert_name": {
Type: schema.TypeString,
Optional: true,
},
"cert_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"upload", "cas", "free"}, false),
},
},
},
MaxItems: 1,
},
"scope": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice(cdn2.Scopes, false),
},
"tags": tagsSchema(),
"cname": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudCdnDomainCreateNew(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cdnService := &CdnService{client: client}
request := cdn.CreateAddCdnDomainRequest()
request.RegionId = client.RegionId
if v := d.Get("resource_group_id").(string); v != "" {
request.ResourceGroupId = v
}
request.DomainName = d.Get("domain_name").(string)
request.CdnType = d.Get("cdn_type").(string)
if v, ok := d.GetOk("scope"); ok {
request.Scope = v.(string)
}
sources, err := cdnService.convertCdnSourcesToString(d.Get("sources").(*schema.Set).List())
if err != nil {
return WrapError(err)
}
request.Sources = sources
raw, err := client.WithCdnClient_new(func(cdnClient *cdn.Client) (interface{}, error) {
return cdnClient.AddCdnDomain(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cdn_domain", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetId(request.DomainName)
err = cdnService.WaitForCdnDomain(d.Id(), Online, DefaultLongTimeout)
if err != nil {
return WrapError(err)
}
return resourceAlicloudCdnDomainUpdateNew(d, meta)
}
func resourceAlicloudCdnDomainUpdateNew(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cdnService := &CdnService{client}
d.Partial(true)
if !d.IsNewResource() {
request := cdn.CreateModifyCdnDomainRequest()
request.RegionId = client.RegionId
if v := d.Get("resource_group_id").(string); v != "" {
request.ResourceGroupId = v
}
request.DomainName = d.Id()
if d.HasChange("sources") {
sources, err := cdnService.convertCdnSourcesToString(d.Get("sources").(*schema.Set).List())
if err != nil {
return WrapError(err)
}
request.Sources = sources
raw, err := client.WithCdnClient_new(func(cdnClient *cdn.Client) (interface{}, error) {
return cdnClient.ModifyCdnDomain(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
err = cdnService.WaitForCdnDomain(d.Id(), Online, DefaultTimeoutMedium)
if err != nil {
return WrapError(err)
}
d.SetPartial("sources")
d.SetPartial("resource_group_id")
}
}
if d.HasChange("certificate_config") {
if err := certificateConfigUpdateNew(client, d); err != nil {
return WrapError(err)
}
}
if err := setCdnTags(client, TagResourceCdn, d); err != nil {
return WrapError(err)
}
d.Partial(false)
return resourceAlicloudCdnDomainReadNew(d, meta)
}
func resourceAlicloudCdnDomainReadNew(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cdnService := &CdnService{client: client}
object, err := cdnService.DescribeCdnDomainNew(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
if len(object.SourceModels.SourceModel) > 0 {
sources := make([]map[string]interface{}, 0)
for _, model := range object.SourceModels.SourceModel {
priority, _ := strconv.Atoi(model.Priority)
weight, _ := strconv.Atoi(model.Weight)
sources = append(sources, map[string]interface{}{
"content": model.Content,
"port": model.Port,
"priority": priority,
"type": model.Type,
"weight": weight,
})
}
err := d.Set("sources", sources)
if err != nil {
return WrapError(err)
}
}
d.Set("domain_name", object.DomainName)
d.Set("cdn_type", object.CdnType)
d.Set("scope", object.Scope)
d.Set("resource_group_id", object.ResourceGroupId)
d.Set("cname", object.Cname)
certInfo, err := cdnService.DescribeDomainCertificateInfo(d.Id())
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
oldConfig := d.Get("certificate_config").([]interface{})
config := make([]map[string]interface{}, 1)
serverCertificateStatus := object.ServerCertificateStatus
if serverCertificateStatus == "" {
serverCertificateStatus = "off"
}
config[0] = map[string]interface{}{
"server_certificate": certInfo.ServerCertificate,
"server_certificate_status": serverCertificateStatus,
"cert_name": certInfo.CertName,
"cert_type": certInfo.CertType,
}
if oldConfig != nil && len(oldConfig) > 0 {
val := oldConfig[0].(map[string]interface{})
config[0]["private_key"] = val["private_key"]
config[0]["force_set"] = val["force_set"]
config[0]["region"] = val["region"]
}
d.Set("certificate_config", config)
tags, err := cdnService.DescribeTags(d.Id(), TagResourceCdn)
if err != nil {
return WrapError(err)
}
d.Set("tags", cdnTagsToMap(tags))
return nil
}
func resourceAlicloudCdnDomainDeleteNew(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cdnService := CdnService{client}
request := cdn.CreateDeleteCdnDomainRequest()
request.RegionId = client.RegionId
request.DomainName = d.Id()
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithCdnClient_new(func(cdnClient *cdn.Client) (interface{}, error) {
return cdnClient.DeleteCdnDomain(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ServiceBusy"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDomain.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(cdnService.WaitForCdnDomain(d.Id(), Deleted, DefaultTimeout))
}
func certificateConfigUpdateNew(client *connectivity.AliyunClient, d *schema.ResourceData) error {
cdnService := &CdnService{client}
request := cdn.CreateSetDomainServerCertificateRequest()
request.RegionId = client.RegionId
request.DomainName = d.Id()
v, ok := d.GetOk("certificate_config")
if !ok {
request.ServerCertificateStatus = "off"
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithCdnClient_new(func(cdnClient *cdn.Client) (interface{}, error) {
return cdnClient.SetDomainServerCertificate(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ServiceBusy"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("certificate_config")
return nil
}
config := v.([]interface{})
val := config[0].(map[string]interface{})
request.ServerCertificateStatus = val["server_certificate_status"].(string)
serverCertificate, okServerCertificate := val["server_certificate"]
if okServerCertificate {
request.ServerCertificate = serverCertificate.(string)
}
if v, ok := val["private_key"]; ok {
request.PrivateKey = v.(string)
}
if v, ok := val["force_set"]; ok && v.(string) != "" {
request.ForceSet = v.(string)
}
if v, ok := val["cert_name"]; ok && v.(string) != "" {
request.CertName = v.(string)
}
if v, ok := val["cert_type"]; ok && v.(string) != "" {
request.CertType = v.(string)
}
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithCdnClient_new(func(cdnClient *cdn.Client) (interface{}, error) {
return cdnClient.SetDomainServerCertificate(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ServiceBusy"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("certificate_config")
if serverCertificate != "" && request.ServerCertificateStatus != "off" {
err := cdnService.WaitForServerCertificateNew(d.Id(), request.ServerCertificate, DefaultTimeout)
if err != nil {
return WrapError(err)
}
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCdnRealTimeLogDelivery() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCdnRealTimeLogDeliveryCreate,
Read: resourceAlicloudCdnRealTimeLogDeliveryRead,
Delete: resourceAlicloudCdnRealTimeLogDeliveryDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(2 * time.Minute),
},
Schema: map[string]*schema.Schema{
"domain": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"logstore": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"project": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"sls_region": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudCdnRealTimeLogDeliveryCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateRealTimeLogDelivery"
request := make(map[string]interface{})
conn, err := client.NewCdnClient()
if err != nil {
return WrapError(err)
}
request["Domain"] = d.Get("domain")
request["Logstore"] = d.Get("logstore")
request["Project"] = d.Get("project")
request["Region"] = d.Get("sls_region")
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2018-05-10"), StringPointer("AK"), request, nil, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"InternalError"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cdn_real_time_log_delivery", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["Domain"]))
return resourceAlicloudCdnRealTimeLogDeliveryRead(d, meta)
}
func resourceAlicloudCdnRealTimeLogDeliveryRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cdnService := CdnService{client}
object, err := cdnService.DescribeCdnRealTimeLogDelivery(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cdn_real_time_log_delivery cdnService.DescribeCdnRealTimeLogDelivery Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("domain", d.Id())
d.Set("logstore", object["Logstore"])
d.Set("project", object["Project"])
d.Set("sls_region", object["Region"])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudCdnRealTimeLogDeliveryDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteRealtimeLogDelivery"
var response map[string]interface{}
conn, err := client.NewCdnClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"Domain": d.Id(),
}
request["Logstore"] = d.Get("logstore")
request["Project"] = d.Get("project")
request["Region"] = d.Get("sls_region")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2018-05-10"), StringPointer("AK"), request, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCenBandwidthLimit() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCenBandwidthLimitCreate,
Read: resourceAlicloudCenBandwidthLimitRead,
Update: resourceAlicloudCenBandwidthLimitUpdate,
Delete: resourceAlicloudCenBandwidthLimitDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Update: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"region_ids": {
Type: schema.TypeSet,
Required: true,
ForceNew: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
MaxItems: 2,
MinItems: 2,
},
"bandwidth_limit": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntAtLeast(1),
},
},
}
}
func resourceAlicloudCenBandwidthLimitCreate(d *schema.ResourceData, meta interface{}) error {
cenId := d.Get("instance_id").(string)
regionIds := d.Get("region_ids").(*schema.Set).List()
if len(regionIds) != 2 {
return WrapError(Error("Two different region ids should be set for bandwidth limit. "))
}
localRegionId := regionIds[0].(string)
oppositeRegionId := regionIds[1].(string)
if strings.Compare(localRegionId, oppositeRegionId) <= 0 {
d.SetId(cenId + COLON_SEPARATED + localRegionId + COLON_SEPARATED + oppositeRegionId)
} else {
d.SetId(cenId + COLON_SEPARATED + oppositeRegionId + COLON_SEPARATED + localRegionId)
}
return resourceAlicloudCenBandwidthLimitUpdate(d, meta)
}
func resourceAlicloudCenBandwidthLimitRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cenService := CenService{client}
object, err := cenService.DescribeCenBandwidthLimit(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
respRegionIds := make([]string, 0)
respRegionIds = append(respRegionIds, object.LocalRegionId, object.OppositeRegionId)
d.Set("region_ids", respRegionIds)
d.Set("instance_id", object.CenId)
d.Set("bandwidth_limit", object.BandwidthLimit)
return nil
}
func resourceAlicloudCenBandwidthLimitUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cenService := CenService{client}
cenId := d.Get("instance_id").(string)
regionIds := d.Get("region_ids").(*schema.Set).List()
if len(regionIds) != 2 {
return WrapError(Error("Two different region ids should be set for bandwidth limit. "))
}
localRegionId := regionIds[0].(string)
oppositeRegionId := regionIds[1].(string)
var bandwidthLimit int
if d.HasChange("bandwidth_limit") {
bandwidthLimit = d.Get("bandwidth_limit").(int)
if bandwidthLimit == 0 {
return WrapError(Error("the bandwidth limit should be at least than 1 Mbps"))
}
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
err := cenService.SetCenInterRegionBandwidthLimit(cenId, localRegionId, oppositeRegionId, bandwidthLimit)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidOperation.CenInstanceStatus"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapError(err)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
stateConf := BuildStateConf([]string{"Modifying"}, []string{"Active"}, d.Timeout(schema.TimeoutUpdate), 3*time.Second, cenService.CenBandwidthLimitStateRefreshFunc(d.Id(), []string{}))
if _, err = stateConf.WaitForState(); err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudCenBandwidthLimitRead(d, meta)
}
func resourceAlicloudCenBandwidthLimitDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cenService := CenService{client}
cenId := d.Get("instance_id").(string)
regionIds := d.Get("region_ids").(*schema.Set).List()
if len(regionIds) != 2 {
return fmt.Errorf("Two different region ids should be set for bandwidth limit")
}
localRegionId := regionIds[0].(string)
oppositeRegionId := regionIds[1].(string)
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
err := cenService.SetCenInterRegionBandwidthLimit(cenId, localRegionId, oppositeRegionId, 0)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidOperation.CenInstanceStatus"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapError(err)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
stateConf := BuildStateConf([]string{"Active", "Modifying"}, []string{}, d.Timeout(schema.TimeoutDelete), 3*time.Second, cenService.CenBandwidthLimitStateRefreshFunc(d.Id(), []string{}))
_, err = stateConf.WaitForState()
if IsExpectedErrors(err, []string{ThrottlingUser}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
})
if err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cbn"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCenBandwidthPackage() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCenBandwidthPackageCreate,
Read: resourceAlicloudCenBandwidthPackageRead,
Update: resourceAlicloudCenBandwidthPackageUpdate,
Delete: resourceAlicloudCenBandwidthPackageDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(11 * time.Minute),
Update: schema.DefaultTimeout(5 * time.Minute),
Delete: schema.DefaultTimeout(11 * time.Minute),
},
Schema: map[string]*schema.Schema{
"bandwidth": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntAtLeast(1),
},
"cen_bandwidth_package_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringLenBetween(2, 128),
ConflictsWith: []string{"name"},
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringLenBetween(2, 128),
ConflictsWith: []string{"cen_bandwidth_package_name"},
Deprecated: "Field 'name' has been deprecated from version 1.98.0. Use 'cen_bandwidth_package_name' and instead.",
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"geographic_region_a_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Asia-Pacific", "Australia", "China", "Europe", "Middle-East", "North-America"}, false),
ConflictsWith: []string{"geographic_region_ids"},
},
"geographic_region_b_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Asia-Pacific", "Australia", "China", "Europe", "Middle-East", "North-America"}, false),
ConflictsWith: []string{"geographic_region_ids"},
},
"geographic_region_ids": {
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
MaxItems: 2,
MinItems: 1,
ConflictsWith: []string{"geographic_region_a_id", "geographic_region_b_id"},
Deprecated: "Field 'geographic_region_ids' has been deprecated from version 1.98.0. Use 'geographic_region_a_id' and 'geographic_region_b_id' instead.",
},
"payment_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"PostPaid", "PrePaid"}, false),
ConflictsWith: []string{"charge_type"},
},
"charge_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"PostPaid", "PrePaid"}, false),
ConflictsWith: []string{"payment_type"},
Deprecated: "Field 'charge_type' has been deprecated from version 1.98.0. Use 'payment_type' and instead.",
},
"period": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 6, 12}),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return PayType(d.Get("charge_type").(string)) == PostPaid || PayType(d.Get("payment_type").(string)) == PostPaid
},
},
"expired_time": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudCenBandwidthPackageCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
request := cbn.CreateCreateCenBandwidthPackageRequest()
request.AutoPay = requests.NewBoolean(true)
request.Bandwidth = requests.NewInteger(d.Get("bandwidth").(int))
if v, ok := d.GetOk("cen_bandwidth_package_name"); ok {
request.Name = v.(string)
} else if v, ok := d.GetOk("name"); ok {
request.Name = v.(string)
}
if v, ok := d.GetOk("description"); ok {
request.Description = v.(string)
}
if d.Get("geographic_region_a_id").(string) != "" && d.Get("geographic_region_b_id").(string) != "" {
request.GeographicRegionAId = d.Get("geographic_region_a_id").(string)
request.GeographicRegionBId = d.Get("geographic_region_b_id").(string)
} else if len(d.Get("geographic_region_ids").(*schema.Set).List()) > 0 {
geographicRegionId := d.Get("geographic_region_ids").(*schema.Set).List()
if len(geographicRegionId) == 1 {
request.GeographicRegionAId = geographicRegionId[0].(string)
request.GeographicRegionBId = geographicRegionId[0].(string)
} else if len(geographicRegionId) == 2 {
if geographicRegionId[1].(string) == "China" {
request.GeographicRegionAId = geographicRegionId[1].(string)
request.GeographicRegionBId = geographicRegionId[0].(string)
} else {
request.GeographicRegionAId = geographicRegionId[0].(string)
request.GeographicRegionBId = geographicRegionId[1].(string)
}
}
} else {
return WrapError(Error(`[ERROR] Argument "geographic_region_a_id" and "geographic_region_b_id" must be set!`))
}
if v, ok := d.GetOk("payment_type"); ok {
if v.(string) == "PrePaid" {
request.BandwidthPackageChargeType = convertPaymentTypeRequest(v.(string))
request.PricingCycle = "Month"
} else {
request.BandwidthPackageChargeType = convertPaymentTypeRequest("PostPaid")
}
} else if v, ok := d.GetOk("charge_type"); ok {
if v.(string) == "PrePaid" {
request.BandwidthPackageChargeType = convertPaymentTypeRequest(v.(string))
request.PricingCycle = "Month"
} else {
request.BandwidthPackageChargeType = convertPaymentTypeRequest("PostPaid")
}
}
if v, ok := d.GetOk("period"); ok {
request.Period = requests.NewInteger(v.(int))
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err := resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.CreateCenBandwidthPackage(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw)
response, _ := raw.(*cbn.CreateCenBandwidthPackageResponse)
d.SetId(fmt.Sprintf("%v", response.CenBandwidthPackageId))
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cen_bandwidth_package", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Idle"}, d.Timeout(schema.TimeoutCreate), 10*time.Second, cbnService.CenBandwidthPackageStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudCenBandwidthPackageRead(d, meta)
}
func resourceAlicloudCenBandwidthPackageRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
object, err := cbnService.DescribeCenBandwidthPackage(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cen_bandwidth_package cbnService.DescribeCenBandwidthPackage Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
geographicRegionIds := make([]string, 0)
geographicRegionIds = append(geographicRegionIds, convertGeographicRegionAIdResponse(object.GeographicRegionAId))
geographicRegionIds = append(geographicRegionIds, convertGeographicRegionBIdResponse(object.GeographicRegionBId))
d.Set("geographic_region_ids", geographicRegionIds)
d.Set("bandwidth", object.Bandwidth)
d.Set("cen_bandwidth_package_name", object.Name)
d.Set("name", object.Name)
d.Set("description", object.Description)
d.Set("geographic_region_a_id", convertGeographicRegionAIdResponse(object.GeographicRegionAId))
d.Set("geographic_region_b_id", convertGeographicRegionBIdResponse(object.GeographicRegionBId))
d.Set("payment_type", convertPaymentTypeResponse(object.BandwidthPackageChargeType))
d.Set("charge_type", convertPaymentTypeResponse(object.BandwidthPackageChargeType))
//if convertPaymentTypeResponse(object.BandwidthPackageChargeType) == "PrePaid" {
// period, err := computePeriodByUnit(object.CreationTime, object.ExpiredTime, d.Get("period").(int), "Month")
// if err != nil {
// return WrapError(err)
// }
// d.Set("period", period)
//}
d.Set("expired_time", object.ExpiredTime)
d.Set("status", object.Status)
return nil
}
func resourceAlicloudCenBandwidthPackageUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cenService := CenService{client}
d.Partial(true)
if d.HasChange("bandwidth") {
request := cbn.CreateModifyCenBandwidthPackageSpecRequest()
request.CenBandwidthPackageId = d.Id()
request.Bandwidth = requests.NewInteger(d.Get("bandwidth").(int))
wait := incrementalWait(3*time.Second, 5*time.Second)
err := resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.ModifyCenBandwidthPackageSpec(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidStatus.Resource", "Operation.Blocking"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
if err := cenService.WaitForCenBandwidthPackage(d.Id(), Idle, d.Get("bandwidth").(int), DefaultCenTimeout); err != nil {
return WrapError(err)
}
d.SetPartial("bandwidth")
}
update := false
request := cbn.CreateModifyCenBandwidthPackageAttributeRequest()
request.CenBandwidthPackageId = d.Id()
if d.HasChange("cen_bandwidth_package_name") {
update = true
request.Name = d.Get("cen_bandwidth_package_name").(string)
}
if d.HasChange("name") {
update = true
request.Name = d.Get("name").(string)
}
if d.HasChange("description") {
update = true
request.Description = d.Get("description").(string)
}
if update {
wait := incrementalWait(3*time.Second, 5*time.Second)
err := resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.ModifyCenBandwidthPackageAttribute(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidStatus.Resource", "Operation.Blocking"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("cen_bandwidth_package_name")
d.SetPartial("name")
d.SetPartial("description")
}
d.Partial(false)
return resourceAlicloudCenBandwidthPackageRead(d, meta)
}
func resourceAlicloudCenBandwidthPackageDelete(d *schema.ResourceData, meta interface{}) error {
if d.Get("payment_type").(string) == "PrePaid" {
log.Printf("[WARN] Cannot destroy resource Alicloud Resource Cen BandwidthPackage. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
client := meta.(*connectivity.AliyunClient)
request := cbn.CreateDeleteCenBandwidthPackageRequest()
request.CenBandwidthPackageId = d.Id()
wait := incrementalWait(3*time.Second, 5*time.Second)
err := resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DeleteCenBandwidthPackage(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidOperation.CenBandwidthLimitsNotZero", "ParameterBwpInstanceId", "Forbidden.Release"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ParameterBwpInstanceId"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return nil
}
func convertPaymentTypeRequest(source string) string {
switch source {
case "PostPaid":
return "POSTPAY"
case "PrePaid":
return "PREPAY"
}
return source
}
func convertGeographicRegionAIdResponse(source string) string {
switch source {
case "asia-pacific":
return "Asia-Pacific"
case "china":
return "China"
case "europe":
return "Europe"
case "middle-east":
return "Middle-East"
case "north-america":
return "North-America"
case "australia":
return "Australia"
}
return source
}
func convertGeographicRegionBIdResponse(source string) string {
switch source {
case "asia-pacific":
return "Asia-Pacific"
case "china":
return "China"
case "europe":
return "Europe"
case "middle-east":
return "Middle-East"
case "north-america":
return "North-America"
case "australia":
return "Australia"
}
return source
}
func convertPaymentTypeResponse(source string) string {
switch source {
case "POSTPAY":
return "PostPaid"
case "PREPAY":
return "PrePaid"
}
return source
}
package alicloud
import (
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cbn"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCenBandwidthPackageAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCenBandwidthPackageAttachmentCreate,
Read: resourceAlicloudCenBandwidthPackageAttachmentRead,
Delete: resourceAlicloudCenBandwidthPackageAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"bandwidth_package_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudCenBandwidthPackageAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cenService := CenService{client}
cenId := d.Get("instance_id").(string)
cenBwpId := d.Get("bandwidth_package_id").(string)
request := cbn.CreateAssociateCenBandwidthPackageRequest()
request.CenId = cenId
request.CenBandwidthPackageId = cenBwpId
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithCenClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.AssociateCenBandwidthPackage(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidOperation.BwpInstanceStatus", "InvalidOperation.BwpBusinessStatus", "InvalidOperation.CenInstanceStatus", "Operation.Blocking"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cen_bandwidth_package_attachment", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetId(cenBwpId)
if err := cenService.WaitForCenBandwidthPackageAttachment(d.Id(), InUse, DefaultCenTimeout); err != nil {
return WrapError(err)
}
return resourceAlicloudCenBandwidthPackageAttachmentRead(d, meta)
}
func resourceAlicloudCenBandwidthPackageAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cenService := CenService{client}
object, err := cenService.DescribeCenBandwidthPackageAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_id", object.CenIds.CenId[0])
d.Set("bandwidth_package_id", object.CenBandwidthPackageId)
return nil
}
func resourceAlicloudCenBandwidthPackageAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cenService := CenService{client}
cenId := d.Get("instance_id").(string)
cenBwpId := d.Get("bandwidth_package_id").(string)
request := cbn.CreateUnassociateCenBandwidthPackageRequest()
request.CenId = cenId
request.CenBandwidthPackageId = cenBwpId
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithCenClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.UnassociateCenBandwidthPackage(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidOperation.BwpInstanceStatus", "InvalidOperation.BwpBusinessStatus", "InvalidOperation.CenInstanceStatus", "Operation.Blocking"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(cenService.WaitForCenBandwidthPackageAttachment(cenBwpId, Deleted, DefaultCenTimeout))
}
package alicloud
import (
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cbn"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCenFlowlog() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCenFlowlogCreate,
Read: resourceAlicloudCenFlowlogRead,
Update: resourceAlicloudCenFlowlogUpdate,
Delete: resourceAlicloudCenFlowlogDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"cen_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"flow_log_name": {
Type: schema.TypeString,
Optional: true,
},
"log_store_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"project_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Inactive"}, false),
Default: "Active",
},
},
}
}
func resourceAlicloudCenFlowlogCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cbn.CreateCreateFlowlogRequest()
request.CenId = d.Get("cen_id").(string)
if v, ok := d.GetOk("description"); ok {
request.Description = v.(string)
}
if v, ok := d.GetOk("flow_log_name"); ok {
request.FlowLogName = v.(string)
}
request.LogStoreName = d.Get("log_store_name").(string)
request.ProjectName = d.Get("project_name").(string)
request.RegionId = client.RegionId
request.ClientToken = buildClientToken(request.GetActionName())
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.CreateFlowlog(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cen_flowlog", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ := raw.(*cbn.CreateFlowlogResponse)
d.SetId(response.FlowLogId)
return resourceAlicloudCenFlowlogUpdate(d, meta)
}
func resourceAlicloudCenFlowlogRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
object, err := cbnService.DescribeCenFlowlog(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("cen_id", object.CenId)
d.Set("description", object.Description)
d.Set("flow_log_name", object.FlowLogName)
d.Set("log_store_name", object.LogStoreName)
d.Set("project_name", object.ProjectName)
d.Set("status", object.Status)
return nil
}
func resourceAlicloudCenFlowlogUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
d.Partial(true)
update := false
request := cbn.CreateModifyFlowLogAttributeRequest()
request.FlowLogId = d.Id()
request.CenId = d.Get("cen_id").(string)
request.RegionId = client.RegionId
if !d.IsNewResource() && d.HasChange("description") {
update = true
request.Description = d.Get("description").(string)
}
if !d.IsNewResource() && d.HasChange("flow_log_name") {
update = true
request.FlowLogName = d.Get("flow_log_name").(string)
}
if update {
err := resource.Retry(30*time.Second, func() *resource.RetryError {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.ModifyFlowLogAttribute(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"LOCK_ERROR"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("description")
d.SetPartial("flow_log_name")
}
if d.HasChange("status") {
object, err := cbnService.DescribeCenFlowlog(d.Id())
if err != nil {
return WrapError(err)
}
target := d.Get("status").(string)
if object.Status != target {
if target == "Active" {
request := cbn.CreateActiveFlowLogRequest()
request.FlowLogId = d.Id()
request.CenId = d.Get("cen_id").(string)
request.RegionId = client.RegionId
err := resource.Retry(30*time.Second, func() *resource.RetryError {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.ActiveFlowLog(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"LOCK_ERROR"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
if target == "Inactive" {
request := cbn.CreateDeactiveFlowLogRequest()
request.FlowLogId = d.Id()
request.CenId = d.Get("cen_id").(string)
request.RegionId = client.RegionId
err := resource.Retry(30*time.Second, func() *resource.RetryError {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DeactiveFlowLog(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"LOCK_ERROR"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("status")
}
}
d.Partial(false)
return resourceAlicloudCenFlowlogRead(d, meta)
}
func resourceAlicloudCenFlowlogDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cbn.CreateDeleteFlowlogRequest()
request.FlowLogId = d.Id()
request.CenId = d.Get("cen_id").(string)
request.RegionId = client.RegionId
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DeleteFlowlog(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidFlowlogId.NotFound", "ProjectOrLogstoreNotExist", "SourceProjectNotExist"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCenInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCenInstanceCreate,
Read: resourceAlicloudCenInstanceRead,
Update: resourceAlicloudCenInstanceUpdate,
Delete: resourceAlicloudCenInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(6 * time.Minute),
Delete: schema.DefaultTimeout(6 * time.Minute),
},
Schema: map[string]*schema.Schema{
"cen_instance_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"name"},
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Field 'name' has been deprecated from version 1.98.0. Use 'cen_instance_name' instead.",
ConflictsWith: []string{"cen_instance_name"},
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"protection_level": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
},
}
}
func resourceAlicloudCenInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateCen"
request := make(map[string]interface{})
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("cen_instance_name"); ok {
request["Name"] = v
} else if v, ok := d.GetOk("name"); ok {
request["Name"] = v
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("protection_level"); ok {
request["ProtectionLevel"] = v
}
request["ClientToken"] = buildClientToken("CreateCen")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cen_instance", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["CenId"]))
cbnService := CbnService{client}
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, cbnService.CenInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudCenInstanceUpdate(d, meta)
}
func resourceAlicloudCenInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
object, err := cbnService.DescribeCenInstance(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cen_instance cbnService.DescribeCenInstance Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("cen_instance_name", object["Name"])
d.Set("name", object["Name"])
d.Set("description", object["Description"])
d.Set("protection_level", object["ProtectionLevel"])
d.Set("status", object["Status"])
if v, ok := object["Tags"].(map[string]interface{}); ok {
d.Set("tags", tagsToMap(v["Tag"]))
}
return nil
}
func resourceAlicloudCenInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
d.Partial(true)
if d.HasChange("tags") {
if err := cbnService.SetResourceTags(d, "cen"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
update := false
request := map[string]interface{}{
"CenId": d.Id(),
}
if !d.IsNewResource() && (d.HasChange("cen_instance_name") || d.HasChange("name")) {
update = true
if v, ok := d.GetOk("cen_instance_name"); ok {
request["Name"] = v
} else if v, ok := d.GetOk("name"); ok {
request["Name"] = v
}
}
if !d.IsNewResource() && d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
}
if !d.IsNewResource() && d.HasChange("protection_level") {
update = true
if v, ok := d.GetOk("protection_level"); ok {
request["ProtectionLevel"] = v
}
}
if update {
action := "ModifyCenAttribute"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("name")
d.SetPartial("cen_instance_name")
d.SetPartial("description")
d.SetPartial("protection_level")
}
d.Partial(false)
return resourceAlicloudCenInstanceRead(d, meta)
}
func resourceAlicloudCenInstanceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
action := "DeleteCen"
var response map[string]interface{}
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"CenId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ParameterCenInstanceId"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, cbnService.CenInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cbn"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCenInstanceAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCenInstanceAttachmentCreate,
Read: resourceAlicloudCenInstanceAttachmentRead,
Update: resourceAlicloudCenInstanceAttachmentUpdate,
Delete: resourceAlicloudCenInstanceAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"cen_owner_id": {
Type: schema.TypeInt,
Optional: true,
},
"child_instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"child_instance_owner_id": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"child_instance_region_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"child_instance_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"VPC", "VBR", "CCN"}, false),
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudCenInstanceAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
request := cbn.CreateAttachCenChildInstanceRequest()
request.ChildInstanceId = d.Get("child_instance_id").(string)
if v, ok := d.GetOk("child_instance_owner_id"); ok {
request.ChildInstanceOwnerId = requests.NewInteger(v.(int))
}
request.ChildInstanceRegionId = d.Get("child_instance_region_id").(string)
request.ChildInstanceType = d.Get("child_instance_type").(string)
request.CenId = d.Get("instance_id").(string)
wait := incrementalWait(3*time.Second, 5*time.Second)
err := resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.AttachCenChildInstance(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidOperation.CenInstanceStatus", "InvalidOperation.ChildInstanceStatus", "Operation.Blocking", "OperationFailed.InvalidVpcStatus", "Throttling.User"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw)
d.SetId(fmt.Sprintf("%v:%v:%v:%v", request.CenId, request.ChildInstanceId, request.ChildInstanceType, request.ChildInstanceRegionId))
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cen_instance_attachment", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Attached"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, cbnService.CenInstanceAttachmentStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudCenInstanceAttachmentRead(d, meta)
}
func resourceAlicloudCenInstanceAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
if len(strings.Split(d.Id(), ":")) == 2 {
childType, _ := GetCenChildInstanceType(d.Get("child_instance_id").(string))
d.SetId(fmt.Sprintf("%v:%v:%v", d.Id(), childType, d.Get("child_instance_region_id").(string)))
}
object, err := cbnService.DescribeCenInstanceAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cen_instance_attachment cbnService.DescribeCenInstanceAttachment Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 4)
if err != nil {
return WrapError(err)
}
d.Set("child_instance_id", parts[1])
d.Set("child_instance_region_id", parts[3])
d.Set("child_instance_type", parts[2])
d.Set("instance_id", parts[0])
d.Set("child_instance_owner_id", object.ChildInstanceOwnerId)
d.Set("status", object.Status)
return nil
}
func resourceAlicloudCenInstanceAttachmentUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return resourceAlicloudCenInstanceAttachmentRead(d, meta)
}
func resourceAlicloudCenInstanceAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
if len(strings.Split(d.Id(), ":")) == 2 {
childType, _ := GetCenChildInstanceType(d.Get("child_instance_id").(string))
d.SetId(fmt.Sprintf("%v:%v:%v", d.Id(), childType, d.Get("child_instance_region_id").(string)))
}
parts, err := ParseResourceId(d.Id(), 4)
if err != nil {
return WrapError(err)
}
cbnService := CbnService{client}
request := cbn.CreateDetachCenChildInstanceRequest()
request.ChildInstanceId = parts[1]
request.ChildInstanceRegionId = parts[3]
request.ChildInstanceType = parts[2]
request.CenId = parts[0]
if v, ok := d.GetOk("cen_owner_id"); ok {
request.CenOwnerId = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("child_instance_owner_id"); ok {
request.ChildInstanceOwnerId = requests.NewInteger(v.(int))
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DetachCenChildInstance(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidOperation.CenInstanceStatus", "Operation.Blocking"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"Bid.NotFound", "ParameterInstanceId"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, cbnService.CenInstanceAttachmentStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCenInstanceGrant() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCenInstanceGrantCreate,
Read: resourceAlicloudCenInstanceGrantRead,
Delete: resourceAlicloudCenInstanceGrantDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"cen_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"child_instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"cen_owner_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudCenInstanceGrantCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cenId := d.Get("cen_id").(string)
ownerId := d.Get("cen_owner_id").(string)
regionId := client.RegionId
instanceId := d.Get("child_instance_id").(string)
instanceType, err := GetCenChildInstanceType(instanceId)
if err != nil {
return WrapError(err)
}
request := vpc.CreateGrantInstanceToCenRequest()
request.RegionId = regionId
request.CenId = cenId
request.CenOwnerId = requests.Integer(ownerId)
request.InstanceId = instanceId
request.InstanceType = instanceType
request.ClientToken = buildClientToken(request.GetActionName())
var raw interface{}
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err = client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.GrantInstanceToCen(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "UnknownError", "TaskConflict"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cen_instance_grant", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetId(cenId + COLON_SEPARATED + instanceId + COLON_SEPARATED + string(ownerId))
return resourceAlicloudCenInstanceGrantRead(d, meta)
}
func resourceAlicloudCenInstanceGrantRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
instanceId := parts[1]
object, err := vpcService.DescribeCenInstanceGrant(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("cen_id", object.CenInstanceId)
d.Set("cen_owner_id", object.CenOwnerId)
d.Set("child_instance_id", instanceId)
return nil
}
func resourceAlicloudCenInstanceGrantDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
cenId := parts[0]
instanceId := parts[1]
ownerId := parts[2]
instanceType, err := GetCenChildInstanceType(instanceId)
if err != nil {
return WrapError(err)
}
request := vpc.CreateRevokeInstanceFromCenRequest()
request.RegionId = client.RegionId
request.InstanceId = instanceId
request.InstanceType = instanceType
request.CenId = cenId
request.CenOwnerId = requests.Integer(ownerId)
var raw interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.RevokeInstanceFromCen(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidInstanceId.NotFound"}) {
return nil
} else if IsExpectedErrors(err, []string{"IncorrectStatus", "TaskConflict"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(vpcService.WaitForCenInstanceGrant(d.Id(), Deleted, DefaultCenTimeout))
}
package alicloud
import (
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cbn"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCenPrivateZone() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCenPrivateZoneCreate,
Read: resourceAlicloudCenPrivateZoneRead,
Delete: resourceAlicloudCenPrivateZoneDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(6 * time.Minute),
},
Schema: map[string]*schema.Schema{
"access_region_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"cen_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"host_region_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"host_vpc_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudCenPrivateZoneCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
request := cbn.CreateRoutePrivateZoneInCenToVpcRequest()
request.AccessRegionId = d.Get("access_region_id").(string)
request.CenId = d.Get("cen_id").(string)
request.HostRegionId = d.Get("host_region_id").(string)
request.HostVpcId = d.Get("host_vpc_id").(string)
wait := incrementalWait(3*time.Second, 5*time.Second)
err := resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.RoutePrivateZoneInCenToVpc(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "InvalidOperation.CenInstanceStatus", "InvalidOperation.NoChildInstanceEitherRegion"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw)
d.SetId(d.Get("cen_id").(string) + ":" + d.Get("access_region_id").(string))
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cen_private_zone", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, cbnService.CenPrivateZoneStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudCenPrivateZoneRead(d, meta)
}
func resourceAlicloudCenPrivateZoneRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
object, err := cbnService.DescribeCenPrivateZone(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("access_region_id", parts[1])
d.Set("cen_id", parts[0])
d.Set("host_region_id", object.HostRegionId)
d.Set("host_vpc_id", object.HostVpcId)
d.Set("status", object.Status)
return nil
}
func resourceAlicloudCenPrivateZoneDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request := cbn.CreateUnroutePrivateZoneInCenToVpcRequest()
request.AccessRegionId = parts[1]
request.CenId = parts[0]
err = resource.Retry(300*time.Second, func() *resource.RetryError {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.UnroutePrivateZoneInCenToVpc(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "InvalidOperation.CenInstanceStatus"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cbn"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCenRouteEntry() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCenRouteEntryCreate,
Read: resourceAlicloudCenRouteEntryRead,
Delete: resourceAlicloudCenRouteEntryDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"route_table_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"cidr_block": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudCenRouteEntryCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cenService := CenService{client}
cenId := d.Get("instance_id").(string)
vtbId := d.Get("route_table_id").(string)
cidr := d.Get("cidr_block").(string)
childInstanceId, childInstanceType, err := cenService.CreateCenRouteEntryParas(vtbId)
if err != nil {
return WrapError(err)
}
request := cbn.CreatePublishRouteEntriesRequest()
request.RegionId = client.RegionId
request.CenId = cenId
request.ChildInstanceId = childInstanceId
request.ChildInstanceType = childInstanceType
request.ChildInstanceRegionId = client.RegionId
request.ChildInstanceRouteTableId = vtbId
request.DestinationCidrBlock = cidr
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := client.WithCenClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.PublishRouteEntries(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "not in a valid state for the operation"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cen_route_entry", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetId(cenId + COLON_SEPARATED + vtbId + COLON_SEPARATED + cidr)
err = cenService.WaitForCenRouterEntry(d.Id(), PUBLISHED, DefaultCenTimeout)
if err != nil {
return WrapError(err)
}
return resourceAlicloudCenRouteEntryRead(d, meta)
}
func resourceAlicloudCenRouteEntryRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cenService := CenService{client}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
cenId := parts[0]
object, err := cenService.DescribeCenRouteEntry(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
if object.PublishStatus == string(NOPUBLISHED) {
d.SetId("")
return nil
}
d.Set("instance_id", cenId)
d.Set("route_table_id", object.ChildInstanceRouteTableId)
d.Set("cidr_block", object.DestinationCidrBlock)
return nil
}
func resourceAlicloudCenRouteEntryDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cenService := CenService{client}
cenId := d.Get("instance_id").(string)
vtbId := d.Get("route_table_id").(string)
cidr := d.Get("cidr_block").(string)
childInstanceId, childInstanceType, err := cenService.CreateCenRouteEntryParas(vtbId)
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
request := cbn.CreateWithdrawPublishedRouteEntriesRequest()
request.RegionId = client.RegionId
request.CenId = cenId
request.ChildInstanceId = childInstanceId
request.ChildInstanceType = childInstanceType
request.ChildInstanceRegionId = client.RegionId
request.ChildInstanceRouteTableId = vtbId
request.DestinationCidrBlock = cidr
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithCenClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.WithdrawPublishedRouteEntries(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidOperation.CenInstanceStatus", "InternalError"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidOperation.NotFoundRoute", "The instance is not exist"}) {
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(cenService.WaitForCenRouterEntry(d.Id(), Deleted, DefaultCenTimeoutLong))
}
package alicloud
import (
"fmt"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cbn"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCenRouteMap() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCenRouteMapCreate,
Read: resourceAlicloudCenRouteMapRead,
Update: resourceAlicloudCenRouteMapUpdate,
Delete: resourceAlicloudCenRouteMapDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(6 * time.Minute),
},
Schema: map[string]*schema.Schema{
"as_path_match_mode": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Include", "Complete"}, false),
},
"cen_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"cen_region_id": {
Type: schema.TypeString,
Required: true,
},
"cidr_match_mode": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Include", "Complete"}, false),
},
"community_match_mode": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Include", "Complete", "Contain"}, false),
},
"community_operate_mode": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Additive", "Replace"}, false),
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"destination_child_instance_types": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"destination_cidr_blocks": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"destination_instance_ids": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"destination_instance_ids_reverse_match": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"destination_route_table_ids": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"map_result": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"Permit", "Deny"}, false),
},
"match_asns": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"match_community_set": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"next_priority": {
Type: schema.TypeInt,
Optional: true,
},
"operate_community_set": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"preference": {
Type: schema.TypeInt,
Optional: true,
},
"prepend_as_path": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"priority": {
Type: schema.TypeInt,
Required: true,
},
"route_map_id": {
Type: schema.TypeString,
Computed: true,
ForceNew: true,
},
"route_types": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"source_child_instance_types": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"source_instance_ids": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"source_instance_ids_reverse_match": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"source_region_ids": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"source_route_table_ids": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"transmit_direction": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"RegionIn", "RegionOut"}, false),
},
},
}
}
func resourceAlicloudCenRouteMapCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
request := cbn.CreateCreateCenRouteMapRequest()
if v, ok := d.GetOk("as_path_match_mode"); ok {
request.AsPathMatchMode = v.(string)
}
request.CenId = d.Get("cen_id").(string)
request.CenRegionId = d.Get("cen_region_id").(string)
if v, ok := d.GetOk("cidr_match_mode"); ok {
request.CidrMatchMode = v.(string)
}
if v, ok := d.GetOk("community_match_mode"); ok {
request.CommunityMatchMode = v.(string)
}
if v, ok := d.GetOk("community_operate_mode"); ok {
request.CommunityOperateMode = v.(string)
}
if v, ok := d.GetOk("description"); ok {
request.Description = v.(string)
}
if v, ok := d.GetOk("destination_child_instance_types"); ok {
destinationChildInstanceTypes := expandStringList(v.(*schema.Set).List())
request.DestinationChildInstanceTypes = &destinationChildInstanceTypes
}
if v, ok := d.GetOk("destination_cidr_blocks"); ok {
destinationCidrBlocks := expandStringList(v.(*schema.Set).List())
request.DestinationCidrBlocks = &destinationCidrBlocks
}
if v, ok := d.GetOk("destination_instance_ids"); ok {
destinationInstanceIds := expandStringList(v.(*schema.Set).List())
request.DestinationInstanceIds = &destinationInstanceIds
}
if v, ok := d.GetOkExists("destination_instance_ids_reverse_match"); ok {
request.DestinationInstanceIdsReverseMatch = requests.NewBoolean(v.(bool))
}
if v, ok := d.GetOk("destination_route_table_ids"); ok {
destinationRouteTableIds := expandStringList(v.(*schema.Set).List())
request.DestinationRouteTableIds = &destinationRouteTableIds
}
request.MapResult = d.Get("map_result").(string)
if v, ok := d.GetOk("match_asns"); ok {
matchAsns := expandStringList(v.(*schema.Set).List())
request.MatchAsns = &matchAsns
}
if v, ok := d.GetOk("match_community_set"); ok {
matchCommunitySet := expandStringList(v.(*schema.Set).List())
request.MatchCommunitySet = &matchCommunitySet
}
if v, ok := d.GetOk("next_priority"); ok {
request.NextPriority = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("operate_community_set"); ok {
operateCommunitySet := expandStringList(v.(*schema.Set).List())
request.OperateCommunitySet = &operateCommunitySet
}
if v, ok := d.GetOk("preference"); ok {
request.Preference = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("prepend_as_path"); ok {
prependAsPath := expandStringList(v.(*schema.Set).List())
request.PrependAsPath = &prependAsPath
}
request.Priority = requests.NewInteger(d.Get("priority").(int))
if v, ok := d.GetOk("route_types"); ok {
routeTypes := expandStringList(v.(*schema.Set).List())
request.RouteTypes = &routeTypes
}
if v, ok := d.GetOk("source_child_instance_types"); ok {
sourceChildInstanceTypes := expandStringList(v.(*schema.Set).List())
request.SourceChildInstanceTypes = &sourceChildInstanceTypes
}
if v, ok := d.GetOk("source_instance_ids"); ok {
sourceInstanceIds := expandStringList(v.(*schema.Set).List())
request.SourceInstanceIds = &sourceInstanceIds
}
if v, ok := d.GetOkExists("source_instance_ids_reverse_match"); ok {
request.SourceInstanceIdsReverseMatch = requests.NewBoolean(v.(bool))
}
if v, ok := d.GetOk("source_region_ids"); ok {
sourceRegionIds := expandStringList(v.(*schema.Set).List())
request.SourceRegionIds = &sourceRegionIds
}
if v, ok := d.GetOk("source_route_table_ids"); ok {
sourceRouteTableIds := expandStringList(v.(*schema.Set).List())
request.SourceRouteTableIds = &sourceRouteTableIds
}
request.TransmitDirection = d.Get("transmit_direction").(string)
wait := incrementalWait(3*time.Second, 5*time.Second)
err := resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.CreateCenRouteMap(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw)
response, _ := raw.(*cbn.CreateCenRouteMapResponse)
d.SetId(fmt.Sprintf("%v:%v", request.CenId, response.RouteMapId))
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cen_route_map", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, cbnService.CenRouteMapStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudCenRouteMapRead(d, meta)
}
func resourceAlicloudCenRouteMapRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
object, err := cbnService.DescribeCenRouteMap(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("cen_id", parts[0])
d.Set("as_path_match_mode", object.AsPathMatchMode)
d.Set("cen_region_id", object.CenRegionId)
d.Set("cidr_match_mode", object.CidrMatchMode)
d.Set("community_match_mode", object.CommunityMatchMode)
d.Set("community_operate_mode", object.CommunityOperateMode)
d.Set("description", object.Description)
d.Set("destination_child_instance_types", object.DestinationChildInstanceTypes.DestinationChildInstanceType)
d.Set("destination_cidr_blocks", object.DestinationCidrBlocks.DestinationCidrBlock)
d.Set("destination_instance_ids", object.DestinationInstanceIds.DestinationInstanceId)
d.Set("destination_instance_ids_reverse_match", object.DestinationInstanceIdsReverseMatch)
d.Set("destination_route_table_ids", object.DestinationRouteTableIds.DestinationRouteTableId)
d.Set("map_result", object.MapResult)
d.Set("match_asns", object.MatchAsns.MatchAsn)
d.Set("match_community_set", object.MatchCommunitySet.MatchCommunity)
d.Set("next_priority", object.NextPriority)
d.Set("operate_community_set", object.OperateCommunitySet.OperateCommunity)
d.Set("preference", object.Preference)
d.Set("prepend_as_path", object.PrependAsPath.AsPath)
d.Set("priority", object.Priority)
d.Set("route_types", object.RouteTypes.RouteType)
d.Set("source_child_instance_types", object.SourceChildInstanceTypes.SourceChildInstanceType)
d.Set("source_instance_ids", object.SourceInstanceIds.SourceInstanceId)
d.Set("source_instance_ids_reverse_match", object.SourceInstanceIdsReverseMatch)
d.Set("source_region_ids", object.SourceRegionIds.SourceRegionId)
d.Set("source_route_table_ids", object.SourceRouteTableIds.SourceRouteTableId)
d.Set("status", object.Status)
d.Set("transmit_direction", object.TransmitDirection)
return nil
}
func resourceAlicloudCenRouteMapUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
update := false
request := cbn.CreateModifyCenRouteMapRequest()
request.CenId = parts[0]
request.RouteMapId = parts[1]
if d.HasChange("cen_region_id") {
update = true
}
request.CenRegionId = d.Get("cen_region_id").(string)
if d.HasChange("map_result") {
update = true
}
request.MapResult = d.Get("map_result").(string)
if d.HasChange("priority") {
update = true
}
request.Priority = requests.NewInteger(d.Get("priority").(int))
if d.HasChange("as_path_match_mode") {
update = true
request.AsPathMatchMode = d.Get("as_path_match_mode").(string)
}
if d.HasChange("cidr_match_mode") {
update = true
request.CidrMatchMode = d.Get("cidr_match_mode").(string)
}
if d.HasChange("community_match_mode") {
update = true
request.CommunityMatchMode = d.Get("community_match_mode").(string)
}
if d.HasChange("community_operate_mode") {
update = true
request.CommunityOperateMode = d.Get("community_operate_mode").(string)
}
if d.HasChange("description") {
update = true
request.Description = d.Get("description").(string)
}
if d.HasChange("destination_child_instance_types") {
update = true
destinationChildInstanceTypes := expandStringList(d.Get("destination_child_instance_types").(*schema.Set).List())
request.DestinationChildInstanceTypes = &destinationChildInstanceTypes
}
if d.HasChange("destination_cidr_blocks") {
update = true
destinationCidrBlocks := expandStringList(d.Get("destination_cidr_blocks").(*schema.Set).List())
request.DestinationCidrBlocks = &destinationCidrBlocks
}
if d.HasChange("destination_instance_ids") {
update = true
destinationInstanceIds := expandStringList(d.Get("destination_instance_ids").(*schema.Set).List())
request.DestinationInstanceIds = &destinationInstanceIds
}
if d.HasChange("destination_instance_ids_reverse_match") {
update = true
request.DestinationInstanceIdsReverseMatch = requests.NewBoolean(d.Get("destination_instance_ids_reverse_match").(bool))
}
if d.HasChange("destination_route_table_ids") {
update = true
destinationRouteTableIds := expandStringList(d.Get("destination_route_table_ids").(*schema.Set).List())
request.DestinationRouteTableIds = &destinationRouteTableIds
}
if d.HasChange("match_asns") {
update = true
matchAsns := expandStringList(d.Get("match_asns").(*schema.Set).List())
request.MatchAsns = &matchAsns
}
if d.HasChange("match_community_set") {
update = true
matchCommunitySet := expandStringList(d.Get("match_community_set").(*schema.Set).List())
request.MatchCommunitySet = &matchCommunitySet
}
if d.HasChange("next_priority") {
update = true
request.NextPriority = requests.NewInteger(d.Get("next_priority").(int))
}
if d.HasChange("operate_community_set") {
update = true
operateCommunitySet := expandStringList(d.Get("operate_community_set").(*schema.Set).List())
request.OperateCommunitySet = &operateCommunitySet
}
if d.HasChange("preference") {
update = true
request.Preference = requests.NewInteger(d.Get("preference").(int))
}
if d.HasChange("prepend_as_path") {
update = true
prependAsPath := expandStringList(d.Get("prepend_as_path").(*schema.Set).List())
request.PrependAsPath = &prependAsPath
}
if d.HasChange("route_types") {
update = true
routeTypes := expandStringList(d.Get("route_types").(*schema.Set).List())
request.RouteTypes = &routeTypes
}
if d.HasChange("source_child_instance_types") {
update = true
sourceChildInstanceTypes := expandStringList(d.Get("source_child_instance_types").(*schema.Set).List())
request.SourceChildInstanceTypes = &sourceChildInstanceTypes
}
if d.HasChange("source_instance_ids") {
update = true
sourceInstanceIds := expandStringList(d.Get("source_instance_ids").(*schema.Set).List())
request.SourceInstanceIds = &sourceInstanceIds
}
if d.HasChange("source_instance_ids_reverse_match") {
update = true
request.SourceInstanceIdsReverseMatch = requests.NewBoolean(d.Get("source_instance_ids_reverse_match").(bool))
}
if d.HasChange("source_region_ids") {
update = true
sourceRegionIds := expandStringList(d.Get("source_region_ids").(*schema.Set).List())
request.SourceRegionIds = &sourceRegionIds
}
if d.HasChange("source_route_table_ids") {
update = true
sourceRouteTableIds := expandStringList(d.Get("source_route_table_ids").(*schema.Set).List())
request.SourceRouteTableIds = &sourceRouteTableIds
}
if update {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.ModifyCenRouteMap(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudCenRouteMapRead(d, meta)
}
func resourceAlicloudCenRouteMapDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request := cbn.CreateDeleteCenRouteMapRequest()
request.CenId = parts[0]
request.RouteMapId = parts[1]
request.CenRegionId = d.Get("cen_region_id").(string)
err = resource.Retry(300*time.Second, func() *resource.RetryError {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DeleteCenRouteMap(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "IncorrectStatus.RouteMap", "Throttling.User"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cbn"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCenRouteService() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCenRouteServiceCreate,
Read: resourceAlicloudCenRouteServiceRead,
Delete: resourceAlicloudCenRouteServiceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(6 * time.Minute),
Delete: schema.DefaultTimeout(6 * time.Minute),
},
Schema: map[string]*schema.Schema{
"access_region_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"cen_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"host": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"host_region_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"host_vpc_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudCenRouteServiceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
request := cbn.CreateResolveAndRouteServiceInCenRequest()
accessRegionId := d.Get("access_region_id").(string)
request.AccessRegionIds = &[]string{accessRegionId}
request.CenId = d.Get("cen_id").(string)
if v, ok := d.GetOk("description"); ok {
request.Description = v.(string)
}
request.Host = d.Get("host").(string)
request.HostRegionId = d.Get("host_region_id").(string)
request.HostVpcId = d.Get("host_vpc_id").(string)
wait := incrementalWait(3*time.Second, 5*time.Second)
err := resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.ResolveAndRouteServiceInCen(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw)
d.SetId(fmt.Sprintf("%v:%v:%v:%v", request.CenId, request.HostRegionId, request.Host, accessRegionId))
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cen_route_service", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, cbnService.CenRouteServiceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudCenRouteServiceRead(d, meta)
}
func resourceAlicloudCenRouteServiceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
object, err := cbnService.DescribeCenRouteService(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cen_route_service cbnService.DescribeCenRouteService Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 4)
if err != nil {
return WrapError(err)
}
d.Set("access_region_id", parts[3])
d.Set("cen_id", parts[0])
d.Set("host", parts[2])
d.Set("host_region_id", parts[1])
d.Set("description", object.Description)
d.Set("host_vpc_id", object.HostVpcId)
d.Set("status", object.Status)
return nil
}
func resourceAlicloudCenRouteServiceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 4)
if err != nil {
return WrapError(err)
}
request := cbn.CreateDeleteRouteServiceInCenRequest()
request.AccessRegionId = parts[3]
request.CenId = parts[0]
request.Host = parts[2]
request.HostRegionId = parts[1]
request.HostVpcId = d.Get("host_vpc_id").(string)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DeleteRouteServiceInCen(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "InvalidOperation.CenInstanceStatus", "InvalidOperation.CloudRouteStatusNotAllow"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCenTransitRouter() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCenTransitRouterCreate,
Read: resourceAlicloudCenTransitRouterRead,
Update: resourceAlicloudCenTransitRouterUpdate,
Delete: resourceAlicloudCenTransitRouterDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(3 * time.Minute),
Delete: schema.DefaultTimeout(3 * time.Minute),
Update: schema.DefaultTimeout(3 * time.Minute),
},
Schema: map[string]*schema.Schema{
"cen_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_description": {
Type: schema.TypeString,
Optional: true,
},
"transit_router_name": {
Type: schema.TypeString,
Optional: true,
},
"transit_router_id": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudCenTransitRouterCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
var response map[string]interface{}
action := "CreateTransitRouter"
request := make(map[string]interface{})
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
request["CenId"] = d.Get("cen_id")
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("transit_router_description"); ok {
request["TransitRouterDescription"] = v
}
if v, ok := d.GetOk("transit_router_name"); ok {
request["TransitRouterName"] = v
}
request["ClientToken"] = buildClientToken("CreateTransitRouter")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cen_transit_router", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprintf("%v:%v", request["CenId"], response["TransitRouterId"]))
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, cbnService.CenTransitRouterStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudCenTransitRouterRead(d, meta)
}
func resourceAlicloudCenTransitRouterRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
object, err := cbnService.DescribeCenTransitRouter(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cen_transit_router cbnService.DescribeCenTransitRouter Failed!!! %s", err)
d.SetId("")
return nil
}
if IsExpectedErrors(err, []string{"Operation.Blocking", "Throttling.User", "ParameterCenInstanceId"}) {
return nil
}
return nil
}
parts, err1 := ParseResourceId(d.Id(), 2)
if err1 != nil {
return WrapError(err1)
}
d.Set("cen_id", parts[0])
d.Set("status", object["Status"])
d.Set("transit_router_description", object["TransitRouterDescription"])
d.Set("transit_router_name", object["TransitRouterName"])
d.Set("type", object["Type"])
d.Set("transit_router_id", object["TransitRouterId"])
return nil
}
func resourceAlicloudCenTransitRouterUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
update := false
parts, err1 := ParseResourceId(d.Id(), 2)
if err1 != nil {
return WrapError(err1)
}
request := map[string]interface{}{
"TransitRouterId": parts[1],
}
request["RegionId"] = client.RegionId
if d.HasChange("transit_router_description") {
update = true
request["TransitRouterDescription"] = d.Get("transit_router_description")
}
if d.HasChange("transit_router_name") {
update = true
request["TransitRouterName"] = d.Get("transit_router_name")
}
if update {
if _, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = d.Get("dry_run")
}
action := "UpdateTransitRouter"
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, cbnService.CenTransitRouterStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudCenTransitRouterRead(d, meta)
}
func resourceAlicloudCenTransitRouterDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteTransitRouter"
var response map[string]interface{}
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
parts, err1 := ParseResourceId(d.Id(), 2)
if err1 != nil {
return WrapError(err1)
}
request := map[string]interface{}{
"TransitRouterId": parts[1],
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ParameterInstanceId"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCenTransitRouterPeerAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCenTransitRouterPeerAttachmentCreate,
Read: resourceAlicloudCenTransitRouterPeerAttachmentRead,
Update: resourceAlicloudCenTransitRouterPeerAttachmentUpdate,
Delete: resourceAlicloudCenTransitRouterPeerAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(3 * time.Minute),
Delete: schema.DefaultTimeout(3 * time.Minute),
Update: schema.DefaultTimeout(3 * time.Minute),
},
Schema: map[string]*schema.Schema{
"auto_publish_route_enabled": {
Type: schema.TypeBool,
Optional: true,
},
"bandwidth": {
Type: schema.TypeInt,
Optional: true,
},
"cen_bandwidth_package_id": {
Type: schema.TypeString,
Optional: true,
},
"cen_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"peer_transit_router_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"peer_transit_router_region_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"resource_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "TR",
},
"route_table_association_enabled": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"route_table_propagation_enabled": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_attachment_description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"transit_router_attachment_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 128),
},
"transit_router_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"transit_router_attachment_id": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudCenTransitRouterPeerAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
var response map[string]interface{}
action := "CreateTransitRouterPeerAttachment"
request := make(map[string]interface{})
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("auto_publish_route_enabled"); ok {
request["AutoPublishRouteEnabled"] = v
}
if v, ok := d.GetOk("bandwidth"); ok {
request["Bandwidth"] = v
}
if v, ok := d.GetOk("cen_bandwidth_package_id"); ok {
request["CenBandwidthPackageId"] = v
}
request["CenId"] = d.Get("cen_id")
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["PeerTransitRouterId"] = d.Get("peer_transit_router_id")
request["PeerTransitRouterRegionId"] = d.Get("peer_transit_router_region_id")
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_type"); ok {
request["ResourceType"] = v
}
if v, ok := d.GetOkExists("route_table_association_enabled"); ok {
request["RouteTableAssociationEnabled"] = v
}
if v, ok := d.GetOkExists("route_table_propagation_enabled"); ok {
request["RouteTablePropagationEnabled"] = v
}
if v, ok := d.GetOk("transit_router_attachment_description"); ok {
request["TransitRouterAttachmentDescription"] = v
}
if v, ok := d.GetOk("transit_router_attachment_name"); ok {
request["TransitRouterAttachmentName"] = v
}
if v, ok := d.GetOk("transit_router_id"); ok {
request["TransitRouterId"] = v
}
request["ClientToken"] = buildClientToken("CreateTransitRouterPeerAttachment")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cen_transit_router_peer_attachment", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprintf("%v:%v", request["CenId"], response["TransitRouterAttachmentId"]))
stateConf := BuildStateConf([]string{}, []string{"Attached"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, cbnService.CenTransitRouterPeerAttachmentStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudCenTransitRouterPeerAttachmentRead(d, meta)
}
func resourceAlicloudCenTransitRouterPeerAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
object, err := cbnService.DescribeCenTransitRouterPeerAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cen_transit_router_peer_attachment cbnService.DescribeCenTransitRouterPeerAttachment Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err1 := ParseResourceId(d.Id(), 2)
if err1 != nil {
return WrapError(err1)
}
d.Set("cen_id", parts[0])
d.Set("transit_router_attachment_id", parts[1])
d.Set("auto_publish_route_enabled", object["AutoPublishRouteEnabled"])
d.Set("bandwidth", formatInt(object["Bandwidth"]))
d.Set("cen_bandwidth_package_id", object["CenBandwidthPackageId"])
d.Set("peer_transit_router_id", object["PeerTransitRouterId"])
d.Set("peer_transit_router_region_id", object["PeerTransitRouterRegionId"])
d.Set("resource_type", object["ResourceType"])
d.Set("status", object["Status"])
d.Set("transit_router_attachment_description", object["TransitRouterAttachmentDescription"])
d.Set("transit_router_attachment_name", object["TransitRouterAttachmentName"])
d.Set("transit_router_id", object["TransitRouterId"])
return nil
}
func resourceAlicloudCenTransitRouterPeerAttachmentUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
update := false
parts, err1 := ParseResourceId(d.Id(), 2)
if err1 != nil {
return WrapError(err1)
}
request := map[string]interface{}{
"TransitRouterAttachmentId": parts[1],
}
if d.HasChange("auto_publish_route_enabled") || d.IsNewResource() {
update = true
request["AutoPublishRouteEnabled"] = d.Get("auto_publish_route_enabled")
}
if d.HasChange("bandwidth") {
update = true
request["Bandwidth"] = d.Get("bandwidth")
}
if d.HasChange("cen_bandwidth_package_id") {
update = true
request["CenBandwidthPackageId"] = d.Get("cen_bandwidth_package_id")
}
if d.HasChange("transit_router_attachment_description") {
update = true
request["TransitRouterAttachmentDescription"] = d.Get("transit_router_attachment_description")
}
if d.HasChange("transit_router_attachment_name") {
update = true
request["TransitRouterAttachmentName"] = d.Get("transit_router_attachment_name")
}
if update {
if _, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = d.Get("dry_run")
}
action := "UpdateTransitRouterPeerAttachmentAttribute"
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
stateConf := BuildStateConf([]string{}, []string{"Attached"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, cbnService.CenTransitRouterPeerAttachmentStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudCenTransitRouterPeerAttachmentRead(d, meta)
}
func resourceAlicloudCenTransitRouterPeerAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
action := "DeleteTransitRouterPeerAttachment"
var response map[string]interface{}
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
parts, err1 := ParseResourceId(d.Id(), 2)
if err1 != nil {
return WrapError(err1)
}
request := map[string]interface{}{
"TransitRouterAttachmentId": parts[1],
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
if v, ok := d.GetOk("resource_type"); ok {
request["ResourceType"] = v
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, cbnService.CenTransitRouterPeerAttachmentStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCenTransitRouterRouteEntry() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCenTransitRouterRouteEntryCreate,
Read: resourceAlicloudCenTransitRouterRouteEntryRead,
Update: resourceAlicloudCenTransitRouterRouteEntryUpdate,
Delete: resourceAlicloudCenTransitRouterRouteEntryDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(3 * time.Minute),
Delete: schema.DefaultTimeout(3 * time.Minute),
Update: schema.DefaultTimeout(3 * time.Minute),
},
Schema: map[string]*schema.Schema{
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_route_entry_description": {
Type: schema.TypeString,
Optional: true,
},
"transit_router_route_entry_destination_cidr_block": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"transit_router_route_entry_name": {
Type: schema.TypeString,
Optional: true,
},
"transit_router_route_entry_next_hop_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"transit_router_route_entry_next_hop_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Attachment", "BlackHole"}, false),
},
"transit_router_route_table_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"transit_router_route_entry_id": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudCenTransitRouterRouteEntryCreate(d *schema.ResourceData, meta interface{}) error {
time.Sleep(60 * time.Second)
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
var response map[string]interface{}
action := "CreateTransitRouterRouteEntry"
request := make(map[string]interface{})
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
if v, ok := d.GetOk("transit_router_route_entry_description"); ok {
request["TransitRouterRouteEntryDescription"] = v
}
request["TransitRouterRouteEntryDestinationCidrBlock"] = d.Get("transit_router_route_entry_destination_cidr_block")
if v, ok := d.GetOk("transit_router_route_entry_name"); ok {
request["TransitRouterRouteEntryName"] = v
}
if v, ok := d.GetOk("transit_router_route_entry_next_hop_id"); ok {
request["TransitRouterRouteEntryNextHopId"] = v
}
request["TransitRouterRouteEntryNextHopType"] = d.Get("transit_router_route_entry_next_hop_type")
request["TransitRouterRouteTableId"] = d.Get("transit_router_route_table_id")
request["ClientToken"] = buildClientToken("CreateTransitRouterRouteEntry")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cen_transit_router_route_entry", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprintf("%v:%v", request["TransitRouterRouteTableId"], response["TransitRouterRouteEntryId"]))
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, cbnService.CenTransitRouterRouteEntryStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudCenTransitRouterRouteEntryRead(d, meta)
}
func resourceAlicloudCenTransitRouterRouteEntryRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
object, err := cbnService.DescribeCenTransitRouterRouteEntry(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cen_transit_router_route_entry cbnService.DescribeCenTransitRouterRouteEntry Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err1 := ParseResourceId(d.Id(), 2)
if err1 != nil {
return WrapError(err1)
}
d.Set("status", object["TransitRouterRouteEntryStatus"])
d.Set("transit_router_route_entry_description", object["TransitRouterRouteEntryDescription"])
d.Set("transit_router_route_entry_destination_cidr_block", object["TransitRouterRouteEntryDestinationCidrBlock"])
d.Set("transit_router_route_entry_name", object["TransitRouterRouteEntryName"])
d.Set("transit_router_route_entry_next_hop_id", object["TransitRouterRouteEntryNextHopId"])
d.Set("transit_router_route_entry_next_hop_type", object["TransitRouterRouteEntryNextHopType"])
d.Set("transit_router_route_entry_id", object["TransitRouterRouteEntryId"])
d.Set("transit_router_route_table_id", parts[0])
return nil
}
func resourceAlicloudCenTransitRouterRouteEntryUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
var response map[string]interface{}
parts, err1 := ParseResourceId(d.Id(), 2)
if err1 != nil {
return WrapError(err1)
}
update := false
request := map[string]interface{}{
"TransitRouterRouteEntryId": parts[1],
}
if d.HasChange("transit_router_route_entry_description") {
update = true
request["TransitRouterRouteEntryDescription"] = d.Get("transit_router_route_entry_description")
}
if d.HasChange("transit_router_route_entry_name") {
update = true
request["TransitRouterRouteEntryName"] = d.Get("transit_router_route_entry_name")
}
if update {
if _, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = d.Get("dry_run")
}
action := "UpdateTransitRouterRouteEntry"
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("UpdateTransitRouterRouteEntry")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, cbnService.CenTransitRouterRouteEntryStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudCenTransitRouterRouteEntryRead(d, meta)
}
func resourceAlicloudCenTransitRouterRouteEntryDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteTransitRouterRouteEntry"
var response map[string]interface{}
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
parts, err1 := ParseResourceId(d.Id(), 2)
if err1 != nil {
return WrapError(err1)
}
request := map[string]interface{}{
"TransitRouterRouteEntryId": parts[1],
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
if v, ok := d.GetOk("transit_router_route_entry_next_hop_id"); ok {
request["TransitRouterRouteEntryNextHopId"] = v
}
request["TransitRouterRouteEntryNextHopType"] = d.Get("transit_router_route_entry_next_hop_type")
request["ClientToken"] = buildClientToken("DeleteTransitRouterRouteEntry")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"IllegalParam.TransitRouterRouteEntryId"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCenTransitRouterRouteTable() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCenTransitRouterRouteTableCreate,
Read: resourceAlicloudCenTransitRouterRouteTableRead,
Update: resourceAlicloudCenTransitRouterRouteTableUpdate,
Delete: resourceAlicloudCenTransitRouterRouteTableDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(3 * time.Minute),
Delete: schema.DefaultTimeout(3 * time.Minute),
Update: schema.DefaultTimeout(3 * time.Minute),
},
Schema: map[string]*schema.Schema{
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"transit_router_route_table_id": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_route_table_type": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_route_table_description": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"transit_router_route_table_name": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudCenTransitRouterRouteTableCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
var response map[string]interface{}
action := "CreateTransitRouterRouteTable"
request := make(map[string]interface{})
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["TransitRouterId"] = d.Get("transit_router_id")
if v, ok := d.GetOk("transit_router_route_table_description"); ok {
request["TransitRouterRouteTableDescription"] = v
}
if v, ok := d.GetOk("transit_router_route_table_name"); ok {
request["TransitRouterRouteTableName"] = v
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cen_transit_router_route_table", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprintf("%v:%v", request["TransitRouterId"], response["TransitRouterRouteTableId"]))
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, cbnService.CenTransitRouterRouteTableStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudCenTransitRouterRouteTableRead(d, meta)
}
func resourceAlicloudCenTransitRouterRouteTableRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
object, err := cbnService.DescribeCenTransitRouterRouteTable(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cen_transit_router_route_table cbnService.DescribeCenTransitRouterRouteTable Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err1 := ParseResourceId(d.Id(), 2)
if err1 != nil {
return WrapError(err1)
}
d.Set("transit_router_id", parts[0])
d.Set("status", object["TransitRouterRouteTableStatus"])
d.Set("transit_router_route_table_description", object["TransitRouterRouteTableDescription"])
d.Set("transit_router_route_table_name", object["TransitRouterRouteTableName"])
d.Set("transit_router_route_table_id", object["TransitRouterRouteTableId"])
d.Set("transit_router_route_table_type", object["TransitRouterRouteTableType"])
return nil
}
func resourceAlicloudCenTransitRouterRouteTableUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
parts, err1 := ParseResourceId(d.Id(), 2)
if err1 != nil {
return WrapError(err1)
}
update := false
request := map[string]interface{}{
"TransitRouterRouteTableId": parts[1],
}
if d.HasChange("transit_router_route_table_description") {
update = true
request["TransitRouterRouteTableDescription"] = d.Get("transit_router_route_table_description")
}
if d.HasChange("transit_router_route_table_name") {
update = true
request["TransitRouterRouteTableName"] = d.Get("transit_router_route_table_name")
}
if update {
if _, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = d.Get("dry_run")
}
action := "UpdateTransitRouterRouteTable"
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, cbnService.CenTransitRouterRouteTableStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudCenTransitRouterRouteTableRead(d, meta)
}
func resourceAlicloudCenTransitRouterRouteTableDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
action := "DeleteTransitRouterRouteTable"
var response map[string]interface{}
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
parts, err1 := ParseResourceId(d.Id(), 2)
if err1 != nil {
return WrapError(err1)
}
request := map[string]interface{}{
"TransitRouterRouteTableId": parts[1],
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["ClientToken"] = buildClientToken("DeleteTransitRouterRouteTable")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidTransitRouterRouteTableId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, cbnService.CenTransitRouterRouteTableStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCenTransitRouterRouteTableAssociation() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCenTransitRouterRouteTableAssociationCreate,
Read: resourceAlicloudCenTransitRouterRouteTableAssociationRead,
Update: resourceAlicloudCenTransitRouterRouteTableAssociationUpdate,
Delete: resourceAlicloudCenTransitRouterRouteTableAssociationDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(3 * time.Minute),
Delete: schema.DefaultTimeout(3 * time.Minute),
},
Schema: map[string]*schema.Schema{
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_attachment_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"transit_router_route_table_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudCenTransitRouterRouteTableAssociationCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
var response map[string]interface{}
action := "AssociateTransitRouterAttachmentWithRouteTable"
request := make(map[string]interface{})
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["TransitRouterAttachmentId"] = d.Get("transit_router_attachment_id")
request["TransitRouterRouteTableId"] = d.Get("transit_router_route_table_id")
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cen_transit_router_route_table_association", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["TransitRouterAttachmentId"], ":", request["TransitRouterRouteTableId"]))
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, cbnService.CenTransitRouterRouteTableAssociationStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudCenTransitRouterRouteTableAssociationRead(d, meta)
}
func resourceAlicloudCenTransitRouterRouteTableAssociationRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
object, err := cbnService.DescribeCenTransitRouterRouteTableAssociation(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cen_transit_router_route_table_association cbnService.DescribeCenTransitRouterRouteTableAssociation Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("transit_router_attachment_id", parts[0])
d.Set("transit_router_route_table_id", parts[1])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudCenTransitRouterRouteTableAssociationUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return resourceAlicloudCenTransitRouterRouteTableAssociationRead(d, meta)
}
func resourceAlicloudCenTransitRouterRouteTableAssociationDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
cbnService := CbnService{client}
action := "DissociateTransitRouterAttachmentFromRouteTable"
var response map[string]interface{}
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"TransitRouterAttachmentId": parts[0],
"TransitRouterRouteTableId": parts[1],
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, cbnService.CenTransitRouterRouteTableAssociationStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCenTransitRouterRouteTablePropagation() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCenTransitRouterRouteTablePropagationCreate,
Read: resourceAlicloudCenTransitRouterRouteTablePropagationRead,
Update: resourceAlicloudCenTransitRouterRouteTablePropagationUpdate,
Delete: resourceAlicloudCenTransitRouterRouteTablePropagationDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(3 * time.Minute),
Delete: schema.DefaultTimeout(3 * time.Minute),
},
Schema: map[string]*schema.Schema{
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_attachment_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"transit_router_route_table_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudCenTransitRouterRouteTablePropagationCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
var response map[string]interface{}
action := "EnableTransitRouterRouteTablePropagation"
request := make(map[string]interface{})
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["TransitRouterAttachmentId"] = d.Get("transit_router_attachment_id")
request["TransitRouterRouteTableId"] = d.Get("transit_router_route_table_id")
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cen_transit_router_route_table_propagation", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["TransitRouterAttachmentId"], ":", request["TransitRouterRouteTableId"]))
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, cbnService.CenTransitRouterRouteTablePropagationStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudCenTransitRouterRouteTablePropagationRead(d, meta)
}
func resourceAlicloudCenTransitRouterRouteTablePropagationRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
object, err := cbnService.DescribeCenTransitRouterRouteTablePropagation(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cen_transit_router_route_table_propagation cbnService.DescribeCenTransitRouterRouteTablePropagation Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("transit_router_attachment_id", parts[0])
d.Set("transit_router_route_table_id", parts[1])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudCenTransitRouterRouteTablePropagationUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return resourceAlicloudCenTransitRouterRouteTablePropagationRead(d, meta)
}
func resourceAlicloudCenTransitRouterRouteTablePropagationDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
cbnService := CbnService{client}
action := "DisableTransitRouterRouteTablePropagation"
var response map[string]interface{}
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"TransitRouterAttachmentId": parts[0],
"TransitRouterRouteTableId": parts[1],
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, cbnService.CenTransitRouterRouteTablePropagationStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCenTransitRouterVbrAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCenTransitRouterVbrAttachmentCreate,
Read: resourceAlicloudCenTransitRouterVbrAttachmentRead,
Update: resourceAlicloudCenTransitRouterVbrAttachmentUpdate,
Delete: resourceAlicloudCenTransitRouterVbrAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(3 * time.Minute),
Delete: schema.DefaultTimeout(3 * time.Minute),
Update: schema.DefaultTimeout(3 * time.Minute),
},
Schema: map[string]*schema.Schema{
"auto_publish_route_enabled": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"cen_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"resource_type": {
Type: schema.TypeString,
Optional: true,
Default: "VBR",
},
"transit_router_attachment_id": {
Type: schema.TypeString,
Computed: true,
},
"route_table_association_enabled": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"route_table_propagation_enabled": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_attachment_description": {
Type: schema.TypeString,
Optional: true,
},
"transit_router_attachment_name": {
Type: schema.TypeString,
Optional: true,
},
"transit_router_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vbr_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"vbr_owner_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
},
}
}
func resourceAlicloudCenTransitRouterVbrAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
var response map[string]interface{}
action := "CreateTransitRouterVbrAttachment"
request := make(map[string]interface{})
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("auto_publish_route_enabled"); ok {
request["AutoPublishRouteEnabled"] = v
}
request["CenId"] = d.Get("cen_id")
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_type"); ok {
request["ResourceType"] = v
}
if v, ok := d.GetOkExists("route_table_association_enabled"); ok {
request["RouteTableAssociationEnabled"] = v
}
if v, ok := d.GetOkExists("route_table_propagation_enabled"); ok {
request["RouteTablePropagationEnabled"] = v
}
if v, ok := d.GetOk("transit_router_attachment_description"); ok {
request["TransitRouterAttachmentDescription"] = v
}
if v, ok := d.GetOk("transit_router_attachment_name"); ok {
request["TransitRouterAttachmentName"] = v
}
if v, ok := d.GetOk("transit_router_id"); ok {
request["TransitRouterId"] = v
}
request["VbrId"] = d.Get("vbr_id")
if v, ok := d.GetOk("vbr_owner_id"); ok {
request["VbrOwnerId"] = v
}
request["ClientToken"] = buildClientToken("CreateTransitRouterVbrAttachment")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cen_transit_router_vbr_attachment", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprintf("%v:%v", request["CenId"], response["TransitRouterAttachmentId"]))
stateConf := BuildStateConf([]string{}, []string{"Attached"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, cbnService.CenTransitRouterVbrAttachmentStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudCenTransitRouterVbrAttachmentRead(d, meta)
}
func resourceAlicloudCenTransitRouterVbrAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
object, err := cbnService.DescribeCenTransitRouterVbrAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cen_transit_router_vbr_attachment cbnService.DescribeCenTransitRouterVbrAttachment Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err1 := ParseResourceId(d.Id(), 2)
if err1 != nil {
return WrapError(err1)
}
d.Set("cen_id", parts[0])
d.Set("auto_publish_route_enabled", object["AutoPublishRouteEnabled"])
d.Set("status", object["Status"])
d.Set("transit_router_attachment_id", object["TransitRouterAttachmentId"])
d.Set("transit_router_attachment_description", object["TransitRouterAttachmentDescription"])
d.Set("transit_router_attachment_name", object["TransitRouterAttachmentName"])
d.Set("transit_router_id", object["TransitRouterId"])
d.Set("vbr_id", object["VbrId"])
d.Set("vbr_owner_id", object["VbrOwnerId"])
return nil
}
func resourceAlicloudCenTransitRouterVbrAttachmentUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
parts, err1 := ParseResourceId(d.Id(), 2)
if err1 != nil {
return WrapError(err1)
}
update := false
request := map[string]interface{}{
"TransitRouterAttachmentId": parts[1],
}
if d.HasChange("auto_publish_route_enabled") || d.IsNewResource() {
update = true
request["AutoPublishRouteEnabled"] = d.Get("auto_publish_route_enabled")
}
if d.HasChange("resource_type") {
update = true
request["ResourceType"] = d.Get("resource_type")
}
if d.HasChange("transit_router_attachment_description") {
update = true
request["TransitRouterAttachmentDescription"] = d.Get("transit_router_attachment_description")
}
if d.HasChange("transit_router_attachment_name") {
update = true
request["TransitRouterAttachmentName"] = d.Get("transit_router_attachment_name")
}
if update {
if _, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = d.Get("dry_run")
}
action := "UpdateTransitRouterVbrAttachmentAttribute"
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Attached"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, cbnService.CenTransitRouterVbrAttachmentStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudCenTransitRouterVbrAttachmentRead(d, meta)
}
func resourceAlicloudCenTransitRouterVbrAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
action := "DeleteTransitRouterVbrAttachment"
var response map[string]interface{}
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
parts, err1 := ParseResourceId(d.Id(), 2)
if err1 != nil {
return WrapError(err1)
}
request := map[string]interface{}{
"TransitRouterAttachmentId": parts[1],
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
if v, ok := d.GetOk("resource_type"); ok {
request["ResourceType"] = v
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, cbnService.CenTransitRouterVbrAttachmentStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCenTransitRouterVpcAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCenTransitRouterVpcAttachmentCreate,
Read: resourceAlicloudCenTransitRouterVpcAttachmentRead,
Update: resourceAlicloudCenTransitRouterVpcAttachmentUpdate,
Delete: resourceAlicloudCenTransitRouterVpcAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(3 * time.Minute),
Delete: schema.DefaultTimeout(3 * time.Minute),
Update: schema.DefaultTimeout(3 * time.Minute),
},
Schema: map[string]*schema.Schema{
"auto_create_vpc_route": {
Type: schema.TypeBool,
Optional: true,
},
"cen_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"resource_type": {
Type: schema.TypeString,
Optional: true,
Default: "VPC",
},
"route_table_association_enabled": {
Type: schema.TypeBool,
Optional: true,
},
"route_table_propagation_enabled": {
Type: schema.TypeBool,
Optional: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"transit_router_attachment_description": {
Type: schema.TypeString,
Optional: true,
},
"transit_router_attachment_name": {
Type: schema.TypeString,
Optional: true,
},
"transit_router_id": {
Type: schema.TypeString,
Optional: true,
},
"transit_router_attachment_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"vpc_owner_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"zone_mappings": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
},
ForceNew: true,
},
},
}
}
func resourceAlicloudCenTransitRouterVpcAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
var response map[string]interface{}
action := "CreateTransitRouterVpcAttachment"
request := make(map[string]interface{})
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("auto_create_vpc_route"); ok {
request["AutoCreateVpcRoute"] = v
}
request["CenId"] = d.Get("cen_id")
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_type"); ok {
request["ResourceType"] = v
}
if v, ok := d.GetOkExists("route_table_association_enabled"); ok {
request["RouteTableAssociationEnabled"] = v
}
if v, ok := d.GetOkExists("route_table_propagation_enabled"); ok {
request["RouteTablePropagationEnabled"] = v
}
if v, ok := d.GetOk("transit_router_attachment_description"); ok {
request["TransitRouterAttachmentDescription"] = v
}
if v, ok := d.GetOk("transit_router_attachment_name"); ok {
request["TransitRouterAttachmentName"] = v
}
if v, ok := d.GetOk("transit_router_id"); ok {
request["TransitRouterId"] = v
}
request["VpcId"] = d.Get("vpc_id")
if v, ok := d.GetOk("vpc_owner_id"); ok {
request["VpcOwnerId"] = v
}
zoneMappingsMaps := make([]map[string]interface{}, 0)
for _, zoneMappings := range d.Get("zone_mappings").([]interface{}) {
zoneMappingsMap := make(map[string]interface{})
zoneMappingsArg := zoneMappings.(map[string]interface{})
zoneMappingsMap["VSwitchId"] = zoneMappingsArg["vswitch_id"]
zoneMappingsMap["ZoneId"] = zoneMappingsArg["zone_id"]
zoneMappingsMaps = append(zoneMappingsMaps, zoneMappingsMap)
}
request["ZoneMappings"] = zoneMappingsMaps
request["ClientToken"] = buildClientToken("CreateTransitRouterVpcAttachment")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cen_transit_router_vpc_attachment", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprintf("%v:%v", request["CenId"], response["TransitRouterAttachmentId"]))
stateConf := BuildStateConf([]string{}, []string{"Attached"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, cbnService.CenTransitRouterVpcAttachmentStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudCenTransitRouterVpcAttachmentRead(d, meta)
}
func resourceAlicloudCenTransitRouterVpcAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
object, err := cbnService.DescribeCenTransitRouterVpcAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cen_transit_router_vpc_attachment cbnService.DescribeCenTransitRouterVpcAttachment Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err1 := ParseResourceId(d.Id(), 2)
if err1 != nil {
return WrapError(err1)
}
d.Set("cen_id", parts[0])
d.Set("resource_type", object["ResourceType"])
d.Set("status", object["Status"])
d.Set("transit_router_attachment_description", object["TransitRouterAttachmentDescription"])
d.Set("transit_router_attachment_name", object["TransitRouterAttachmentName"])
d.Set("transit_router_attachment_id", object["TransitRouterAttachmentId"])
d.Set("vpc_id", object["VpcId"])
d.Set("vpc_owner_id", fmt.Sprint(object["VpcOwnerId"]))
zoneMappings := make([]map[string]interface{}, 0)
if zoneMappingsList, ok := object["ZoneMappings"].([]interface{}); ok {
for _, v := range zoneMappingsList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"vswitch_id": m1["VSwitchId"],
"zone_id": m1["ZoneId"],
}
zoneMappings = append(zoneMappings, temp1)
}
}
}
if err := d.Set("zone_mappings", zoneMappings); err != nil {
return WrapError(err)
}
return nil
}
func resourceAlicloudCenTransitRouterVpcAttachmentUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
update := false
parts, err1 := ParseResourceId(d.Id(), 2)
if err1 != nil {
return WrapError(err1)
}
request := map[string]interface{}{
"TransitRouterAttachmentId": parts[1],
}
if d.HasChange("resource_type") {
update = true
request["ResourceType"] = d.Get("resource_type")
}
if d.HasChange("transit_router_attachment_description") {
update = true
request["TransitRouterAttachmentDescription"] = d.Get("transit_router_attachment_description")
}
if d.HasChange("transit_router_attachment_name") {
update = true
request["TransitRouterAttachmentName"] = d.Get("transit_router_attachment_name")
}
if update {
if _, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = d.Get("dry_run")
}
action := "UpdateTransitRouterVpcAttachmentAttribute"
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Attached"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, cbnService.CenTransitRouterVpcAttachmentStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudCenTransitRouterVpcAttachmentRead(d, meta)
}
func resourceAlicloudCenTransitRouterVpcAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
action := "DeleteTransitRouterVpcAttachment"
var response map[string]interface{}
conn, err := client.NewCbnClient()
if err != nil {
return WrapError(err)
}
parts, err1 := ParseResourceId(d.Id(), 2)
if err1 != nil {
return WrapError(err1)
}
request := map[string]interface{}{
"TransitRouterAttachmentId": parts[1],
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
if v, ok := d.GetOk("resource_type"); ok {
request["ResourceType"] = v
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, cbnService.CenTransitRouterVpcAttachmentStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cbn"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCenVbrHealthCheck() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCenVbrHealthCheckCreate,
Read: resourceAlicloudCenVbrHealthCheckRead,
Update: resourceAlicloudCenVbrHealthCheckUpdate,
Delete: resourceAlicloudCenVbrHealthCheckDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(6 * time.Minute),
Delete: schema.DefaultTimeout(6 * time.Minute),
Update: schema.DefaultTimeout(6 * time.Minute),
},
Schema: map[string]*schema.Schema{
"cen_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"health_check_interval": {
Type: schema.TypeInt,
Optional: true,
Default: 2,
},
"health_check_source_ip": {
Type: schema.TypeString,
Optional: true,
},
"health_check_target_ip": {
Type: schema.TypeString,
Required: true,
},
"healthy_threshold": {
Type: schema.TypeInt,
Optional: true,
Default: 8,
},
"vbr_instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"vbr_instance_owner_id": {
Type: schema.TypeInt,
Optional: true,
},
"vbr_instance_region_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudCenVbrHealthCheckCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cbn.CreateEnableCenVbrHealthCheckRequest()
request.CenId = d.Get("cen_id").(string)
if v, ok := d.GetOk("health_check_interval"); ok {
request.HealthCheckInterval = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("health_check_source_ip"); ok {
request.HealthCheckSourceIp = v.(string)
}
request.HealthCheckTargetIp = d.Get("health_check_target_ip").(string)
if v, ok := d.GetOk("healthy_threshold"); ok {
request.HealthyThreshold = requests.NewInteger(v.(int))
}
request.VbrInstanceId = d.Get("vbr_instance_id").(string)
if v, ok := d.GetOk("vbr_instance_owner_id"); ok {
request.VbrInstanceOwnerId = requests.NewInteger(v.(int))
}
request.VbrInstanceRegionId = d.Get("vbr_instance_region_id").(string)
wait := incrementalWait(3*time.Second, 5*time.Second)
err := resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.EnableCenVbrHealthCheck(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InstanceStatus.NotSupport", "Operation.Blocking", "InvalidOperation.CenInstanceStatus", "InvalidOperation.VbrNotAttachedToCen", "OperationFailed.StatusNotSupport"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw)
d.SetId(fmt.Sprintf("%v:%v", request.VbrInstanceId, request.VbrInstanceRegionId))
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cen_vbr_health_check", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return resourceAlicloudCenVbrHealthCheckRead(d, meta)
}
func resourceAlicloudCenVbrHealthCheckRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cbnService := CbnService{client}
object, err := cbnService.DescribeCenVbrHealthCheck(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cen_vbr_health_check cbnService.DescribeCenVbrHealthCheck Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("vbr_instance_id", parts[0])
d.Set("vbr_instance_region_id", parts[1])
d.Set("cen_id", object.CenId)
d.Set("health_check_interval", object.HealthCheckInterval)
d.Set("health_check_source_ip", object.HealthCheckSourceIp)
d.Set("health_check_target_ip", object.HealthCheckTargetIp)
d.Set("healthy_threshold", object.HealthyThreshold)
return nil
}
func resourceAlicloudCenVbrHealthCheckUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
update := false
request := cbn.CreateEnableCenVbrHealthCheckRequest()
request.VbrInstanceId = parts[0]
request.VbrInstanceRegionId = parts[1]
request.CenId = d.Get("cen_id").(string)
if d.HasChange("health_check_target_ip") {
update = true
}
request.HealthCheckTargetIp = d.Get("health_check_target_ip").(string)
if d.HasChange("health_check_interval") {
update = true
request.HealthCheckInterval = requests.NewInteger(d.Get("health_check_interval").(int))
}
if d.HasChange("health_check_source_ip") {
update = true
request.HealthCheckSourceIp = d.Get("health_check_source_ip").(string)
}
if d.HasChange("healthy_threshold") {
update = true
request.HealthyThreshold = requests.NewInteger(d.Get("healthy_threshold").(int))
}
if d.HasChange("vbr_instance_owner_id") {
update = true
request.VbrInstanceOwnerId = requests.NewInteger(d.Get("vbr_instance_owner_id").(int))
}
if update {
wait := incrementalWait(3*time.Second, 5*time.Second)
err := resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.EnableCenVbrHealthCheck(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "InvalidOperation.CenInstanceStatus", "InstanceStatus.NotSupport"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudCenVbrHealthCheckRead(d, meta)
}
func resourceAlicloudCenVbrHealthCheckDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request := cbn.CreateDisableCenVbrHealthCheckRequest()
request.VbrInstanceId = parts[0]
request.VbrInstanceRegionId = parts[1]
request.CenId = d.Get("cen_id").(string)
if v, ok := d.GetOk("vbr_instance_owner_id"); ok {
request.VbrInstanceOwnerId = requests.NewInteger(v.(int))
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
raw, err := client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DisableCenVbrHealthCheck(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "InstanceStatus.NotSupport"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudClickHouseAccount() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudClickHouseAccountCreate,
Read: resourceAlicloudClickHouseAccountRead,
Update: resourceAlicloudClickHouseAccountUpdate,
Delete: resourceAlicloudClickHouseAccountDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"account_description": {
Type: schema.TypeString,
Optional: true,
},
"account_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-z][a-z0-9_]{1,15}`), "The account_name most consist of lowercase letters, numbers, and underscores, starting with a lowercase letter"),
},
"account_password": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`[a-zA-Z!#$%^&*()_+-=]{8,32}`), "account_password must consist of uppercase letters, lowercase letters, numbers, and special characters"),
},
"db_cluster_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudClickHouseAccountCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateAccount"
request := make(map[string]interface{})
conn, err := client.NewClickhouseClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("account_description"); ok {
request["AccountDescription"] = v
}
request["AccountName"] = d.Get("account_name")
request["AccountPassword"] = d.Get("account_password")
request["DBClusterId"] = d.Get("db_cluster_id")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectAccountStatus", "IncorrectDBInstanceState"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_click_house_account", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["DBClusterId"], ":", request["AccountName"]))
return resourceAlicloudClickHouseAccountRead(d, meta)
}
func resourceAlicloudClickHouseAccountRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
clickhouseService := ClickhouseService{client}
object, err := clickhouseService.DescribeClickHouseAccount(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_click_house_account clickhouseService.DescribeClickHouseAccount Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("account_name", parts[1])
d.Set("db_cluster_id", parts[0])
d.Set("account_description", object["AccountDescription"])
d.Set("status", object["AccountStatus"])
d.Set("type", object["AccountType"])
return nil
}
func resourceAlicloudClickHouseAccountUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
update := false
d.Partial(true)
request := map[string]interface{}{
"AccountName": parts[1],
"DBClusterId": parts[0],
}
if d.HasChange("account_description") {
update = true
if v, ok := d.GetOk("account_description"); ok {
request["AccountDescription"] = v
}
}
if update {
action := "ModifyAccountDescription"
conn, err := client.NewClickhouseClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectAccountStatus", "IncorrectDBInstanceState"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("account_description")
}
update = false
if d.HasChange("account_password") {
update = true
request = map[string]interface{}{
"AccountName": parts[1],
"DBClusterId": parts[0],
}
request["AccountPassword"] = d.Get("account_password")
}
if update {
action := "ResetAccountPassword"
conn, err := client.NewClickhouseClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectAccountStatus", "IncorrectDBInstanceState"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("account_password")
}
d.Partial(false)
return resourceAlicloudClickHouseAccountRead(d, meta)
}
func resourceAlicloudClickHouseAccountDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
clickhouseService := ClickhouseService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteAccount"
var response map[string]interface{}
conn, err := client.NewClickhouseClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AccountName": parts[1],
"DBClusterId": parts[0],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectAccountStatus", "IncorrectDBInstanceState"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"Deleting"}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, clickhouseService.ClickhouseStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
if NotFoundError(err) {
return nil
}
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudClickHouseBackupPolicy() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudClickHouseBackupPolicyCreate,
Read: resourceAlicloudClickHouseBackupPolicyRead,
Update: resourceAlicloudClickHouseBackupPolicyUpdate,
Delete: resourceAlicloudClickHouseBackupPolicyDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"backup_retention_period": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(7, 730),
},
"db_cluster_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"preferred_backup_period": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Required: true,
},
"preferred_backup_time": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice(BACKUP_TIME, false),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudClickHouseBackupPolicyCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateBackupPolicy"
request := make(map[string]interface{})
conn, err := client.NewClickhouseClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("backup_retention_period"); ok {
request["BackupRetentionPeriod"] = v
}
request["DBClusterId"] = d.Get("db_cluster_id")
if v, ok := d.Get("preferred_backup_period").(*schema.Set); ok {
periodList := expandStringList(v.List())
request["PreferredBackupPeriod"] = strings.Join(periodList[:], COMMA_SEPARATED)
}
request["PreferredBackupTime"] = d.Get("preferred_backup_time")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_click_house_backup_policy", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["DBClusterId"]))
clickhouseService := ClickhouseService{client}
stateConf := BuildStateConf([]string{}, []string{"true"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, clickhouseService.ClickHouseBackupPolicyStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudClickHouseBackupPolicyRead(d, meta)
}
func resourceAlicloudClickHouseBackupPolicyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
clickhouseService := ClickhouseService{client}
object, err := clickhouseService.DescribeClickHouseBackupPolicy(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_click_house_backup_policy clickhouseService.DescribeClickHouseBackupPolicy Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("db_cluster_id", d.Id())
if v, ok := object["BackupRetentionPeriod"]; ok && fmt.Sprint(v) != "0" {
d.Set("backup_retention_period", formatInt(v))
}
d.Set("preferred_backup_period", strings.Split(object["PreferredBackupPeriod"].(string), ","))
d.Set("preferred_backup_time", object["PreferredBackupTime"])
d.Set("status", fmt.Sprint(object["Switch"]))
return nil
}
func resourceAlicloudClickHouseBackupPolicyUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"DBClusterId": d.Id(),
}
if d.HasChange("preferred_backup_period") {
update = true
}
if v, ok := d.Get("preferred_backup_period").(*schema.Set); ok {
periodList := expandStringList(v.List())
request["PreferredBackupPeriod"] = strings.Join(periodList[:], COMMA_SEPARATED)
}
if d.HasChange("preferred_backup_time") {
update = true
}
request["PreferredBackupTime"] = d.Get("preferred_backup_time")
if d.HasChange("backup_retention_period") {
update = true
if v, ok := d.GetOk("backup_retention_period"); ok {
request["BackupRetentionPeriod"] = v
}
}
if update {
action := "ModifyBackupPolicy"
conn, err := client.NewClickhouseClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudClickHouseBackupPolicyRead(d, meta)
}
func resourceAlicloudClickHouseBackupPolicyDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudClickHouseBackupPolicy. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudClickHouseDbCluster() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudClickHouseDbClusterCreate,
Read: resourceAlicloudClickHouseDbClusterRead,
Update: resourceAlicloudClickHouseDbClusterUpdate,
Delete: resourceAlicloudClickHouseDbClusterDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(60 * time.Minute),
Update: schema.DefaultTimeout(60 * time.Minute),
},
Schema: map[string]*schema.Schema{
"category": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"Basic", "HighAvailability"}, false),
ForceNew: true,
},
"db_cluster_access_white_list": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"db_cluster_ip_array_attribute": {
Type: schema.TypeString,
Optional: true,
},
"db_cluster_ip_array_name": {
Type: schema.TypeString,
Optional: true,
},
"security_ip_list": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"db_cluster_class": {
Type: schema.TypeString,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"S4-NEW", "S8", "S16", "S32", "S64", "S104", "C4-NEW", "C8", "C16", "C32", "C64", "C104"}, false),
Required: true,
},
"db_cluster_network_type": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"vpc"}, false),
Required: true,
ForceNew: true,
},
"db_cluster_version": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"19.15.2.2", "20.3.10.75", "20.8.7.15"}, false),
},
"db_node_storage": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"db_node_group_count": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(1, 48),
Required: true,
ForceNew: true,
},
"encryption_key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"encryption_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"payment_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo", "Subscription"}, false),
ForceNew: true,
},
"period": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Month", "Year"}, false),
},
"storage_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"cloud_essd", "cloud_efficiency", "cloud_essd_pl2", "cloud_essd_pl3"}, false),
},
"used_time": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"db_cluster_description": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Creating", "Deleting", "Restarting", "Preparing", "Running"}, false),
},
"maintain_time": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
},
}
}
func resourceAlicloudClickHouseDbClusterCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
clickhouseService := ClickhouseService{client}
var response map[string]interface{}
action := "CreateDBInstance"
request := make(map[string]interface{})
conn, err := client.NewClickhouseClient()
if err != nil {
return WrapError(err)
}
request["DBClusterCategory"] = d.Get("category")
request["DBClusterClass"] = d.Get("db_cluster_class")
if v, ok := d.GetOk("db_cluster_description"); ok {
request["DBClusterDescription"] = v
}
request["DBClusterNetworkType"] = d.Get("db_cluster_network_type")
request["DBClusterVersion"] = d.Get("db_cluster_version")
request["DBNodeGroupCount"] = d.Get("db_node_group_count")
request["DBNodeStorage"] = d.Get("db_node_storage")
if v, ok := d.GetOk("encryption_key"); ok {
request["EncryptionKey"] = v
}
if v, ok := d.GetOk("encryption_type"); ok {
request["EncryptionType"] = v
}
request["PayType"] = convertClickHouseDbClusterPaymentTypeRequest(d.Get("payment_type").(string))
if v, ok := d.GetOk("period"); ok {
request["Period"] = v
}
request["RegionId"] = client.RegionId
request["DbNodeStorageType"] = d.Get("storage_type")
if v, ok := d.GetOk("used_time"); ok {
request["UsedTime"] = v
}
vswitchId := Trim(d.Get("vswitch_id").(string))
if vswitchId != "" {
vpcService := VpcService{client}
vsw, err := vpcService.DescribeVSwitchWithTeadsl(vswitchId)
if err != nil {
return WrapError(err)
}
request["VPCId"] = vsw["VpcId"]
request["VSwitchId"] = vswitchId
if v, ok := request["ZoneId"].(string); !ok || v == "" {
request["ZoneId"] = vsw["ZoneId"]
}
}
request["ClientToken"] = buildClientToken("CreateDBInstance")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_click_house_db_cluster", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["DBClusterId"]))
stateConf := BuildStateConf([]string{"Creating", "Deleting", "Restarting", "Preparing"}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, clickhouseService.ClickHouseDbClusterStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudClickHouseDbClusterUpdate(d, meta)
}
func resourceAlicloudClickHouseDbClusterRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
clickhouseService := ClickhouseService{client}
object, err := clickhouseService.DescribeClickHouseDbCluster(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_click_house_db_cluster clickhouseService.DescribeClickHouseDbCluster Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("category", object["Category"])
d.Set("db_cluster_description", object["DBClusterDescription"])
d.Set("db_cluster_network_type", object["DBClusterNetworkType"])
d.Set("db_node_storage", fmt.Sprint(formatInt(object["DBNodeStorage"])))
d.Set("encryption_key", object["EncryptionKey"])
d.Set("encryption_type", object["EncryptionType"])
d.Set("maintain_time", object["MaintainTime"])
d.Set("status", object["DBClusterStatus"])
d.Set("payment_type", convertClickHouseDbClusterPaymentTypeResponse(object["PayType"].(string)))
d.Set("storage_type", convertClickHouseDbClusterStorageTypeResponse(object["StorageType"].(string)))
d.Set("vswitch_id", object["VSwitchId"])
d.Set("zone_id", object["ZoneId"])
describeDBClusterAccessWhiteListObject, err := clickhouseService.DescribeDBClusterAccessWhiteList(d.Id())
if err != nil {
return WrapError(err)
}
if dBClusterAccessWhiteListMap, ok := describeDBClusterAccessWhiteListObject["DBClusterAccessWhiteList"].(map[string]interface{}); ok && dBClusterAccessWhiteListMap != nil {
if iPArrayList, ok := dBClusterAccessWhiteListMap["IPArray"]; ok && iPArrayList != nil {
dBClusterAccessWhiteListMaps := make([]map[string]interface{}, 0)
for _, iPArrayListItem := range iPArrayList.([]interface{}) {
if v, ok := iPArrayListItem.(map[string]interface{}); ok {
if v["DBClusterIPArrayName"].(string) == "default" {
continue
}
iPArrayListItemMap := make(map[string]interface{})
iPArrayListItemMap["db_cluster_ip_array_attribute"] = v["DBClusterIPArrayAttribute"]
iPArrayListItemMap["db_cluster_ip_array_name"] = v["DBClusterIPArrayName"]
iPArrayListItemMap["security_ip_list"] = v["SecurityIPList"]
dBClusterAccessWhiteListMaps = append(dBClusterAccessWhiteListMaps, iPArrayListItemMap)
}
}
d.Set("db_cluster_access_white_list", dBClusterAccessWhiteListMaps)
}
}
return nil
}
func resourceAlicloudClickHouseDbClusterUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"DBClusterId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("db_cluster_description") {
update = true
if v, ok := d.GetOk("db_cluster_description"); ok {
request["DBClusterDescription"] = v
}
}
if update {
action := "ModifyDBClusterDescription"
conn, err := client.NewClickhouseClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectDBInstanceState"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("db_cluster_description")
}
update = false
modifyDBClusterMaintainTimeReq := map[string]interface{}{
"DBClusterId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("maintain_time") {
update = true
}
if v, ok := d.GetOk("maintain_time"); ok {
modifyDBClusterMaintainTimeReq["MaintainTime"] = v
}
if update {
action := "ModifyDBClusterMaintainTime"
conn, err := client.NewClickhouseClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-11"), StringPointer("AK"), nil, modifyDBClusterMaintainTimeReq, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectDBInstanceState"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyDBClusterMaintainTimeReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("maintain_time")
}
if d.HasChange("db_cluster_access_white_list") {
oraw, nraw := d.GetChange("db_cluster_access_white_list")
remove := oraw.(*schema.Set).Difference(nraw.(*schema.Set)).List()
create := nraw.(*schema.Set).Difference(oraw.(*schema.Set)).List()
if len(remove) > 0 {
removeWhiteListReq := map[string]interface{}{
"DBClusterId": d.Id(),
"ModifyMode": "Delete",
}
for _, whiteList := range remove {
whiteListArg := whiteList.(map[string]interface{})
removeWhiteListReq["DBClusterIPArrayAttribute"] = whiteListArg["db_cluster_ip_array_attribute"]
removeWhiteListReq["DBClusterIPArrayName"] = whiteListArg["db_cluster_ip_array_name"]
removeWhiteListReq["SecurityIps"] = whiteListArg["security_ip_list"]
action := "ModifyDBClusterAccessWhiteList"
conn, err := client.NewClickhouseClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-11"), StringPointer("AK"), nil, removeWhiteListReq, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectDBInstanceState"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, removeWhiteListReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
}
if len(create) > 0 {
createWhiteListReq := map[string]interface{}{
"DBClusterId": d.Id(),
"ModifyMode": "Append",
}
for _, whiteList := range create {
whiteListArg := whiteList.(map[string]interface{})
createWhiteListReq["DBClusterIPArrayAttribute"] = whiteListArg["db_cluster_ip_array_attribute"]
createWhiteListReq["DBClusterIPArrayName"] = whiteListArg["db_cluster_ip_array_name"]
createWhiteListReq["SecurityIps"] = whiteListArg["security_ip_list"]
action := "ModifyDBClusterAccessWhiteList"
conn, err := client.NewClickhouseClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-11"), StringPointer("AK"), nil, createWhiteListReq, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectDBInstanceState"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, createWhiteListReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
}
d.SetPartial("db_cluster_access_white_list")
}
if d.HasChange("status") {
clickhouseService := ClickhouseService{client}
object, err := clickhouseService.DescribeClickHouseDbCluster(d.Id())
if err != nil {
return WrapError(err)
}
target := d.Get("status").(string)
if object["DBClusterStatus"].(string) != target {
if target == "Running" {
request := map[string]interface{}{
"DBClusterId": d.Id(),
}
request["RegionId"] = client.RegionId
action := "RestartInstance"
conn, err := client.NewClickhouseClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectDBInstanceState"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("status")
}
stateConf := BuildStateConf([]string{"RESTARTING"}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, clickhouseService.ClickHouseDbClusterStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.Partial(false)
return resourceAlicloudClickHouseDbClusterRead(d, meta)
}
func resourceAlicloudClickHouseDbClusterDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteDBCluster"
var response map[string]interface{}
conn, err := client.NewClickhouseClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DBClusterId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectDBInstanceState"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func convertClickHouseDbClusterPaymentTypeRequest(source string) string {
switch source {
case "PayAsYouGo":
return "Postpaid"
case "Subscription":
return "Prepay"
}
return source
}
func convertClickHouseDbClusterPaymentTypeResponse(source string) string {
switch source {
case "Postpaid":
return "PayAsYouGo"
case "Prepay":
return "Subscription"
}
return source
}
func convertClickHouseDbClusterStorageTypeResponse(source string) string {
switch source {
case "CloudESSD":
return "cloud_essd"
case "CloudEfficiency":
return "cloud_efficiency"
case "CloudESSD_PL2":
return "cloud_essd_pl2"
case "CloudESSD_PL3":
return "cloud_essd_pl3"
}
return source
}
package alicloud
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/smartag"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCloudConnectNetwork() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCloudConnectNetworkCreate,
Read: resourceAlicloudCloudConnectNetworkRead,
Update: resourceAlicloudCloudConnectNetworkUpdate,
Delete: resourceAlicloudCloudConnectNetworkDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 128),
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"is_default": {
Type: schema.TypeBool,
Required: true,
},
"cidr_block": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateVpnCIDRNetworkAddress,
},
},
}
}
func resourceAlicloudCloudConnectNetworkCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := smartag.CreateCreateCloudConnectNetworkRequest()
request.IsDefault = requests.NewBoolean(d.Get("is_default").(bool))
if v, ok := d.GetOk("name"); ok && v.(string) != "" {
request.Name = v.(string)
}
if v, ok := d.GetOk("description"); ok && v.(string) != "" {
request.Description = v.(string)
}
if v, ok := d.GetOk("cidr_block"); ok && v.(string) != "" {
request.CidrBlock = v.(string)
}
raw, err := client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.CreateCloudConnectNetwork(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloud_connect_network", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*smartag.CreateCloudConnectNetworkResponse)
d.SetId(response.CcnId)
return resourceAlicloudCloudConnectNetworkRead(d, meta)
}
func resourceAlicloudCloudConnectNetworkRead(d *schema.ResourceData, meta interface{}) error {
ccnService := SagService{meta.(*connectivity.AliyunClient)}
object, err := ccnService.DescribeCloudConnectNetwork(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", object.Name)
d.Set("description", object.Description)
d.Set("cidr_block", object.CidrBlock)
d.Set("is_default", object.IsDefault)
return nil
}
func resourceAlicloudCloudConnectNetworkUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
update := false
request := smartag.CreateModifyCloudConnectNetworkRequest()
request.CcnId = d.Id()
if d.HasChange("name") {
request.Name = d.Get("name").(string)
update = true
}
if d.HasChange("description") {
request.Description = d.Get("description").(string)
update = true
}
if d.HasChange("cidr_block") {
request.CidrBlock = d.Get("cidr_block").(string)
update = true
}
if update {
raw, err := client.WithSagClient(func(ccnClient *smartag.Client) (interface{}, error) {
return ccnClient.ModifyCloudConnectNetwork(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
return resourceAlicloudCloudConnectNetworkRead(d, meta)
}
func resourceAlicloudCloudConnectNetworkDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sagService := SagService{client}
request := smartag.CreateDeleteCloudConnectNetworkRequest()
request.CcnId = d.Id()
raw, err := client.WithSagClient(func(ccnClient *smartag.Client) (interface{}, error) {
return ccnClient.DeleteCloudConnectNetwork(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ParameterCcnInstanceId"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(sagService.WaitForCloudConnectNetwork(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"fmt"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/smartag"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCloudConnectNetworkAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCloudConnectNetworkAttachmentCreate,
Read: resourceAlicloudCloudConnectNetworkAttachmentRead,
Delete: resourceAlicloudCloudConnectNetworkAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"ccn_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"sag_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudCloudConnectNetworkAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := smartag.CreateBindSmartAccessGatewayRequest()
request.RegionId = client.RegionId
request.CcnId = d.Get("ccn_id").(string)
request.SmartAGId = d.Get("sag_id").(string)
var err error
var raw interface{}
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err = client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.BindSmartAccessGateway(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "UnknownError"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloud_connect_network_attachment", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetId(fmt.Sprintf("%s%s%s", request.CcnId, COLON_SEPARATED, request.SmartAGId))
return resourceAlicloudCloudConnectNetworkAttachmentRead(d, meta)
}
func resourceAlicloudCloudConnectNetworkAttachmentRead(d *schema.ResourceData, meta interface{}) error {
sagService := SagService{meta.(*connectivity.AliyunClient)}
object, err := sagService.DescribeCloudConnectNetworkAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("ccn_id", object.AssociatedCcnId)
d.Set("sag_id", object.SmartAGId)
return nil
}
func resourceAlicloudCloudConnectNetworkAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sagService := SagService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
ccnId := parts[0]
sagId := parts[1]
request := smartag.CreateUnbindSmartAccessGatewayRequest()
request.RegionId = client.RegionId
request.CcnId = ccnId
request.SmartAGId = sagId
var raw interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.UnbindSmartAccessGateway(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectStatus", "TaskConflict"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidInstanceId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(sagService.WaitForCloudConnectNetworkAttachment(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"fmt"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/smartag"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCloudConnectNetworkGrant() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCloudConnectNetworkGrantCreate,
Read: resourceAlicloudCloudConnectNetworkGrantRead,
Delete: resourceAlicloudCloudConnectNetworkGrantDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"ccn_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"cen_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"cen_uid": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudCloudConnectNetworkGrantCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := smartag.CreateGrantInstanceToCbnRequest()
request.RegionId = client.RegionId
request.CcnInstanceId = d.Get("ccn_id").(string)
request.CenInstanceId = d.Get("cen_id").(string)
request.CenUid = d.Get("cen_uid").(requests.Integer)
var err error
var raw interface{}
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err = client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.GrantInstanceToCbn(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"Operation.Blocking", "UnknownError"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloud_connect_network_grant", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetId(fmt.Sprintf("%s%s%s", request.CcnInstanceId, COLON_SEPARATED, request.CenInstanceId))
return resourceAlicloudCloudConnectNetworkGrantRead(d, meta)
}
func resourceAlicloudCloudConnectNetworkGrantRead(d *schema.ResourceData, meta interface{}) error {
sagService := SagService{meta.(*connectivity.AliyunClient)}
object, err := sagService.DescribeCloudConnectNetworkGrant(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("ccn_id", object.CcnInstanceId)
d.Set("cen_id", object.CenInstanceId)
d.Set("cen_uid", object.CenUid)
return nil
}
func resourceAlicloudCloudConnectNetworkGrantDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sagService := SagService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request := smartag.CreateRevokeInstanceFromCbnRequest()
request.RegionId = client.RegionId
request.CcnInstanceId = parts[0]
request.CenInstanceId = parts[1]
var raw interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.RevokeInstanceFromCbn(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectStatus", "TaskConflict"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidInstanceId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(sagService.WaitForCloudConnectNetworkGrant(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCloudFirewallControlPolicy() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCloudFirewallControlPolicyCreate,
Read: resourceAlicloudCloudFirewallControlPolicyRead,
Update: resourceAlicloudCloudFirewallControlPolicyUpdate,
Delete: resourceAlicloudCloudFirewallControlPolicyDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"acl_action": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"accept", "drop", "log"}, false),
},
"acl_uuid": {
Type: schema.TypeString,
Computed: true,
},
"application_name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"ANY", "HTTP", "HTTPS", "MQTT", "Memcache", "MongoDB", "MySQL", "RDP", "Redis", "SMTP", "SMTPS", "SSH", "SSL", "VNC"}, false),
},
"description": {
Type: schema.TypeString,
Required: true,
},
"dest_port": {
Type: schema.TypeString,
Optional: true,
Computed: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("dest_port_type"); ok && v.(string) == "port" {
return false
}
return true
},
},
"dest_port_group": {
Type: schema.TypeString,
Optional: true,
Computed: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("dest_port_type"); ok && v.(string) == "group" {
return false
}
return true
},
},
"dest_port_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"group", "port"}, false),
},
"destination": {
Type: schema.TypeString,
Required: true,
},
"destination_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"group", "location", "net", "domain"}, false),
},
"direction": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"in", "out"}, false),
},
"ip_version": {
Type: schema.TypeString,
Optional: true,
},
"lang": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"en", "zh"}, false),
},
"proto": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"ANY", "TCP", "UDP", "ICMP"}, false),
},
"release": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"source": {
Type: schema.TypeString,
Required: true,
},
"source_ip": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"source_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"group", "location", "net"}, false),
},
},
}
}
func resourceAlicloudCloudFirewallControlPolicyCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AddControlPolicy"
request := make(map[string]interface{})
conn, err := client.NewCloudfwClient()
if err != nil {
return WrapError(err)
}
request["AclAction"] = d.Get("acl_action")
request["ApplicationName"] = d.Get("application_name")
request["Description"] = d.Get("description")
if v, ok := d.GetOk("dest_port"); ok {
request["DestPort"] = v
}
if v, ok := d.GetOk("dest_port_group"); ok {
request["DestPortGroup"] = v
}
if v, ok := d.GetOk("dest_port_type"); ok {
request["DestPortType"] = v
}
request["Destination"] = d.Get("destination")
request["DestinationType"] = d.Get("destination_type")
request["Direction"] = d.Get("direction")
if v, ok := d.GetOk("ip_version"); ok {
request["IpVersion"] = v
}
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
// order属性不透出
request["NewOrder"] = "-1"
request["Proto"] = d.Get("proto")
request["Source"] = d.Get("source")
if v, ok := d.GetOk("source_ip"); ok {
request["SourceIp"] = v
}
request["SourceType"] = d.Get("source_type")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-07"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloud_firewall_control_policy", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["AclUuid"], ":", request["Direction"]))
return resourceAlicloudCloudFirewallControlPolicyRead(d, meta)
}
func resourceAlicloudCloudFirewallControlPolicyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudfwService := CloudfwService{client}
object, err := cloudfwService.DescribeCloudFirewallControlPolicy(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cloud_firewall_control_policy cloudfwService.DescribeCloudFirewallControlPolicy Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("acl_uuid", parts[0])
d.Set("direction", parts[1])
d.Set("acl_action", object["AclAction"])
d.Set("application_name", object["ApplicationName"])
d.Set("description", object["Description"])
d.Set("dest_port", object["DestPort"])
d.Set("dest_port_group", object["DestPortGroup"])
d.Set("dest_port_type", object["DestPortType"])
d.Set("destination", object["Destination"])
d.Set("destination_type", object["DestinationType"])
d.Set("direction", object["Direction"])
d.Set("proto", object["Proto"])
d.Set("release", object["Release"])
d.Set("source", object["Source"])
d.Set("source_type", object["SourceType"])
return nil
}
func resourceAlicloudCloudFirewallControlPolicyUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"AclUuid": parts[0],
"Direction": parts[1],
}
if d.HasChange("acl_action") {
update = true
}
request["AclAction"] = d.Get("acl_action")
if d.HasChange("application_name") {
update = true
}
request["ApplicationName"] = d.Get("application_name")
if d.HasChange("description") {
update = true
}
request["Description"] = d.Get("description")
if d.HasChange("destination") {
update = true
}
request["Destination"] = d.Get("destination")
if d.HasChange("destination_type") {
update = true
}
request["DestinationType"] = d.Get("destination_type")
if d.HasChange("proto") {
update = true
}
request["Proto"] = d.Get("proto")
if d.HasChange("source") {
update = true
}
request["Source"] = d.Get("source")
if d.HasChange("source_type") {
update = true
}
request["SourceType"] = d.Get("source_type")
if d.HasChange("dest_port") {
update = true
}
request["DestPort"] = d.Get("dest_port")
if d.HasChange("dest_port_group") {
update = true
request["DestPortGroup"] = d.Get("dest_port_group")
}
if d.HasChange("dest_port_type") {
update = true
}
request["DestPortType"] = d.Get("dest_port_type")
if d.HasChange("lang") {
update = true
request["Lang"] = d.Get("lang")
}
if d.HasChange("release") || d.IsNewResource() {
update = true
request["Release"] = d.Get("release")
}
if update {
if v, ok := d.GetOk("source_ip"); ok {
request["SourceIp"] = v
}
action := "ModifyControlPolicy"
conn, err := client.NewCloudfwClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-07"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudCloudFirewallControlPolicyRead(d, meta)
}
func resourceAlicloudCloudFirewallControlPolicyDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteControlPolicy"
var response map[string]interface{}
conn, err := client.NewCloudfwClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AclUuid": parts[0],
"Direction": parts[1],
}
if v, ok := d.GetOk("source_ip"); ok {
request["SourceIp"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-07"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCloudFirewallControlPolicyOrder() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCloudFirewallControlPolicyOrderCreate,
Read: resourceAlicloudCloudFirewallControlPolicyOrderRead,
Update: resourceAlicloudCloudFirewallControlPolicyOrderUpdate,
Delete: resourceAlicloudCloudFirewallControlPolicyOrderDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"acl_uuid": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"direction": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"in", "out"}, false),
},
"order": {
Type: schema.TypeInt,
Optional: true,
},
},
}
}
func resourceAlicloudCloudFirewallControlPolicyOrderCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "ModifyControlPolicyPriority"
request := make(map[string]interface{})
conn, err := client.NewCloudfwClient()
if err != nil {
return WrapError(err)
}
request["Direction"] = d.Get("direction")
request["Order"] = d.Get("order")
request["AclUuid"] = d.Get("acl_uuid")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-07"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloud_firewall_control_policy_order", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["AclUuid"], ":", request["Direction"]))
return resourceAlicloudCloudFirewallControlPolicyRead(d, meta)
}
func resourceAlicloudCloudFirewallControlPolicyOrderUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "ModifyControlPolicyPriority"
conn, err := client.NewCloudfwClient()
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"AclUuid": parts[0],
"Direction": parts[1],
}
if d.HasChange("order") {
update = true
request["Order"] = d.Get("order")
}
if update {
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-07"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
}
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloud_firewall_control_policy_order", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["AclUuid"], ":", request["Direction"]))
return resourceAlicloudCloudFirewallControlPolicyRead(d, meta)
}
func resourceAlicloudCloudFirewallControlPolicyOrderRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudfwService := CloudfwService{client}
object, err := cloudfwService.DescribeCloudFirewallControlPolicy(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cloud_firewall_control_policy_order cloudfwService.DescribeCloudFirewallControlPolicy Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("acl_uuid", parts[0])
d.Set("direction", parts[1])
d.Set("order", formatInt(object["Order"]))
return nil
}
func resourceAlicloudCloudFirewallControlPolicyOrderDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] Resource alicloud_cloud_firewall_control_policy_order [%s] will not be deleted", d.Id())
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCloudFirewallInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCloudFirewallInstanceCreate,
Read: resourceAlicloudCloudFirewallInstanceRead,
Update: resourceAlicloudCloudFirewallInstanceUpdate,
Delete: resourceAlicloudCloudFirewallInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"payment_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Subscription"}, false),
},
"period": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntInSlice([]int{6, 12, 24, 36}),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("payment_type"); ok && v.(string) == "Subscription" {
return false
}
return true
},
},
"renew_period": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(1, 12),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("payment_type"); ok && v.(string) == "Subscription" {
if v, ok := d.GetOk("renewal_status"); ok && v.(string) == "AutoRenewal" {
return false
}
}
return true
},
},
"renewal_status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"AutoRenewal", "ManualRenewal"}, false),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("payment_type"); ok && v.(string) == "Subscription" {
return false
}
return true
},
},
"logistics": {
Type: schema.TypeString,
Optional: true,
},
"cfw_service": {
Type: schema.TypeBool,
Required: true,
},
"fw_vpc_number": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(2, 500),
},
"ip_number": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(20, 4000),
},
"cfw_log_storage": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(1000, 500000),
},
"cfw_log": {
Type: schema.TypeBool,
Required: true,
},
"band_width": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(10, 15000),
},
"instance_count": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(5, 5000),
},
"spec": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"premium_version", "enterprise_version", "ultimate_version"}, false),
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"renewal_duration_unit": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"end_time": {
Type: schema.TypeString,
Computed: true,
},
"release_time": {
Type: schema.TypeString,
Computed: true,
},
"modify_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Downgrade", "Upgrade"}, false),
},
},
}
}
func resourceAlicloudCloudFirewallInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateInstance"
request := make(map[string]interface{})
conn, err := client.NewBssopenapiClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken(action)
request["ProductCode"] = "vipcloudfw"
request["ProductType"] = "vipcloudfw"
request["SubscriptionType"] = d.Get("payment_type")
if v, ok := d.GetOk("period"); ok {
request["Period"] = v
} else if d.Get("payment_type").(string) == "Subscription" {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is %v", "period", "payment_type", "Subscription"))
}
if v, ok := d.GetOk("renewal_status"); ok {
request["RenewalStatus"] = v
}
if v, ok := d.GetOk("renewal_duration"); ok {
request["RenewPeriod"] = v
} else if v, ok := d.GetOk("renewal_status"); ok && v.(string) == "AutoRenewal" {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is %v ", "renewal_duration", "renewal_status", d.Get("renewal_status")))
}
if v, ok := d.GetOk("logistics"); ok {
request["Logistics"] = v
}
parameterMapList := make([]map[string]interface{}, 0)
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "Spec",
"Value": convertCloudFirewallInstanceVersion(d.Get("spec").(string)),
})
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "IpNumber",
"Value": d.Get("ip_number"),
})
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "BandWidth",
"Value": d.Get("band_width"),
})
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "CfwLog",
"Value": d.Get("cfw_log"),
})
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "CfwLogStorage",
"Value": d.Get("cfw_log_storage"),
})
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "CfwService",
"Value": d.Get("cfw_service"),
})
if v, ok := d.GetOk("fw_vpc_number"); ok {
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "FwVpcNumber",
"Value": v,
})
}
if v, ok := d.GetOk("instance_count"); ok {
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "InstanceCount",
"Value": v,
})
}
request["Parameter"] = parameterMapList
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-14"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"NotApplicable"}) {
conn.Endpoint = String(connectivity.BssOpenAPIEndpointInternational)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloud_firewall_instance", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
responseData := response["Data"].(map[string]interface{})
d.SetId(fmt.Sprint(responseData["InstanceId"]))
return resourceAlicloudCloudFirewallInstanceRead(d, meta)
}
func resourceAlicloudCloudFirewallInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
bssOpenApiService := BssOpenApiService{client}
getQueryInstanceObject, err := bssOpenApiService.QueryAvailableInstance(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("create_time", getQueryInstanceObject["CreateTime"])
d.Set("renewal_status", getQueryInstanceObject["RenewStatus"])
d.Set("renewal_duration_unit", convertCloudFirewallInstanceRenewalDurationUnitResponse(getQueryInstanceObject["RenewalDurationUnit"]))
d.Set("status", getQueryInstanceObject["Status"])
d.Set("subscription_type", getQueryInstanceObject["SubscriptionType"])
d.Set("end_time", getQueryInstanceObject["EndTime"])
return nil
}
func resourceAlicloudCloudFirewallInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewBssopenapiClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
d.Partial(true)
update := false
renewInstancerequest := map[string]interface{}{
"InstanceId": d.Id(),
}
if d.HasChange("renew_period") && !d.IsNewResource() {
update = true
renewInstancerequest["RenewPeriod"] = d.Get("renew_period")
}
if update {
action := "RenewInstance"
renewInstancerequest["ClientToken"] = buildClientToken(action)
renewInstancerequest["ProductCode"] = "vipcloudfw"
renewInstancerequest["ProductType"] = "vipcloudfw"
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-14"), StringPointer("AK"), nil, renewInstancerequest, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"NotApplicable"}) {
conn.Endpoint = String(connectivity.BssOpenAPIEndpointInternational)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, renewInstancerequest)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
}
update = false
modifyInstanceRequest := map[string]interface{}{
"InstanceId": d.Id(),
}
modifyInstanceRequest["ProductType"] = "vipcloudfw"
modifyInstanceRequest["ProductCode"] = "vipcloudfw"
modifyInstanceRequest["SubscriptionType"] = d.Get("payment_type")
parameterMapList := make([]map[string]interface{}, 0)
if d.HasChange("cfw_service") {
update = true
}
if v, ok := d.GetOk("cfw_service"); ok {
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "CfwService",
"Value": v,
})
}
if d.HasChange("fw_vpc_number") {
update = true
}
if v, ok := d.GetOk("fw_vpc_number"); ok {
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "FwVpcNumber",
"Value": v,
})
}
if d.HasChange("ip_number") {
update = true
}
if v, ok := d.GetOk("ip_number"); ok {
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "IpNumber",
"Value": v,
})
}
if d.HasChange("cfw_log_storage") {
update = true
}
if v, ok := d.GetOk("cfw_log_storage"); ok {
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "CfwLogStorage",
"Value": v,
})
}
if d.HasChange("cfw_log") {
update = true
}
if v, ok := d.GetOk("cfw_log"); ok {
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "CfwLog",
"Value": v,
})
}
if d.HasChange("band_width") {
update = true
}
if v, ok := d.GetOk("band_width"); ok {
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "BandWidth",
"Value": v,
})
}
if d.HasChange("spec") {
update = true
}
if v, ok := d.GetOk("spec"); ok {
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "Spec",
"Value": convertCloudFirewallInstanceVersion(v.(string)),
})
}
if d.HasChange("instance_count") {
update = true
}
if v, ok := d.GetOk("instance_count"); ok {
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "InstanceCount",
"Value": v,
})
}
modifyInstanceRequest["Parameter"] = parameterMapList
if update {
if v, ok := d.GetOk("modify_type"); ok {
modifyInstanceRequest["ModifyType"] = v
}
action := "ModifyInstance"
modifyInstanceRequest["ClientToken"] = buildClientToken(action)
conn, err := client.NewBssopenapiClient()
if err != nil {
return WrapError(err)
}
modifyInstanceRequest["ClientToken"] = buildClientToken(action)
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-14"), StringPointer("AK"), nil, modifyInstanceRequest, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"NotApplicable"}) {
conn.Endpoint = String(connectivity.BssOpenAPIEndpointInternational)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyInstanceRequest)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetPartial("payment_type")
d.SetPartial("cfw_service")
d.SetPartial("fw_vpc_number")
d.SetPartial("ip_number")
d.SetPartial("cfw_log_storage")
d.SetPartial("cfw_log")
d.SetPartial("band_width")
d.SetPartial("spec")
d.SetPartial("instance_count")
}
d.Partial(false)
return resourceAlicloudCloudFirewallInstanceRead(d, meta)
}
func resourceAlicloudCloudFirewallInstanceDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudCloudFirewallInstance. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
func convertCloudFirewallInstanceVersion(source string) interface{} {
switch source {
case "premium_version":
return 2
case "enterprise_version":
return 3
case "ultimate_version":
return 4
}
return source
}
func convertCloudFirewallInstanceRenewalDurationUnitResponse(source interface{}) interface{} {
switch source {
case "M":
return "Month"
case "Y":
return "Year"
}
return source
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCloudSsoAccessAssignment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCloudSsoAccessAssignmentCreate,
Read: resourceAlicloudCloudSsoAccessAssignmentRead,
Update: resourceAlicloudCloudSsoAccessAssignmentUpdate,
Delete: resourceAlicloudCloudSsoAccessAssignmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
Delete: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"access_configuration_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"deprovision_strategy": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"DeprovisionForLastAccessAssignmentOnAccount", "None"}, false),
},
"directory_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"principal_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"principal_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Group", "User"}, false),
},
"target_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"target_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"RD-Account"}, false),
},
},
}
}
func resourceAlicloudCloudSsoAccessAssignmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateAccessAssignment"
request := make(map[string]interface{})
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
request["AccessConfigurationId"] = d.Get("access_configuration_id")
request["DirectoryId"] = d.Get("directory_id")
request["PrincipalId"] = d.Get("principal_id")
request["PrincipalType"] = d.Get("principal_type")
request["TargetId"] = d.Get("target_id")
request["TargetType"] = d.Get("target_type")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"OperationConflict.Task"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloud_sso_access_assignment", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["DirectoryId"], ":", request["AccessConfigurationId"], ":", request["TargetType"], ":", request["TargetId"], ":", request["PrincipalType"], ":", request["PrincipalId"]))
v, err := jsonpath.Get("$.Task", response)
if err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
response = v.(map[string]interface{})
cloudssoService := CloudssoService{client}
stateConf := BuildStateConf([]string{}, []string{"Success"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, cloudssoService.CloudssoServiceAccessAssignmentStateRefreshFunc(fmt.Sprint(request["DirectoryId"]), fmt.Sprint(response["TaskId"]), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudCloudSsoAccessAssignmentRead(d, meta)
}
func resourceAlicloudCloudSsoAccessAssignmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudssoService := CloudssoService{client}
_, err := cloudssoService.DescribeCloudSsoAccessAssignment(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cloud_sso_access_assignment cloudssoService.DescribeCloudSsoAccessAssignment Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 6)
if err != nil {
return WrapError(err)
}
d.Set("directory_id", parts[0])
d.Set("access_configuration_id", parts[1])
d.Set("target_type", parts[2])
d.Set("target_id", parts[3])
d.Set("principal_type", parts[4])
d.Set("principal_id", parts[5])
return nil
}
func resourceAlicloudCloudSsoAccessAssignmentUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return resourceAlicloudCloudSsoAccessAssignmentRead(d, meta)
}
func resourceAlicloudCloudSsoAccessAssignmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 6)
if err != nil {
return WrapError(err)
}
action := "DeleteAccessAssignment"
var response map[string]interface{}
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DirectoryId": parts[0],
"AccessConfigurationId": parts[1],
"TargetType": parts[2],
"TargetId": parts[3],
"PrincipalType": parts[4],
"PrincipalId": parts[5],
}
if v, ok := d.GetOk("deprovision_strategy"); ok {
request["DeprovisionStrategy"] = v
} else {
request["DeprovisionStrategy"] = "DeprovisionForLastAccessAssignmentOnAccount"
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"OperationConflict.Task", "DeletionConflict.AccessConfigurationProvisioning.AccessAssignment"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Task", response)
if err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
response = v.(map[string]interface{})
cloudssoService := CloudssoService{client}
stateConf := BuildStateConf([]string{}, []string{"Success"}, d.Timeout(schema.TimeoutDelete), 5*time.Second, cloudssoService.CloudssoServiceAccessAssignmentStateRefreshFunc(fmt.Sprint(request["DirectoryId"]), fmt.Sprint(response["TaskId"]), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCloudSsoAccessConfiguration() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCloudSsoAccessConfigurationCreate,
Read: resourceAlicloudCloudSsoAccessConfigurationRead,
Update: resourceAlicloudCloudSsoAccessConfigurationUpdate,
Delete: resourceAlicloudCloudSsoAccessConfigurationDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
Update: schema.DefaultTimeout(5 * time.Minute),
Delete: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"access_configuration_id": {
Type: schema.TypeString,
Computed: true,
},
"access_configuration_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-zA-z0-9-]{1,32}$`), "The name of the resource. The name can be up to `32` characters long and can contain letters, digits, and hyphens (-)"),
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(0, 1024),
},
"directory_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"force_remove_permission_policies": {
Type: schema.TypeBool,
Optional: true,
},
"permission_policies": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"permission_policy_document": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"permission_policy_name": {
Type: schema.TypeString,
Required: true,
},
"permission_policy_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"System", "Inline"}, false),
},
},
},
},
"relay_state": {
Type: schema.TypeString,
Optional: true,
},
"session_duration": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(900, 43200),
},
},
}
}
func resourceAlicloudCloudSsoAccessConfigurationCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateAccessConfiguration"
request := make(map[string]interface{})
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
request["AccessConfigurationName"] = d.Get("access_configuration_name")
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["DirectoryId"] = d.Get("directory_id")
if v, ok := d.GetOk("relay_state"); ok {
request["RelayState"] = v
}
if v, ok := d.GetOk("session_duration"); ok {
request["SessionDuration"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloud_sso_access_configuration", action, AlibabaCloudSdkGoERROR)
}
responseAccessConfiguration := response["AccessConfiguration"].(map[string]interface{})
d.SetId(fmt.Sprint(request["DirectoryId"], ":", responseAccessConfiguration["AccessConfigurationId"]))
return resourceAlicloudCloudSsoAccessConfigurationUpdate(d, meta)
}
func resourceAlicloudCloudSsoAccessConfigurationRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudssoService := CloudssoService{client}
object, err := cloudssoService.DescribeCloudSsoAccessConfiguration(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cloud_sso_access_configuration cloudssoService.DescribeCloudSsoAccessConfiguration Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("access_configuration_id", parts[1])
d.Set("directory_id", parts[0])
d.Set("access_configuration_name", object["AccessConfigurationName"])
d.Set("description", object["Description"])
d.Set("relay_state", object["RelayState"])
if v, ok := object["SessionDuration"]; ok && fmt.Sprint(v) != "0" {
d.Set("session_duration", formatInt(v))
}
listPermissionPoliciesInAccessConfigurationObject, err := cloudssoService.ListPermissionPoliciesInAccessConfiguration(d.Id())
if err != nil {
return WrapError(err)
}
if permissionPoliciesList, ok := listPermissionPoliciesInAccessConfigurationObject["PermissionPolicies"]; ok && permissionPoliciesList != nil {
permissionPoliciesMaps := make([]map[string]interface{}, 0)
for _, permissionPoliciesListItem := range permissionPoliciesList.([]interface{}) {
if permissionPoliciesListItemMap, ok := permissionPoliciesListItem.(map[string]interface{}); ok {
permissionPoliciesListItemMaps := map[string]interface{}{}
permissionPoliciesListItemMaps["permission_policy_name"] = permissionPoliciesListItemMap["PermissionPolicyName"]
permissionPoliciesListItemMaps["permission_policy_type"] = permissionPoliciesListItemMap["PermissionPolicyType"]
permissionPoliciesListItemMaps["permission_policy_document"] = permissionPoliciesListItemMap["PermissionPolicyDocument"]
permissionPoliciesMaps = append(permissionPoliciesMaps, permissionPoliciesListItemMaps)
}
}
d.Set("permission_policies", permissionPoliciesMaps)
}
return nil
}
func resourceAlicloudCloudSsoAccessConfigurationUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Partial(true)
if d.HasChange("permission_policies") {
oraw, nraw := d.GetChange("permission_policies")
removed := oraw.(*schema.Set).Difference(nraw.(*schema.Set)).List()
added := nraw.(*schema.Set).Difference(oraw.(*schema.Set)).List()
if len(removed) > 0 {
for _, permissions := range removed {
RemovePermissionPolicyFromAccessConfigurationReq := map[string]interface{}{
"AccessConfigurationId": parts[1],
"DirectoryId": parts[0],
}
permissionsArg := permissions.(map[string]interface{})
RemovePermissionPolicyFromAccessConfigurationReq["PermissionPolicyName"] = permissionsArg["permission_policy_name"]
RemovePermissionPolicyFromAccessConfigurationReq["PermissionPolicyType"] = permissionsArg["permission_policy_type"]
action := "RemovePermissionPolicyFromAccessConfiguration"
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, RemovePermissionPolicyFromAccessConfigurationReq, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"OperationConflict.Task"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, RemovePermissionPolicyFromAccessConfigurationReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
}
if len(added) > 0 {
for _, permissions := range added {
AddPermissionPolicyFromAccessConfigurationReq := map[string]interface{}{
"AccessConfigurationId": parts[1],
"DirectoryId": parts[0],
}
permissionsArg := permissions.(map[string]interface{})
AddPermissionPolicyFromAccessConfigurationReq["PermissionPolicyName"] = permissionsArg["permission_policy_name"]
AddPermissionPolicyFromAccessConfigurationReq["PermissionPolicyType"] = permissionsArg["permission_policy_type"]
if AddPermissionPolicyFromAccessConfigurationReq["PermissionPolicyType"] == "Inline" {
AddPermissionPolicyFromAccessConfigurationReq["InlinePolicyDocument"] = permissionsArg["permission_policy_document"]
}
action := "AddPermissionPolicyToAccessConfiguration"
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, AddPermissionPolicyFromAccessConfigurationReq, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"OperationConflict.Task"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, AddPermissionPolicyFromAccessConfigurationReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
}
// Provisioning access configuration when permission policies has changed.
cloudssoService := CloudssoService{client}
objects, err := cloudssoService.DescribeCloudSsoAccessConfigurationProvisionings(fmt.Sprint(parts[0]), fmt.Sprint(parts[1]))
if err != nil {
return WrapError(err)
}
for _, object := range objects {
err = cloudssoService.CloudssoServicAccessConfigurationProvisioning(fmt.Sprint(parts[0]), fmt.Sprint(parts[1]), fmt.Sprint(object["TargetType"]), fmt.Sprint(object["TargetId"]))
if err != nil {
return WrapError(err)
}
}
}
update := false
updateAccessConfigurationReq := map[string]interface{}{
"AccessConfigurationId": parts[1],
"DirectoryId": parts[0],
}
if d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
updateAccessConfigurationReq["NewDescription"] = v
}
}
if d.HasChange("relay_state") {
update = true
if v, ok := d.GetOk("relay_state"); ok {
updateAccessConfigurationReq["NewRelayState"] = v
}
}
if d.HasChange("session_duration") {
update = true
if v, ok := d.GetOk("session_duration"); ok {
updateAccessConfigurationReq["NewSessionDuration"] = v
}
}
if update {
action := "UpdateAccessConfiguration"
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, updateAccessConfigurationReq, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"OperationConflict.Task"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, updateAccessConfigurationReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("description")
d.SetPartial("relay_state")
d.SetPartial("session_duration")
}
d.Partial(false)
return resourceAlicloudCloudSsoAccessConfigurationRead(d, meta)
}
func resourceAlicloudCloudSsoAccessConfigurationDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("permission_policies"); ok {
removed := v.(*schema.Set).List()
if len(removed) > 0 {
for _, permissions := range removed {
RemovePermissionPolicyFromAccessConfigurationReq := map[string]interface{}{
"AccessConfigurationId": parts[1],
"DirectoryId": parts[0],
}
permissionsArg := permissions.(map[string]interface{})
RemovePermissionPolicyFromAccessConfigurationReq["PermissionPolicyName"] = permissionsArg["permission_policy_name"]
RemovePermissionPolicyFromAccessConfigurationReq["PermissionPolicyType"] = permissionsArg["permission_policy_type"]
action := "RemovePermissionPolicyFromAccessConfiguration"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, RemovePermissionPolicyFromAccessConfigurationReq, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"OperationConflict.Task"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, RemovePermissionPolicyFromAccessConfigurationReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
}
}
action := "DeleteAccessConfiguration"
request := map[string]interface{}{
"AccessConfigurationId": parts[1],
"DirectoryId": parts[0],
}
if v, ok := d.GetOk("force_remove_permission_policies"); ok {
request["ForceRemovePermissionPolicies"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"DeletionConflict.AccessConfiguration.Provisioning", "DeletionConflict.AccessConfiguration.AccessAssignment", "OperationConflict.Task", "DeletionConflict.AccessConfiguration.Task"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.AccessConfiguration"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCloudSsoAccessConfigurationProvisioning() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCloudSsoAccessConfigurationProvisioningCreate,
Read: resourceAlicloudCloudSsoAccessConfigurationProvisioningRead,
Update: resourceAlicloudCloudSsoAccessConfigurationProvisioningUpdate,
Delete: resourceAlicloudCloudSsoAccessConfigurationProvisioningDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"access_configuration_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"directory_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"target_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"target_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"RD-Account"}, false),
},
"status": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Provisioned"}, false),
},
},
}
}
func resourceAlicloudCloudSsoAccessConfigurationProvisioningCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudssoService := CloudssoService{client}
err := cloudssoService.CloudssoServicAccessConfigurationProvisioning(fmt.Sprint(d.Get("directory_id")), fmt.Sprint(d.Get("access_configuration_id")), fmt.Sprint(d.Get("target_type")), fmt.Sprint(d.Get("target_id")))
if err != nil {
return WrapError(err)
}
d.SetId(fmt.Sprint(d.Get("directory_id"), ":", d.Get("access_configuration_id"), ":", d.Get("target_type"), ":", d.Get("target_id")))
return resourceAlicloudCloudSsoAccessConfigurationProvisioningRead(d, meta)
}
func resourceAlicloudCloudSsoAccessConfigurationProvisioningRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudssoService := CloudssoService{client}
object, err := cloudssoService.DescribeCloudSsoAccessConfigurationProvisioning(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cloud_sso_access_configuration_provisioning cloudssoService.DescribeCloudSsoAccessConfigurationProvisioning Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 4)
if err != nil {
return WrapError(err)
}
d.Set("access_configuration_id", parts[1])
d.Set("directory_id", parts[0])
d.Set("target_id", parts[3])
d.Set("target_type", parts[2])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudCloudSsoAccessConfigurationProvisioningUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudssoService := CloudssoService{client}
if d.HasChange("status") {
object, err := cloudssoService.DescribeCloudSsoAccessConfigurationProvisioning(d.Id())
if err != nil && !NotFoundError(err) {
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 4)
if err != nil {
return WrapError(err)
}
if v, ok := object["Status"]; !ok || fmt.Sprint(v) != "Provisioned" {
cloudssoService := CloudssoService{client}
err := cloudssoService.CloudssoServicAccessConfigurationProvisioning(fmt.Sprint(parts[0]), fmt.Sprint(parts[1]), fmt.Sprint(parts[2]), fmt.Sprint(parts[3]))
if err != nil {
return WrapError(err)
}
}
}
return resourceAlicloudCloudSsoAccessConfigurationProvisioningRead(d, meta)
}
func resourceAlicloudCloudSsoAccessConfigurationProvisioningDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 4)
if err != nil {
return WrapError(err)
}
action := "DeprovisionAccessConfiguration"
var response map[string]interface{}
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AccessConfigurationId": parts[1],
"DirectoryId": parts[0],
"TargetId": parts[3],
"TargetType": parts[2],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"OperationConflict.Task", "DeletionConflict.AccessConfigurationProvisioning.AccessAssignment"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.AccessConfigurationProvisioning"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Tasks", response)
if err != nil || len(v.([]interface{})) < 1 {
return WrapErrorf(err, IdMsg, d.Id())
}
response = v.([]interface{})[0].(map[string]interface{})
cloudssoService := CloudssoService{client}
_, err = cloudssoService.GetTaskStatus(fmt.Sprint(request["DirectoryId"]), fmt.Sprint(response["TaskId"]))
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
stateConf := BuildStateConf([]string{}, []string{"Success"}, d.Timeout(schema.TimeoutDelete), 5*time.Second, cloudssoService.CloudssoServiceAccessConfigurationProvisioningStateRefreshFunc(fmt.Sprint(request["DirectoryId"]), fmt.Sprint(response["TaskId"]), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCloudSsoDirectory() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCloudSsoDirectoryCreate,
Read: resourceAlicloudCloudSsoDirectoryRead,
Update: resourceAlicloudCloudSsoDirectoryUpdate,
Delete: resourceAlicloudCloudSsoDirectoryDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"directory_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-z0-9-]{1,64}$`), "The name of the resource. The name must be 2 to 64 characters in length and can contain lower case letters, digits, and hyphens (-)."),
},
"mfa_authentication_status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Disabled", "Enabled"}, false),
},
"saml_identity_provider_configuration": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"encoded_metadata_document": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
Computed: true,
},
"sso_status": {
Computed: true,
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Disabled", "Enabled"}, false),
},
},
},
ForceNew: true,
},
"scim_synchronization_status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Disabled", "Enabled"}, false),
},
},
}
}
func resourceAlicloudCloudSsoDirectoryCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateDirectory"
request := make(map[string]interface{})
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("directory_name"); ok {
request["DirectoryName"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloud_sso_directory", action, AlibabaCloudSdkGoERROR)
}
responseDirectory := response["Directory"].(map[string]interface{})
d.SetId(fmt.Sprint(responseDirectory["DirectoryId"]))
return resourceAlicloudCloudSsoDirectoryUpdate(d, meta)
}
func resourceAlicloudCloudSsoDirectoryRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudssoService := CloudssoService{client}
getDirectoryObject, err := cloudssoService.DescribeCloudSsoDirectory(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cloud_sso_directory cloudssoService.DescribeCloudSsoDirectory Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("directory_name", getDirectoryObject["DirectoryName"])
d.Set("mfa_authentication_status", getDirectoryObject["MFAAuthenticationStatus"])
d.Set("scim_synchronization_status", getDirectoryObject["SCIMSynchronizationStatus"])
if SAMLIdentityProviderConfiguration, ok := getDirectoryObject["SAMLIdentityProviderConfiguration"]; ok && len(SAMLIdentityProviderConfiguration.(map[string]interface{})) > 0 {
SAMLIdentityProviderConfigurationSli := make([]map[string]interface{}, 0)
SAMLIdentityProviderConfigurationMap := make(map[string]interface{})
SAMLIdentityProviderConfigurationMap["sso_status"] = SAMLIdentityProviderConfiguration.(map[string]interface{})["SSOStatus"]
if v, ok := SAMLIdentityProviderConfiguration.(map[string]interface{})["EncodedMetadataDocument"]; ok {
SAMLIdentityProviderConfigurationMap["encoded_metadata_document"] = v
}
SAMLIdentityProviderConfigurationSli = append(SAMLIdentityProviderConfigurationSli, SAMLIdentityProviderConfigurationMap)
d.Set("saml_identity_provider_configuration", SAMLIdentityProviderConfigurationSli)
}
return nil
}
func resourceAlicloudCloudSsoDirectoryUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"DirectoryId": d.Id(),
}
if d.HasChange("mfa_authentication_status") {
update = true
if v, ok := d.GetOk("mfa_authentication_status"); ok {
request["MFAAuthenticationStatus"] = v
}
}
if update {
action := "SetMFAAuthenticationStatus"
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("mfa_authentication_status")
}
update = false
setSCIMSynchronizationStatusReq := map[string]interface{}{
"DirectoryId": d.Id(),
}
if d.HasChange("scim_synchronization_status") {
update = true
if v, ok := d.GetOk("scim_synchronization_status"); ok {
setSCIMSynchronizationStatusReq["SCIMSynchronizationStatus"] = v
}
}
if update {
action := "SetSCIMSynchronizationStatus"
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, setSCIMSynchronizationStatusReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, setSCIMSynchronizationStatusReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("scim_synchronization_status")
}
update = false
updateDirectoryReq := map[string]interface{}{
"DirectoryId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("directory_name") {
update = true
if v, ok := d.GetOk("directory_name"); ok {
updateDirectoryReq["NewDirectoryName"] = v
}
}
if update {
action := "UpdateDirectory"
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, updateDirectoryReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, updateDirectoryReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("directory_name")
}
update = false
setExternalSAMLIdentityProviderReq := map[string]interface{}{
"DirectoryId": d.Id(),
}
if d.HasChange("saml_identity_provider_configuration") {
update = true
if v, ok := d.GetOk("saml_identity_provider_configuration"); ok {
for _, setExternalSAMLIdentityProvider := range v.(*schema.Set).List() {
setExternalSAMLIdentityProviderArg := setExternalSAMLIdentityProvider.(map[string]interface{})
if v, ok := setExternalSAMLIdentityProviderArg["sso_status"]; ok && v != "" {
setExternalSAMLIdentityProviderReq["SSOStatus"] = v
}
if v, ok := setExternalSAMLIdentityProviderArg["encoded_metadata_document"]; ok && v != "" {
setExternalSAMLIdentityProviderReq["EncodedMetadataDocument"] = v
}
}
}
}
if update {
action := "SetExternalSAMLIdentityProvider"
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, setExternalSAMLIdentityProviderReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, setExternalSAMLIdentityProviderReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("saml_identity_provider_configuration")
}
d.Partial(false)
return resourceAlicloudCloudSsoDirectoryRead(d, meta)
}
func resourceAlicloudCloudSsoDirectoryDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
if _, ok := d.GetOk("saml_identity_provider_configuration"); ok {
deleteExternalSAMLIdentityProviderReq := map[string]interface{}{
"DirectoryId": d.Id(),
}
deleteExternalSAMLIdentityProviderReq["SSOStatus"] = "Disabled"
action := "SetExternalSAMLIdentityProvider"
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, deleteExternalSAMLIdentityProviderReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, deleteExternalSAMLIdentityProviderReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
clearExternalSAMLIdentityProviderReq := map[string]interface{}{
"DirectoryId": d.Id(),
}
action = "ClearExternalSAMLIdentityProvider"
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, clearExternalSAMLIdentityProviderReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, clearExternalSAMLIdentityProviderReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
action := "DeleteDirectory"
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DirectoryId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"DeletionConflict.Directory.Task"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Directory"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCloudSsoGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCloudSsoGroupCreate,
Read: resourceAlicloudCloudSsoGroupRead,
Update: resourceAlicloudCloudSsoGroupUpdate,
Delete: resourceAlicloudCloudSsoGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(0, 1024),
},
"directory_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"group_id": {
Type: schema.TypeString,
Computed: true,
},
"group_name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[\w-.]{1,128}$`), "The name of the resource. The name must be 1 to 128 characters in length and can contain letters, digits, periods (.), underscores (_), and hyphens (-)."),
},
},
}
}
func resourceAlicloudCloudSsoGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateGroup"
request := make(map[string]interface{})
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["DirectoryId"] = d.Get("directory_id")
request["GroupName"] = d.Get("group_name")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloud_sso_group", action, AlibabaCloudSdkGoERROR)
}
responseGroup := response["Group"].(map[string]interface{})
d.SetId(fmt.Sprint(request["DirectoryId"], ":", responseGroup["GroupId"]))
return resourceAlicloudCloudSsoGroupRead(d, meta)
}
func resourceAlicloudCloudSsoGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudssoService := CloudssoService{client}
object, err := cloudssoService.DescribeCloudSsoGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cloud_sso_group cloudssoService.DescribeCloudSsoGroup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("directory_id", parts[0])
d.Set("group_id", parts[1])
d.Set("description", object["Description"])
d.Set("group_name", object["GroupName"])
return nil
}
func resourceAlicloudCloudSsoGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"DirectoryId": parts[0],
"GroupId": parts[1],
}
if d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
request["NewDescription"] = v
}
}
if d.HasChange("group_name") {
update = true
if v, ok := d.GetOk("group_name"); ok {
request["NewGroupName"] = v
}
}
if update {
action := "UpdateGroup"
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudCloudSsoGroupRead(d, meta)
}
func resourceAlicloudCloudSsoGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteGroup"
var response map[string]interface{}
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DirectoryId": parts[0],
"GroupId": parts[1],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"DeletionConflict.Group.AccessAssigment"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Group"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCloudSsoScimServerCredential() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCloudSsoScimServerCredentialCreate,
Read: resourceAlicloudCloudSsoScimServerCredentialRead,
Update: resourceAlicloudCloudSsoScimServerCredentialUpdate,
Delete: resourceAlicloudCloudSsoScimServerCredentialDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"credential_id": {
Type: schema.TypeString,
Computed: true,
},
"directory_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Disabled", "Enabled"}, false),
},
},
}
}
func resourceAlicloudCloudSsoScimServerCredentialCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateSCIMServerCredential"
request := make(map[string]interface{})
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
request["DirectoryId"] = d.Get("directory_id")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloud_sso_scim_server_credential", action, AlibabaCloudSdkGoERROR)
}
responseSCIMServerCredential := response["SCIMServerCredential"].(map[string]interface{})
d.SetId(fmt.Sprint(request["DirectoryId"], ":", responseSCIMServerCredential["CredentialId"]))
return resourceAlicloudCloudSsoScimServerCredentialUpdate(d, meta)
}
func resourceAlicloudCloudSsoScimServerCredentialRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudssoService := CloudssoService{client}
object, err := cloudssoService.DescribeCloudSsoScimServerCredential(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cloud_sso_scim_server_credential cloudssoService.DescribeCloudSsoScimServerCredential Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("credential_id", parts[1])
d.Set("directory_id", parts[0])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudCloudSsoScimServerCredentialUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"CredentialId": parts[1],
"DirectoryId": parts[0],
}
if d.HasChange("status") {
if v, ok := d.GetOk("status"); ok {
request["NewStatus"] = v
}
}
action := "UpdateSCIMServerCredentialStatus"
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return resourceAlicloudCloudSsoScimServerCredentialRead(d, meta)
}
func resourceAlicloudCloudSsoScimServerCredentialDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteSCIMServerCredential"
var response map[string]interface{}
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"CredentialId": parts[1],
"DirectoryId": parts[0],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.SCIMCredential"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCloudSsoUser() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCloudSsoUserCreate,
Read: resourceAlicloudCloudSsoUserRead,
Update: resourceAlicloudCloudSsoUserUpdate,
Delete: resourceAlicloudCloudSsoUserDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(0, 1024),
},
"directory_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"display_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(0, 256),
},
"email": {
Type: schema.TypeString,
Optional: true,
},
"first_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(0, 64),
},
"last_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(0, 64),
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Disabled", "Enabled"}, false),
},
"user_id": {
Type: schema.TypeString,
Computed: true,
},
"user_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[\w-.@]{1,64}$`), "The name of the resource. The name must be 1 to 64 characters in length and can contain letters, digits, at signs (@), periods (.), underscores (_), and hyphens (-)."),
},
},
}
}
func resourceAlicloudCloudSsoUserCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateUser"
request := make(map[string]interface{})
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["DirectoryId"] = d.Get("directory_id")
if v, ok := d.GetOk("display_name"); ok {
request["DisplayName"] = v
}
if v, ok := d.GetOk("email"); ok {
request["Email"] = v
}
if v, ok := d.GetOk("first_name"); ok {
request["FirstName"] = v
}
if v, ok := d.GetOk("last_name"); ok {
request["LastName"] = v
}
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
if v, ok := d.GetOk("user_name"); ok {
request["UserName"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloud_sso_user", action, AlibabaCloudSdkGoERROR)
}
responseUser := response["User"].(map[string]interface{})
d.SetId(fmt.Sprint(request["DirectoryId"], ":", responseUser["UserId"]))
return resourceAlicloudCloudSsoUserRead(d, meta)
}
func resourceAlicloudCloudSsoUserRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudssoService := CloudssoService{client}
object, err := cloudssoService.DescribeCloudSsoUser(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cloud_sso_user cloudssoService.DescribeCloudSsoUser Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("directory_id", parts[0])
d.Set("user_id", parts[1])
d.Set("description", object["Description"])
d.Set("display_name", object["DisplayName"])
d.Set("email", object["Email"])
d.Set("first_name", object["FirstName"])
d.Set("last_name", object["LastName"])
d.Set("status", object["Status"])
d.Set("user_name", object["UserName"])
return nil
}
func resourceAlicloudCloudSsoUserUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Partial(true)
update := false
request := map[string]interface{}{
"DirectoryId": parts[0],
"UserId": parts[1],
}
if d.HasChange("status") {
update = true
if v, ok := d.GetOk("status"); ok {
request["NewStatus"] = v
}
}
if update {
action := "UpdateUserStatus"
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("status")
}
update = false
updateUserReq := map[string]interface{}{
"DirectoryId": parts[0],
"UserId": parts[1],
}
if d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
updateUserReq["NewDescription"] = v
}
}
if d.HasChange("display_name") {
update = true
if v, ok := d.GetOk("display_name"); ok {
updateUserReq["NewDisplayName"] = v
}
}
if d.HasChange("email") {
update = true
if v, ok := d.GetOk("email"); ok {
updateUserReq["NewEmail"] = v
}
}
if d.HasChange("first_name") {
update = true
if v, ok := d.GetOk("first_name"); ok {
updateUserReq["NewFirstName"] = v
}
}
if d.HasChange("last_name") {
update = true
if v, ok := d.GetOk("last_name"); ok {
updateUserReq["NewLastName"] = v
}
}
if update {
action := "UpdateUser"
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, updateUserReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, updateUserReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("description")
d.SetPartial("display_name")
d.SetPartial("email")
d.SetPartial("first_name")
d.SetPartial("last_name")
}
d.Partial(false)
return resourceAlicloudCloudSsoUserRead(d, meta)
}
func resourceAlicloudCloudSsoUserDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteUser"
var response map[string]interface{}
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DirectoryId": parts[0],
"UserId": parts[1],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"DeletionConflict.User.AccessAssigment"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.User"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCloudSsoUserAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCloudSsoUserAttachmentCreate,
Read: resourceAlicloudCloudSsoUserAttachmentRead,
Delete: resourceAlicloudCloudSsoUserAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"directory_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"user_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudCloudSsoUserAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AddUserToGroup"
request := make(map[string]interface{})
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
request["DirectoryId"] = d.Get("directory_id")
request["GroupId"] = d.Get("group_id")
request["UserId"] = d.Get("user_id")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloud_sso_user_attachment", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["DirectoryId"], ":", request["GroupId"], ":", request["UserId"]))
return resourceAlicloudCloudSsoUserAttachmentRead(d, meta)
}
func resourceAlicloudCloudSsoUserAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudssoService := CloudssoService{client}
_, err := cloudssoService.DescribeCloudSsoUserAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cloud_sso_user_attachment cloudssoService.DescribeCloudSsoUserAttachment Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
d.Set("directory_id", parts[0])
d.Set("group_id", parts[1])
d.Set("user_id", parts[2])
return nil
}
func resourceAlicloudCloudSsoUserAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
action := "RemoveUserFromGroup"
var response map[string]interface{}
conn, err := client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DirectoryId": parts[0],
"GroupId": parts[1],
"UserId": parts[2],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCloudStorageGatewayExpressSync() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCloudStorageGatewayExpressSyncCreate,
Read: resourceAlicloudCloudStorageGatewayExpressSyncRead,
Delete: resourceAlicloudCloudStorageGatewayExpressSyncDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Delete: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"bucket_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"bucket_prefix": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"bucket_region": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(0, 255),
},
"express_sync_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile("^[\u4e00-\u9fa5a-zA-Z][\u4e00-\u9fa5a-zA-Z0-9-_.]{0,127}$"), "The length of the name is limited to `1` to `128` characters. It can contain uppercase and lowercase letters, Chinese characters, numbers, English periods (.), underscores (_), or hyphens (-), and must start with letters."),
},
},
}
}
func resourceAlicloudCloudStorageGatewayExpressSyncCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateExpressSync"
request := make(map[string]interface{})
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
request["BucketName"] = d.Get("bucket_name")
if v, ok := d.GetOk("bucket_prefix"); ok {
request["BucketPrefix"] = v
}
request["BucketRegion"] = d.Get("bucket_region")
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["Name"] = d.Get("express_sync_name")
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloud_storage_gateway_express_sync", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetId(fmt.Sprint(response["ExpressSyncId"]))
return resourceAlicloudCloudStorageGatewayExpressSyncRead(d, meta)
}
func resourceAlicloudCloudStorageGatewayExpressSyncRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sgwService := SgwService{client}
object, err := sgwService.DescribeExpressSyncs(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cloud_storage_gateway_express_sync sgwService.DescribeExpressSyncs Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("bucket_name", object["BucketName"])
d.Set("bucket_prefix", object["BucketPrefix"])
d.Set("bucket_region", object["BucketRegion"])
d.Set("description", object["Description"])
d.Set("express_sync_name", object["Name"])
return nil
}
func resourceAlicloudCloudStorageGatewayExpressSyncDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sgwService := SgwService{client}
action := "DeleteExpressSync"
var response map[string]interface{}
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ExpressSyncId": d.Id(),
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ExpressSyncNotExist"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
stateConf := BuildStateConf([]string{}, []string{"task.state.completed"}, d.Timeout(schema.TimeoutDelete), 1*time.Second, sgwService.CloudStorageGatewayTaskStateRefreshFunc(d.Id(), fmt.Sprint(response["TaskId"]), []string{"task.state.failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCloudStorageGatewayExpressSyncShareAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCloudStorageGatewayExpressSyncShareAttachmentCreate,
Read: resourceAlicloudCloudStorageGatewayExpressSyncShareAttachmentRead,
Delete: resourceAlicloudCloudStorageGatewayExpressSyncShareAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
Delete: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"express_sync_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"gateway_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"share_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudCloudStorageGatewayExpressSyncShareAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sgwService := SgwService{client}
var response map[string]interface{}
action := "AddSharesToExpressSync"
request := make(map[string]interface{})
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
request["ExpressSyncId"] = d.Get("express_sync_id")
sharesMaps := make(map[string]interface{})
gatewayId := fmt.Sprint(d.Get("gateway_id"))
shareName := fmt.Sprint(d.Get("share_name"))
sharesMaps[gatewayId] = shareName
if v, err := convertMaptoJsonString(sharesMaps); err != nil {
return WrapError(err)
} else {
request["GatewayShares"] = v
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloud_storage_gateway_express_sync_share_attachment", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
stateConf := BuildStateConf([]string{}, []string{"task.state.completed"}, d.Timeout(schema.TimeoutCreate), 1*time.Second, sgwService.CloudStorageGatewayTaskStateRefreshFunc(fmt.Sprint(request["ExpressSyncId"]), fmt.Sprint(response["TaskId"]), []string{"task.state.failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetId(fmt.Sprint(request["ExpressSyncId"], ":", gatewayId, ":", shareName))
return resourceAlicloudCloudStorageGatewayExpressSyncShareAttachmentRead(d, meta)
}
func resourceAlicloudCloudStorageGatewayExpressSyncShareAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sgwService := SgwService{client}
object, err := sgwService.DescribeExpressSyncShares(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cloud_storage_gateway_express_sync sgwService.DescribeExpressSyncShares Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("express_sync_id", object["ExpressSyncId"])
d.Set("gateway_id", object["GatewayId"])
d.Set("share_name", object["ShareName"])
return nil
}
func resourceAlicloudCloudStorageGatewayExpressSyncShareAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sgwService := SgwService{client}
var response map[string]interface{}
action := "RemoveSharesFromExpressSync"
request := make(map[string]interface{})
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
request["ExpressSyncId"] = parts[0]
sharesMaps := make(map[string]interface{})
gatewayId := fmt.Sprint(parts[1])
shareName := fmt.Sprint(parts[2])
sharesMaps[gatewayId] = shareName
if v, err := convertMaptoJsonString(sharesMaps); err != nil {
return WrapError(err)
} else {
request["GatewayShares"] = v
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ExpressSyncNotExist", "GatewayNotExist"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
stateConf := BuildStateConf([]string{}, []string{"task.state.completed"}, d.Timeout(schema.TimeoutDelete), 1*time.Second, sgwService.CloudStorageGatewayTaskStateRefreshFunc(parts[0], fmt.Sprint(response["TaskId"]), []string{"task.state.failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCloudStorageGatewayGateway() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCloudStorageGatewayGatewayCreate,
Read: resourceAlicloudCloudStorageGatewayGatewayRead,
Update: resourceAlicloudCloudStorageGatewayGatewayUpdate,
Delete: resourceAlicloudCloudStorageGatewayGatewayDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"location": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"Cloud", "On_Premise"}, false),
Required: true,
ForceNew: true,
},
"storage_bundle_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"type": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"File", "Iscsi"}, false),
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"gateway_class": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"Basic", "Standard", "Enhanced", "Advanced"}, false),
Optional: true,
},
"gateway_name": {
Type: schema.TypeString,
Required: true,
},
"payment_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo"}, false),
Default: "PayAsYouGo",
},
"public_network_bandwidth": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(5, 200),
Computed: true,
Optional: true,
},
"reason_detail": {
Type: schema.TypeString,
Optional: true,
},
"reason_type": {
Type: schema.TypeString,
Optional: true,
},
"release_after_expiration": {
Type: schema.TypeBool,
Optional: true,
},
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudCloudStorageGatewayGatewayCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateGateway"
request := make(map[string]interface{})
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("gateway_class"); ok {
request["GatewayClass"] = v
}
request["Location"] = d.Get("location")
request["Name"] = d.Get("gateway_name")
if v, ok := d.GetOk("payment_type"); ok {
request["PostPaid"] = convertCsgGatewayPaymentTypeReq(v.(string))
}
if v, ok := d.GetOk("public_network_bandwidth"); ok {
request["PublicNetworkBandwidth"] = v
}
if v, ok := d.GetOkExists("release_after_expiration"); ok {
request["ReleaseAfterExpiration"] = v
}
request["StorageBundleId"] = d.Get("storage_bundle_id")
request["Type"] = d.Get("type")
if v, ok := d.GetOk("vswitch_id"); ok {
request["VSwitchId"] = v
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"BadRequest"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloud_storage_gateway_gateway", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetId(fmt.Sprint(response["GatewayId"]))
if d.Get("location").(string) == "Cloud" {
action = "DeployGateway"
request = map[string]interface{}{
"GatewayId": d.Id(),
}
if id, ok := response["GatewayId"]; ok {
request["GatewayId"] = fmt.Sprint(id)
}
if v, ok := d.GetOk("gateway_class"); ok {
request["GatewayClass"] = v
}
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"BadRequest"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloud_storage_gateway_gateway", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
}
err = gatewayDescribeTasks(d, meta, d.Id())
if err != nil {
return WrapError(err)
}
return resourceAlicloudCloudStorageGatewayGatewayRead(d, meta)
}
func resourceAlicloudCloudStorageGatewayGatewayRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sgwService := SgwService{client}
var object map[string]interface{}
var err error
object, err = sgwService.DescribeCloudStorageGatewayGateway(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cloud_storage_gateway_gateway sgwService.DescribeCloudStorageGatewayGateway Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("payment_type", convertCsgGatewayPaymentTypeResp(object["IsPostPaid"].(bool)))
d.Set("description", object["Description"])
d.Set("gateway_class", object["GatewayClass"])
d.Set("gateway_name", object["Name"])
d.Set("location", object["Location"])
if v, ok := object["PublicNetworkBandwidth"]; ok && fmt.Sprint(v) != "0" {
d.Set("public_network_bandwidth", formatInt(v))
}
d.Set("status", object["Status"])
d.Set("storage_bundle_id", object["StorageBundleId"])
d.Set("type", object["Type"])
d.Set("vswitch_id", object["VSwitchId"])
return nil
}
func resourceAlicloudCloudStorageGatewayGatewayUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewHcsSgwClient()
var response map[string]interface{}
d.Partial(true)
request := map[string]interface{}{
"GatewayId": d.Id(),
}
if d.HasChange("description") || d.HasChange("gateway_name") {
action := "ModifyGateway"
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("gateway_name"); ok {
request["Name"] = v
}
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetPartial("description")
d.SetPartial("gateway_name")
}
if d.HasChange("public_network_bandwidth") {
err = gatewayDescribeTasks(d, meta, d.Id())
if err != nil {
return WrapError(err)
}
action := "ExpandGatewayNetworkBandwidth"
request = map[string]interface{}{
"GatewayId": d.Id(),
}
if v, ok := d.GetOk("public_network_bandwidth"); ok {
request["NewNetworkBandwidth"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
err = gatewayDescribeTasks(d, meta, d.Id())
if err != nil {
return WrapError(err)
}
d.SetPartial("public_network_bandwidth")
}
if d.HasChange("gateway_class") {
err = gatewayDescribeTasks(d, meta, d.Id())
if err != nil {
return WrapError(err)
}
action := "ModifyGatewayClass"
request = map[string]interface{}{
"GatewayId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
if v, ok := d.GetOk("gateway_class"); ok {
request["GatewayClass"] = v
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetPartial("gateway_class")
err = gatewayDescribeTasks(d, meta, d.Id())
if err != nil {
return WrapError(err)
}
}
}
d.Partial(false)
return resourceAlicloudCloudStorageGatewayGatewayRead(d, meta)
}
func resourceAlicloudCloudStorageGatewayGatewayDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewHcsSgwClient()
var response map[string]interface{}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = gatewayDescribeTasks(d, meta, d.Id())
if err != nil {
return WrapError(err)
}
action := "DeleteGateway"
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"GatewayId": d.Id(),
}
if v, ok := d.GetOk("reason_detail"); ok {
request["ReasonDetail"] = v
}
if v, ok := d.GetOk("reason_type"); ok {
request["ReasonType"] = v
}
wait = incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"GatewayNotExist"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
addDebug(action, response, request)
err = gatewayDescribeTasks(d, meta, d.Id())
if err != nil {
return WrapError(err)
}
return nil
}
func gatewayDescribeTasks(d *schema.ResourceData, meta interface{}, TargetId string) error {
action := "DescribeTasks"
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewHcsSgwClient()
var response map[string]interface{}
request := map[string]interface{}{
"GatewayId": d.Id(),
}
request["TargetId"] = TargetId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
tasks := response["Tasks"].(map[string]interface{})
for _, val := range tasks {
for _, task := range val.([]interface{}) {
if state, exist := task.(map[string]interface{})["StateCode"]; exist {
if state != "task.state.completed" {
return resource.RetryableError(fmt.Errorf("There are still tasks left"))
}
continue
}
}
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapError(err)
}
return nil
}
func convertCsgGatewayPaymentTypeReq(source interface{}) interface{} {
switch source {
case "PayAsYouGo":
return true
}
return source
}
func convertCsgGatewayPaymentTypeResp(source interface{}) interface{} {
switch source {
case true:
return "PayAsYouGo"
case false:
return "Subscription"
}
return source
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCloudStorageGatewayGatewayBlockVolume() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCloudStorageGatewayGatewayBlockVolumeCreate,
Read: resourceAlicloudCloudStorageGatewayGatewayBlockVolumeRead,
Update: resourceAlicloudCloudStorageGatewayGatewayBlockVolumeUpdate,
Delete: resourceAlicloudCloudStorageGatewayGatewayBlockVolumeDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"cache_mode": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Cache", "WriteThrough"}, false),
},
"chap_enabled": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"chap_in_password": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(12, 16),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOkExists("chap_enabled"); ok && v.(bool) {
return false
}
return true
},
},
"chap_in_user": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[A-Za-z0-9]{0,32}$`), "The chap_in_user must be 1 to 32 characters in length, and can contain letters and digits."),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOkExists("chap_enabled"); ok && v.(bool) {
return false
}
return true
},
},
"chunk_size": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.IntInSlice([]int{131072, 16384, 32768, 65536, 8192}),
},
"gateway_block_volume_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-z][a-z0-9]{0,31}$`), "The name must be 1 to 32 characters in length, and can contain lower case letters and digits."),
},
"gateway_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"index_id": {
Type: schema.TypeString,
Computed: true,
},
"is_source_deletion": {
Type: schema.TypeBool,
Optional: true,
},
"local_path": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("cache_mode"); ok && v.(string) == "Cache" {
return false
}
return true
},
},
"oss_bucket_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"oss_bucket_ssl": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
ForceNew: true,
},
"oss_endpoint": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"protocol": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"recovery": {
Type: schema.TypeBool,
Optional: true,
},
"size": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(1, 262144),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudCloudStorageGatewayGatewayBlockVolumeCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateGatewayBlockVolume"
request := make(map[string]interface{})
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("cache_mode"); ok {
request["CacheMode"] = v
}
if v, ok := d.GetOkExists("chap_enabled"); ok {
request["ChapEnabled"] = v
}
if v, ok := d.GetOk("chap_in_user"); ok {
request["ChapInUser"] = v
}
if v, ok := d.GetOk("chap_in_password"); ok {
request["ChapInPassword"] = v
}
if v, ok := d.GetOk("chunk_size"); ok {
request["ChunkSize"] = v
}
request["Name"] = d.Get("gateway_block_volume_name")
request["GatewayId"] = d.Get("gateway_id")
if v, ok := d.GetOk("local_path"); ok {
request["LocalFilePath"] = v
}
request["OssBucketName"] = d.Get("oss_bucket_name")
if v, ok := d.GetOkExists("oss_bucket_ssl"); ok {
request["OssBucketSsl"] = v
}
request["OssEndpoint"] = d.Get("oss_endpoint")
request["VolumeProtocol"] = d.Get("protocol")
if v, ok := d.GetOkExists("recovery"); ok {
request["Recovery"] = v
}
if v, ok := d.GetOk("size"); ok {
request["Size"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloud_storage_gateway_gateway_block_volume", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
sgwService := SgwService{client}
stateConf := BuildStateConf([]string{}, []string{"task.state.completed"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, sgwService.CloudStorageGatewayTaskStateRefreshFunc(request["GatewayId"].(string), response["TaskId"].(string), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
response, err = sgwService.DescribeTasks(request["GatewayId"].(string), response["TaskId"].(string))
if err != nil {
d.SetId("")
return WrapError(err)
}
d.SetId(fmt.Sprint(request["GatewayId"], ":", response["RelatedResourceId"]))
return resourceAlicloudCloudStorageGatewayGatewayBlockVolumeRead(d, meta)
}
func resourceAlicloudCloudStorageGatewayGatewayBlockVolumeRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sgwService := SgwService{client}
object, err := sgwService.DescribeCloudStorageGatewayGatewayBlockVolume(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cloud_storage_gateway_gateway_block_volume sgwService.DescribeCloudStorageGatewayGatewayBlockVolume Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("gateway_id", parts[0])
d.Set("index_id", parts[1])
d.Set("cache_mode", object["CacheMode"])
d.Set("chap_enabled", object["ChapEnabled"])
d.Set("chap_in_user", object["ChapInUser"])
if v, ok := object["ChunkSize"]; ok && fmt.Sprint(v) != "0" {
d.Set("chunk_size", formatInt(v))
}
d.Set("gateway_block_volume_name", object["Name"])
d.Set("local_path", object["LocalPath"])
d.Set("oss_bucket_name", object["OssBucketName"])
d.Set("oss_bucket_ssl", object["OssBucketSsl"])
d.Set("oss_endpoint", object["OssEndpoint"])
d.Set("protocol", object["Protocol"])
d.Set("status", fmt.Sprint(formatInt(object["VolumeState"])))
return nil
}
func resourceAlicloudCloudStorageGatewayGatewayBlockVolumeUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"GatewayId": parts[0],
"IndexId": parts[1],
}
if v, ok := d.GetOkExists("chap_enabled"); ok {
request["ChapEnabled"] = v
}
if d.HasChange("chap_enabled") {
update = true
}
if v, ok := d.GetOk("chap_in_password"); ok {
request["ChapInPassword"] = v
}
if d.HasChange("chap_in_password") {
update = true
}
if v, ok := d.GetOk("chap_in_user"); ok {
request["ChapInUser"] = v
}
if d.HasChange("chap_in_user") {
update = true
}
if d.HasChange("size") {
update = true
if v, ok := d.GetOk("size"); ok {
request["Size"] = v
}
}
if update {
action := "UpdateGatewayBlockVolume"
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
sgwService := SgwService{client}
stateConf := BuildStateConf([]string{}, []string{"task.state.completed"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, sgwService.CloudStorageGatewayTaskStateRefreshFunc(request["GatewayId"].(string), response["TaskId"].(string), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudCloudStorageGatewayGatewayBlockVolumeRead(d, meta)
}
func resourceAlicloudCloudStorageGatewayGatewayBlockVolumeDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteGatewayBlockVolumes"
var response map[string]interface{}
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"GatewayId": parts[0],
"IndexId": parts[1],
}
if v, ok := d.GetOkExists("is_source_deletion"); ok {
request["IsSourceDeletion"] = v
} else {
request["IsSourceDeletion"] = true
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
sgwService := SgwService{client}
stateConf := BuildStateConf([]string{}, []string{"task.state.completed"}, d.Timeout(schema.TimeoutDelete), 5*time.Second, sgwService.CloudStorageGatewayTaskStateRefreshFunc(request["GatewayId"].(string), response["TaskId"].(string), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCloudStorageGatewayGatewayCacheDisk() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCloudStorageGatewayGatewayCacheDiskCreate,
Read: resourceAlicloudCloudStorageGatewayGatewayCacheDiskRead,
Update: resourceAlicloudCloudStorageGatewayGatewayCacheDiskUpdate,
Delete: resourceAlicloudCloudStorageGatewayGatewayCacheDiskDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"cache_disk_category": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"cloud_efficiency", "cloud_ssd"}, false),
},
"cache_disk_size_in_gb": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(20, 32768),
},
"cache_id": {
Type: schema.TypeString,
Computed: true,
},
"gateway_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"local_file_path": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeInt,
Computed: true,
},
},
}
}
func resourceAlicloudCloudStorageGatewayGatewayCacheDiskCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sgwService := SgwService{client}
var response map[string]interface{}
action := "CreateGatewayCacheDisk"
request := make(map[string]interface{})
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("cache_disk_category"); ok {
request["CacheDiskCategory"] = v
}
request["CacheDiskSizeInGB"] = d.Get("cache_disk_size_in_gb")
request["GatewayId"] = d.Get("gateway_id")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloud_storage_gateway_gateway_cache_disk", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
stateConf := BuildStateConf([]string{}, []string{"task.state.completed"}, d.Timeout(schema.TimeoutCreate), 1*time.Second, sgwService.CloudStorageGatewayTaskStateRefreshFunc(fmt.Sprint(request["GatewayId"]), fmt.Sprint(response["TaskId"]), []string{"task.state.failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
task, err := sgwService.DescribeTasks(fmt.Sprint(request["GatewayId"]), fmt.Sprint(response["TaskId"]))
if err != nil {
return nil
}
object, err := sgwService.DescribeCloudStorageGatewayGatewayCacheDisk(fmt.Sprint(request["GatewayId"], ":", task["RelatedResourceId"], ":"))
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cloud_storage_gateway_gateway_cache_disk sgwService.DescribeCloudStorageGatewayGatewayCacheDisk Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.SetId(fmt.Sprint(request["GatewayId"], ":", task["RelatedResourceId"], ":", object["LocalFilePath"]))
return resourceAlicloudCloudStorageGatewayGatewayCacheDiskRead(d, meta)
}
func resourceAlicloudCloudStorageGatewayGatewayCacheDiskRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sgwService := SgwService{client}
object, err := sgwService.DescribeCloudStorageGatewayGatewayCacheDisk(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cloud_storage_gateway_gateway_cache_disk sgwService.DescribeCloudStorageGatewayGatewayCacheDisk Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
d.Set("gateway_id", parts[0])
d.Set("local_file_path", object["LocalFilePath"])
d.Set("cache_disk_category", object["CacheType"])
d.Set("cache_disk_size_in_gb", formatInt(object["SizeInGB"]))
d.Set("cache_id", object["CacheId"])
d.Set("status", formatInt(object["ExpireStatus"]))
return nil
}
func resourceAlicloudCloudStorageGatewayGatewayCacheDiskUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sgwService := SgwService{client}
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
if d.HasChange("cache_disk_size_in_gb") {
request := map[string]interface{}{
"GatewayId": parts[0],
"LocalFilePath": parts[2],
"NewSizeInGB": d.Get("cache_disk_size_in_gb"),
}
action := "ExpandCacheDisk"
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
stateConf := BuildStateConf([]string{}, []string{"task.state.completed"}, d.Timeout(schema.TimeoutCreate), 1*time.Second, sgwService.CloudStorageGatewayTaskStateRefreshFunc(fmt.Sprint(request["GatewayId"]), fmt.Sprint(response["TaskId"]), []string{"task.state.failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudCloudStorageGatewayGatewayCacheDiskRead(d, meta)
}
func resourceAlicloudCloudStorageGatewayGatewayCacheDiskDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sgwService := SgwService{client}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
action := "DeleteGatewayCacheDisk"
var response map[string]interface{}
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"GatewayId": parts[0],
"CacheId": parts[1],
"LocalFilePath": parts[2],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
stateConf := BuildStateConf([]string{}, []string{"task.state.completed"}, d.Timeout(schema.TimeoutCreate), 1*time.Second, sgwService.CloudStorageGatewayTaskStateRefreshFunc(fmt.Sprint(request["GatewayId"]), fmt.Sprint(response["TaskId"]), []string{"task.state.failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCloudStorageGatewayGatewayFileShare() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCloudStorageGatewayGatewayFileShareCreate,
Read: resourceAlicloudCloudStorageGatewayGatewayFileShareRead,
Update: resourceAlicloudCloudStorageGatewayGatewayFileShareUpdate,
Delete: resourceAlicloudCloudStorageGatewayGatewayFileShareDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
Update: schema.DefaultTimeout(5 * time.Minute),
Delete: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"access_based_enumeration": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("protocol"); ok && v.(string) == "SMB" {
if _, ok := d.GetOkExists("windows_acl"); ok {
return false
}
}
return true
},
},
"backend_limit": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(0, 1280),
},
"browsable": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("protocol"); ok && v.(string) == "SMB" {
return false
}
return true
},
},
"cache_mode": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Cache", "Sync"}, false),
},
"direct_io": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
ForceNew: true,
},
"download_limit": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(0, 1280),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("cache_mode"); ok && v.(string) == "Sync" {
return false
}
return true
},
},
"fast_reclaim": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"fe_limit": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(0, 1280),
},
"gateway_file_share_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-z][A-Za-z0-9\\_\\.\\-]{1,254}$`), "Length from `1` to `255` characters can contain lowercase letters, digits, (.), (_) Or (-), at the same time, must start with a lowercase letter."),
},
"gateway_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ignore_delete": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"in_place": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
ForceNew: true,
},
"index_id": {
Type: schema.TypeString,
Computed: true,
},
"lag_period": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(5, 120),
},
"local_path": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"nfs_v4_optimization": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("protocol"); ok && v.(string) == "NFS" {
return false
}
return true
},
},
"oss_bucket_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"oss_bucket_ssl": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
ForceNew: true,
},
"oss_endpoint": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"partial_sync_paths": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"path_prefix": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"polling_interval": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(0, 36000),
},
"protocol": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"NFS", "SMB"}, false),
},
"remote_sync": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"remote_sync_download": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("cache_mode"); ok && v.(string) == "Sync" {
return false
}
return true
},
},
"ro_client_list": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("protocol"); ok && v.(string) == "NFS" {
return false
}
return true
},
},
"ro_user_list": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("protocol"); ok && v.(string) == "SMB" {
return false
}
return true
},
},
"rw_client_list": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("protocol"); ok && v.(string) == "NFS" {
return false
}
return true
},
},
"rw_user_list": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("protocol"); ok && v.(string) == "SMB" {
return false
}
return true
},
},
"squash": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"all_anonymous", "all_squash", "none", "root_squash"}, false),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("protocol"); ok && v.(string) == "NFS" {
return false
}
return true
},
},
"support_archive": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Computed: true,
},
"transfer_acceleration": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"windows_acl": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("protocol"); ok && v.(string) == "SMB" {
return false
}
return true
},
},
"bypass_cache_read": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
},
}
}
func resourceAlicloudCloudStorageGatewayGatewayFileShareCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sgwService := SgwService{client}
var response map[string]interface{}
action := "CreateGatewayFileShare"
request := make(map[string]interface{})
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("access_based_enumeration"); ok {
request["AccessBasedEnumeration"] = v
}
if v, ok := d.GetOk("backend_limit"); ok {
request["BackendLimit"] = v
}
if v, ok := d.GetOkExists("browsable"); ok {
request["Browsable"] = v
}
if v, ok := d.GetOk("cache_mode"); ok {
request["CacheMode"] = v
}
if v, ok := d.GetOkExists("direct_io"); ok {
request["DirectIO"] = v
}
if v, ok := d.GetOk("download_limit"); ok {
request["DownloadLimit"] = v
}
if v, ok := d.GetOkExists("fast_reclaim"); ok {
request["FastReclaim"] = v
}
if v, ok := d.GetOk("fe_limit"); ok {
request["FrontendLimit"] = v
}
if v, ok := d.GetOkExists("bypass_cache_read"); ok {
request["BypassCacheRead"] = v
}
request["Name"] = d.Get("gateway_file_share_name")
request["GatewayId"] = d.Get("gateway_id")
if v, ok := d.GetOkExists("ignore_delete"); ok {
request["IgnoreDelete"] = v
}
if v, ok := d.GetOkExists("in_place"); ok {
request["InPlace"] = v
}
if v, ok := d.GetOk("lag_period"); ok {
request["LagPeriod"] = v
}
request["LocalFilePath"] = d.Get("local_path")
if v, ok := d.GetOkExists("nfs_v4_optimization"); ok {
request["NfsV4Optimization"] = v
}
request["OssBucketName"] = d.Get("oss_bucket_name")
if v, ok := d.GetOkExists("oss_bucket_ssl"); ok {
request["OssBucketSsl"] = v
}
request["OssEndpoint"] = d.Get("oss_endpoint")
if v, ok := d.GetOk("partial_sync_paths"); ok {
request["PartialSyncPaths"] = v
}
if v, ok := d.GetOk("path_prefix"); ok {
request["PathPrefix"] = v
}
if v, ok := d.GetOk("polling_interval"); ok {
request["PollingInterval"] = v
}
request["ShareProtocol"] = d.Get("protocol")
if v, ok := d.GetOkExists("remote_sync"); ok {
request["RemoteSync"] = v
}
if v, ok := d.GetOkExists("remote_sync_download"); ok {
request["RemoteSyncDownload"] = v
}
if v, ok := d.GetOk("ro_client_list"); ok {
request["ReadOnlyClientList"] = v
}
if v, ok := d.GetOk("ro_user_list"); ok {
request["ReadOnlyUserList"] = v
}
if v, ok := d.GetOk("rw_client_list"); ok {
request["ReadWriteClientList"] = v
}
if v, ok := d.GetOk("rw_user_list"); ok {
request["ReadWriteUserList"] = v
}
if v, ok := d.GetOk("squash"); ok {
request["Squash"] = v
}
if v, ok := d.GetOkExists("support_archive"); ok {
request["SupportArchive"] = v
}
if v, ok := d.GetOkExists("transfer_acceleration"); ok {
request["TransferAcceleration"] = v
}
if v, ok := d.GetOkExists("windows_acl"); ok {
request["WindowsAcl"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloud_storage_gateway_gateway_file_share", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
stateConf := BuildStateConf([]string{}, []string{"task.state.completed"}, d.Timeout(schema.TimeoutCreate), 1*time.Second, sgwService.CloudStorageGatewayTaskStateRefreshFunc(fmt.Sprint(request["GatewayId"]), fmt.Sprint(response["TaskId"]), []string{"task.state.failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
object, err := sgwService.DescribeTasks(fmt.Sprint(request["GatewayId"]), fmt.Sprint(response["TaskId"]))
if err != nil {
return nil
}
d.SetId(fmt.Sprint(request["GatewayId"], ":", object["RelatedResourceId"]))
return resourceAlicloudCloudStorageGatewayGatewayFileShareRead(d, meta)
}
func resourceAlicloudCloudStorageGatewayGatewayFileShareRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sgwService := SgwService{client}
object, err := sgwService.DescribeCloudStorageGatewayGatewayFileShare(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cloud_storage_gateway_gateway_file_share sgwService.DescribeCloudStorageGatewayGatewayFileShare Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("gateway_id", parts[0])
d.Set("index_id", parts[1])
d.Set("access_based_enumeration", object["AccessBasedEnumeration"])
d.Set("backend_limit", formatInt(object["BeLimit"]))
d.Set("browsable", object["Browsable"])
d.Set("cache_mode", object["CacheMode"])
d.Set("direct_io", object["DirectIO"])
d.Set("download_limit", formatInt(object["DownloadLimit"]))
d.Set("fast_reclaim", object["FastReclaim"])
d.Set("fe_limit", formatInt(object["FeLimit"]))
d.Set("gateway_file_share_name", object["Name"])
d.Set("ignore_delete", object["IgnoreDelete"])
d.Set("in_place", object["InPlace"])
d.Set("lag_period", formatInt(object["LagPeriod"]))
d.Set("local_path", object["LocalPath"])
d.Set("nfs_v4_optimization", object["NfsV4Optimization"])
d.Set("oss_bucket_name", object["OssBucketName"])
d.Set("oss_bucket_ssl", object["OssBucketSsl"])
d.Set("oss_endpoint", object["OssEndpoint"])
d.Set("partial_sync_paths", object["PartialSyncPaths"])
d.Set("path_prefix", object["PathPrefix"])
if v, ok := object["PollingInterval"]; ok && fmt.Sprint(v) != "0" {
d.Set("polling_interval", formatInt(v))
}
d.Set("protocol", object["Protocol"])
d.Set("bypass_cache_read", object["BypassCacheRead"])
d.Set("remote_sync", object["RemoteSync"])
d.Set("remote_sync_download", object["RemoteSyncDownload"])
d.Set("ro_client_list", object["RoClientList"])
d.Set("ro_user_list", object["RoUserList"])
d.Set("rw_client_list", object["RwClientList"])
d.Set("rw_user_list", object["RwUserList"])
d.Set("squash", object["Squash"])
d.Set("support_archive", object["SupportArchive"])
d.Set("transfer_acceleration", object["TransferAcceleration"])
d.Set("windows_acl", object["WindowsAcl"])
return nil
}
func resourceAlicloudCloudStorageGatewayGatewayFileShareUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sgwService := SgwService{client}
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"GatewayId": parts[0],
"IndexId": parts[1],
}
request["Name"] = d.Get("gateway_file_share_name")
if d.HasChange("access_based_enumeration") || d.IsNewResource() {
update = true
}
if v, ok := d.GetOkExists("access_based_enumeration"); ok {
request["AccessBasedEnumeration"] = v
}
if v, ok := d.GetOkExists("backend_limit"); ok {
request["BackendLimit"] = v
}
if d.HasChange("backend_limit") {
update = true
}
if d.HasChange("browsable") || d.IsNewResource() {
update = true
}
if v, ok := d.GetOkExists("browsable"); ok {
request["Browsable"] = v
}
if d.HasChange("bypass_cache_read") {
update = true
}
if v, ok := d.GetOkExists("bypass_cache_read"); ok {
request["BypassCacheRead"] = v
}
if v, ok := d.GetOk("cache_mode"); ok {
request["CacheMode"] = v
}
if d.HasChange("download_limit") {
update = true
}
if v, ok := d.GetOkExists("download_limit"); ok {
request["DownloadLimit"] = v
}
if d.HasChange("fast_reclaim") || d.IsNewResource() {
update = true
}
if v, ok := d.GetOkExists("fast_reclaim"); ok {
request["FastReclaim"] = v
}
if d.HasChange("fe_limit") {
update = true
}
if v, ok := d.GetOkExists("fe_limit"); ok {
request["FrontendLimit"] = v
}
if d.HasChange("ignore_delete") || d.IsNewResource() {
update = true
}
if v, ok := d.GetOkExists("ignore_delete"); ok {
request["IgnoreDelete"] = v
}
if v, ok := d.GetOkExists("in_place"); ok {
request["InPlace"] = v
}
if d.HasChange("lag_period") {
update = true
}
if v, ok := d.GetOk("lag_period"); ok {
request["LagPeriod"] = v
}
if d.HasChange("nfs_v4_optimization") || d.IsNewResource() {
update = true
}
if v, ok := d.GetOkExists("nfs_v4_optimization"); ok {
request["NfsV4Optimization"] = v
}
if d.HasChange("polling_interval") {
update = true
}
if v, ok := d.GetOkExists("polling_interval"); ok {
request["PollingInterval"] = v
}
if d.HasChange("remote_sync") || d.IsNewResource() {
update = true
}
if v, ok := d.GetOkExists("remote_sync"); ok {
request["RemoteSync"] = v
}
if d.HasChange("remote_sync_download") || d.IsNewResource() {
update = true
}
if v, ok := d.GetOkExists("remote_sync_download"); ok {
request["RemoteSyncDownload"] = v
}
if d.HasChange("ro_client_list") {
update = true
}
if v, ok := d.GetOk("ro_client_list"); ok {
request["ReadOnlyClientList"] = v
}
if d.HasChange("ro_user_list") {
update = true
}
if v, ok := d.GetOk("ro_user_list"); ok {
request["ReadOnlyUserList"] = v
}
if d.HasChange("rw_client_list") {
update = true
}
if v, ok := d.GetOk("rw_client_list"); ok {
request["ReadWriteClientList"] = v
}
if d.HasChange("rw_user_list") {
update = true
}
if v, ok := d.GetOk("rw_user_list"); ok {
request["ReadWriteUserList"] = v
}
if d.HasChange("squash") {
update = true
}
if v, ok := d.GetOk("squash"); ok {
request["Squash"] = v
}
if d.HasChange("transfer_acceleration") || d.IsNewResource() {
update = true
}
if v, ok := d.GetOkExists("transfer_acceleration"); ok {
request["TransferAcceleration"] = v
}
if d.HasChange("windows_acl") || d.IsNewResource() {
update = true
}
if v, ok := d.GetOkExists("windows_acl"); ok {
request["WindowsAcl"] = v
}
if update {
action := "UpdateGatewayFileShare"
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
stateConf := BuildStateConf([]string{}, []string{"task.state.completed"}, d.Timeout(schema.TimeoutUpdate), 1*time.Second, sgwService.CloudStorageGatewayTaskStateRefreshFunc(fmt.Sprint(request["GatewayId"]), fmt.Sprint(response["TaskId"]), []string{"task.state.failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudCloudStorageGatewayGatewayFileShareRead(d, meta)
}
func resourceAlicloudCloudStorageGatewayGatewayFileShareDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sgwService := SgwService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteGatewayFileShares"
var response map[string]interface{}
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"GatewayId": parts[0],
"IndexId": parts[1],
"Force": true,
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"GatewayDeletionError"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
stateConf := BuildStateConf([]string{}, []string{"task.state.completed"}, d.Timeout(schema.TimeoutDelete), 1*time.Second, sgwService.CloudStorageGatewayTaskStateRefreshFunc(fmt.Sprint(request["GatewayId"]), fmt.Sprint(response["TaskId"]), []string{"task.state.failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCloudStorageGatewayGatewayLogging() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCloudStorageGatewayGatewayLoggingCreate,
Read: resourceAlicloudCloudStorageGatewayGatewayLoggingRead,
Update: resourceAlicloudCloudStorageGatewayGatewayLoggingUpdate,
Delete: resourceAlicloudCloudStorageGatewayGatewayLoggingDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"gateway_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"sls_logstore": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"sls_project": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Enabled", "Disabled"}, false),
},
},
}
}
func resourceAlicloudCloudStorageGatewayGatewayLoggingCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateGatewayLogging"
request := make(map[string]interface{})
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
request["GatewayId"] = d.Get("gateway_id")
request["SlsLogstore"] = d.Get("sls_logstore")
request["SlsProject"] = d.Get("sls_project")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloud_storage_gateway_gateway_logging", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetId(fmt.Sprint(request["GatewayId"]))
return resourceAlicloudCloudStorageGatewayGatewayLoggingUpdate(d, meta)
}
func resourceAlicloudCloudStorageGatewayGatewayLoggingRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sgwService := SgwService{client}
object, err := sgwService.DescribeCloudStorageGatewayGatewayLogging(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cloud_storage_gateway_gateway_logging sgwService.DescribeCloudStorageGatewayGatewayLogging Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("gateway_id", d.Id())
d.Set("sls_logstore", object["SlsLogstore"])
d.Set("sls_project", object["SlsProject"])
d.Set("status", object["GatewayLoggingStatus"])
return nil
}
func resourceAlicloudCloudStorageGatewayGatewayLoggingUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sgwService := SgwService{client}
var response map[string]interface{}
d.Partial(true)
if d.HasChange("status") {
object, err := sgwService.DescribeCloudStorageGatewayGatewayLogging(d.Id())
if err != nil {
return WrapError(err)
}
target := d.Get("status").(string)
if object["GatewayLoggingStatus"].(string) != target {
if target == "Disabled" {
request := map[string]interface{}{
"GatewayId": d.Id(),
}
action := "DisableGatewayLogging"
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
}
if target == "Enabled" {
request := map[string]interface{}{
"GatewayId": d.Id(),
}
action := "EnableGatewayLogging"
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
}
d.SetPartial("status")
}
}
d.Partial(false)
return resourceAlicloudCloudStorageGatewayGatewayLoggingRead(d, meta)
}
func resourceAlicloudCloudStorageGatewayGatewayLoggingDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteGatewayLogging"
var response map[string]interface{}
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"GatewayId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCloudStorageGatewayGatewaySmbUser() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCloudStorageGatewayGatewaySmbUserCreate,
Read: resourceAlicloudCloudStorageGatewayGatewaySmbUserRead,
Delete: resourceAlicloudCloudStorageGatewayGatewaySmbUserDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
Delete: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"gateway_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"password": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Sensitive: true,
},
"username": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudCloudStorageGatewayGatewaySmbUserCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sgwService := SgwService{client}
var response map[string]interface{}
action := "CreateGatewaySMBUser"
request := make(map[string]interface{})
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
request["GatewayId"] = d.Get("gateway_id")
request["Password"] = d.Get("password")
request["Username"] = d.Get("username")
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloud_storage_gateway_gateway_smb_user", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetId(fmt.Sprint(request["GatewayId"], ":", request["Username"]))
stateConf := BuildStateConf([]string{}, []string{"task.state.completed"}, d.Timeout(schema.TimeoutCreate), 1*time.Second, sgwService.CloudStorageGatewayTaskStateRefreshFunc(fmt.Sprint(request["GatewayId"]), fmt.Sprint(response["TaskId"]), []string{"task.state.Failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudCloudStorageGatewayGatewaySmbUserRead(d, meta)
}
func resourceAlicloudCloudStorageGatewayGatewaySmbUserRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sgwService := SgwService{client}
_, err := sgwService.DescribeCloudStorageGatewayGatewaySmbUser(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cloud_storage_gateway_gateway_smb_user sgwService.DescribeCloudStorageGatewayGatewaySmbUser Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("gateway_id", parts[0])
d.Set("username", parts[1])
return nil
}
func resourceAlicloudCloudStorageGatewayGatewaySmbUserDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sgwService := SgwService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteGatewaySMBUser"
var response map[string]interface{}
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"GatewayId": parts[0],
"Username": parts[1],
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"InternalError"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
stateConf := BuildStateConf([]string{}, []string{"task.state.completed"}, d.Timeout(schema.TimeoutCreate), 1*time.Second, sgwService.CloudStorageGatewayTaskStateRefreshFunc(fmt.Sprint(request["GatewayId"]), fmt.Sprint(response["TaskId"]), []string{"task.state.Failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCloudStorageGatewayStorageBundle() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCloudStorageGatewayStorageBundleCreate,
Read: resourceAlicloudCloudStorageGatewayStorageBundleRead,
Update: resourceAlicloudCloudStorageGatewayStorageBundleUpdate,
Delete: resourceAlicloudCloudStorageGatewayStorageBundleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
},
"storage_bundle_name": {
Type: schema.TypeString,
Required: true,
},
},
}
}
func resourceAlicloudCloudStorageGatewayStorageBundleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateStorageBundle"
request := make(map[string]interface{})
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["BackendBucketRegionId"] = client.RegionId
request["Name"] = d.Get("storage_bundle_name")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloud_storage_gateway_storage_bundle", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["StorageBundleId"]))
return resourceAlicloudCloudStorageGatewayStorageBundleRead(d, meta)
}
func resourceAlicloudCloudStorageGatewayStorageBundleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sgwService := SgwService{client}
object, err := sgwService.DescribeCloudStorageGatewayStorageBundle(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cloud_storage_gateway_storage_bundle sgwService.DescribeCloudStorageGatewayStorageBundle Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", object["Description"])
d.Set("storage_bundle_name", object["Name"])
return nil
}
func resourceAlicloudCloudStorageGatewayStorageBundleUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"StorageBundleId": d.Id(),
}
if d.HasChange("storage_bundle_name") {
update = true
}
request["Name"] = d.Get("storage_bundle_name")
if d.HasChange("description") {
update = true
request["Description"] = d.Get("description")
}
if update {
action := "ModifyStorageBundle"
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudCloudStorageGatewayStorageBundleRead(d, meta)
}
func resourceAlicloudCloudStorageGatewayStorageBundleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteStorageBundle"
var response map[string]interface{}
conn, err := client.NewHcsSgwClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"StorageBundleId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"StorageBundleNotExist"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCloudauthFaceConfig() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCloudauthFaceConfigCreate,
Read: resourceAlicloudCloudauthFaceConfigRead,
Update: resourceAlicloudCloudauthFaceConfigUpdate,
Delete: resourceAlicloudCloudauthFaceConfigDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"biz_name": {
Type: schema.TypeString,
Required: true,
},
"biz_type": {
Type: schema.TypeString,
Required: true,
},
"gmt_modified": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudCloudauthFaceConfigCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateFaceConfig"
request := make(map[string]interface{})
conn, err := client.NewCloudauthClient()
if err != nil {
return WrapError(err)
}
request["BizName"] = d.Get("biz_name")
request["BizType"] = d.Get("biz_type")
request["SourceIp"] = buildClientToken(action)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-07"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloudauth_face_config", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["BizType"]))
return resourceAlicloudCloudauthFaceConfigRead(d, meta)
}
func resourceAlicloudCloudauthFaceConfigRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudauthService := CloudauthService{client}
object, err := cloudauthService.DescribeCloudauthFaceConfig(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cloudauth_face_config cloudauthService.DescribeCloudauthFaceConfig Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("biz_name", object["BizName"])
d.Set("biz_type", object["BizType"])
d.Set("gmt_modified", object["GmtUpdated"])
return nil
}
func resourceAlicloudCloudauthFaceConfigUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"BizType": d.Id(),
}
if d.HasChange("biz_name") {
update = true
}
request["BizName"] = d.Get("biz_name")
if update {
action := "UpdateFaceConfig"
request["SourceIp"] = buildClientToken(action)
conn, err := client.NewCloudauthClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-07"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudCloudauthFaceConfigRead(d, meta)
}
func resourceAlicloudCloudauthFaceConfigDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudCloudauthFaceConfig. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
package alicloud
import (
"encoding/json"
"fmt"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"strconv"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cms"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCmsAlarm() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCmsAlarmCreate,
Read: resourceAlicloudCmsAlarmRead,
Update: resourceAlicloudCmsAlarmUpdate,
Delete: resourceAlicloudCmsAlarmDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"project": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"metric": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"dimensions": {
Type: schema.TypeMap,
Required: true,
ForceNew: true,
Elem: schema.TypeString,
},
"period": {
Type: schema.TypeInt,
Optional: true,
Default: 300,
},
"escalations_critical": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"statistics": {
Type: schema.TypeString,
Optional: true,
Default: Average,
ValidateFunc: validation.StringInSlice([]string{Average, Minimum, Maximum, ErrorCodeMaximum, Value, Sum, Count}, false),
},
"comparison_operator": {
Type: schema.TypeString,
Optional: true,
Default: Equal,
ValidateFunc: validation.StringInSlice([]string{
MoreThan, MoreThanOrEqual, LessThan, LessThanOrEqual, NotEqual,
}, false),
},
"threshold": {
Type: schema.TypeString,
Optional: true,
},
"times": {
Type: schema.TypeInt,
Optional: true,
Default: 3,
},
},
},
DiffSuppressFunc: cmsClientCriticalSuppressFunc,
MaxItems: 1,
},
"escalations_warn": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"statistics": {
Type: schema.TypeString,
Optional: true,
Default: Average,
ValidateFunc: validation.StringInSlice([]string{Average, Minimum, Maximum, ErrorCodeMaximum, Value, Sum, Count}, false),
},
"comparison_operator": {
Type: schema.TypeString,
Optional: true,
Default: Equal,
ValidateFunc: validation.StringInSlice([]string{
MoreThan, MoreThanOrEqual, LessThan, LessThanOrEqual, NotEqual,
}, false),
},
"threshold": {
Type: schema.TypeString,
Optional: true,
},
"times": {
Type: schema.TypeInt,
Optional: true,
Default: 3,
},
},
},
DiffSuppressFunc: cmsClientWarnSuppressFunc,
MaxItems: 1,
},
"escalations_info": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"statistics": {
Type: schema.TypeString,
Optional: true,
Default: Average,
ValidateFunc: validation.StringInSlice([]string{Average, Minimum, Maximum, ErrorCodeMaximum, Value, Sum, Count}, false),
},
"comparison_operator": {
Type: schema.TypeString,
Optional: true,
Default: Equal,
ValidateFunc: validation.StringInSlice([]string{
MoreThan, MoreThanOrEqual, LessThan, LessThanOrEqual, NotEqual,
}, false),
},
"threshold": {
Type: schema.TypeString,
Optional: true,
},
"times": {
Type: schema.TypeInt,
Optional: true,
Default: 3,
},
},
},
DiffSuppressFunc: cmsClientInfoSuppressFunc,
MaxItems: 1,
},
"statistics": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{Average, Minimum, Maximum, ErrorCodeMaximum, Value, Sum, Count}, false),
Deprecated: "Field 'statistics' has been deprecated from provider version 1.94.0. New field 'escalations_critical.statistics' instead.",
},
"operator": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{
MoreThan, MoreThanOrEqual, LessThan, LessThanOrEqual, Equal, NotEqual,
}, false),
Deprecated: "Field 'operator' has been deprecated from provider version 1.94.0. New field 'escalations_critical.comparison_operator' instead.",
},
"threshold": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Field 'threshold' has been deprecated from provider version 1.94.0. New field 'escalations_critical.threshold' instead.",
},
"triggered_count": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Deprecated: "Field 'triggered_count' has been deprecated from provider version 1.94.0. New field 'escalations_critical.times' instead.",
},
"contact_groups": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"start_time": {
Type: schema.TypeInt,
Optional: true,
//Default: 0,
//ValidateFunc: validation.IntBetween(0, 24),
Deprecated: "Field 'start_time' has been deprecated from provider version 1.50.0. New field 'effective_interval' instead.",
},
"end_time": {
Type: schema.TypeInt,
Optional: true,
//Default: 24,
//ValidateFunc: validation.IntBetween(0, 24),
Deprecated: "Field 'end_time' has been deprecated from provider version 1.50.0. New field 'effective_interval' instead.",
},
"effective_interval": {
Type: schema.TypeString,
Optional: true,
Default: "00:00-23:59",
},
"silence_time": {
Type: schema.TypeInt,
Optional: true,
Default: 86400,
ValidateFunc: validation.IntBetween(300, 86400),
},
"notify_type": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{0, 1}),
Removed: "Field 'notify_type' has been removed from provider version 1.50.0.",
},
"enabled": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"webhook": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudCmsAlarmCreate(d *schema.ResourceData, meta interface{}) error {
d.SetId(resource.UniqueId())
return resourceAlicloudCmsAlarmUpdate(d, meta)
}
func resourceAlicloudCmsAlarmRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cmsService := CmsService{client}
alarm, err := cmsService.DescribeAlarm(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return err
}
d.Set("name", alarm.RuleName)
d.Set("project", alarm.Namespace)
d.Set("metric", alarm.MetricName)
if period, err := strconv.Atoi(alarm.Period); err != nil {
return WrapError(err)
} else {
d.Set("period", period)
}
d.Set("statistics", alarm.Escalations.Critical.Statistics)
oper := convertOperator(alarm.Escalations.Critical.ComparisonOperator)
if oper == MoreThan && d.Get("operator").(string) == Equal {
oper = Equal
}
d.Set("operator", oper)
d.Set("threshold", alarm.Escalations.Critical.Threshold)
d.Set("triggered_count", alarm.Escalations.Critical.Times)
escalationsCritical := make([]map[string]interface{}, 1)
mapping := map[string]interface{}{
"statistics": alarm.Escalations.Critical.Statistics,
"comparison_operator": convertOperator(alarm.Escalations.Critical.ComparisonOperator),
"threshold": alarm.Escalations.Critical.Threshold,
"times": alarm.Escalations.Critical.Times,
}
escalationsCritical[0] = mapping
d.Set("escalations_critical", escalationsCritical)
escalationsWarn := make([]map[string]interface{}, 1)
if alarm.Escalations.Warn.Times != "" {
if count, err := strconv.Atoi(alarm.Escalations.Warn.Times); err != nil {
return WrapError(err)
} else {
mappingWarn := map[string]interface{}{
"statistics": alarm.Escalations.Warn.Statistics,
"comparison_operator": convertOperator(alarm.Escalations.Warn.ComparisonOperator),
"threshold": alarm.Escalations.Warn.Threshold,
"times": count,
}
escalationsWarn[0] = mappingWarn
d.Set("escalations_warn", escalationsWarn)
}
}
escalationsInfo := make([]map[string]interface{}, 1)
if alarm.Escalations.Info.Times != "" {
if count, err := strconv.Atoi(alarm.Escalations.Info.Times); err != nil {
return WrapError(err)
} else {
mappingInfo := map[string]interface{}{
"statistics": alarm.Escalations.Info.Statistics,
"comparison_operator": convertOperator(alarm.Escalations.Info.ComparisonOperator),
"threshold": alarm.Escalations.Info.Threshold,
"times": count,
}
escalationsInfo[0] = mappingInfo
d.Set("escalations_info", escalationsInfo)
}
}
d.Set("effective_interval", alarm.EffectiveInterval)
//d.Set("start_time", parts[0])
//d.Set("end_time", parts[1])
d.Set("silence_time", alarm.SilenceTime)
d.Set("status", alarm.AlertState)
d.Set("enabled", alarm.EnableState)
d.Set("webhook", alarm.Webhook)
d.Set("contact_groups", strings.Split(alarm.ContactGroups, ","))
var dims []string
if alarm.Dimensions != "" {
if err := json.Unmarshal([]byte(alarm.Dimensions), &dims); err != nil {
return fmt.Errorf("Unmarshaling Dimensions got an error: %#v.", err)
}
}
d.Set("dimensions", dims)
return nil
}
func resourceAlicloudCmsAlarmUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cmsService := CmsService{client}
d.Partial(true)
request := cms.CreatePutResourceMetricRuleRequest()
request.RuleId = d.Id()
request.RuleName = d.Get("name").(string)
request.Namespace = d.Get("project").(string)
request.MetricName = d.Get("metric").(string)
request.Period = strconv.Itoa(d.Get("period").(int))
request.ContactGroups = strings.Join(expandStringList(d.Get("contact_groups").([]interface{})), ",")
// 兼容弃用参数
request.EscalationsCriticalStatistics = d.Get("statistics").(string)
request.EscalationsCriticalComparisonOperator = convertOperator(d.Get("operator").(string))
if v, ok := d.GetOk("threshold"); ok && v.(string) != "" {
request.EscalationsCriticalThreshold = v.(string)
}
request.EscalationsCriticalThreshold = d.Get("threshold").(string)
request.EscalationsCriticalTimes = requests.NewInteger(d.Get("triggered_count").(int))
// Critical
if v, ok := d.GetOk("escalations_critical"); ok && len(v.([]interface{})) != 0 {
for _, val := range v.([]interface{}) {
val := val.(map[string]interface{})
request.EscalationsCriticalStatistics = val["statistics"].(string)
request.EscalationsCriticalComparisonOperator = convertOperator(val["comparison_operator"].(string))
request.EscalationsCriticalThreshold = val["threshold"].(string)
request.EscalationsCriticalTimes = requests.NewInteger(val["times"].(int))
}
}
// Warn
if v, ok := d.GetOk("escalations_warn"); ok && len(v.([]interface{})) != 0 {
for _, val := range v.([]interface{}) {
val := val.(map[string]interface{})
request.EscalationsWarnStatistics = val["statistics"].(string)
request.EscalationsWarnComparisonOperator = convertOperator(val["comparison_operator"].(string))
request.EscalationsWarnThreshold = val["threshold"].(string)
request.EscalationsWarnTimes = requests.NewInteger(val["times"].(int))
}
}
// Info
if v, ok := d.GetOk("escalations_info"); ok && len(v.([]interface{})) != 0 {
for _, val := range v.([]interface{}) {
val := val.(map[string]interface{})
request.EscalationsInfoStatistics = val["statistics"].(string)
request.EscalationsInfoComparisonOperator = convertOperator(val["comparison_operator"].(string))
request.EscalationsInfoThreshold = val["threshold"].(string)
request.EscalationsInfoTimes = requests.NewInteger(val["times"].(int))
}
}
if v, ok := d.GetOk("effective_interval"); ok && v.(string) != "" {
request.EffectiveInterval = v.(string)
} else {
start, startOk := d.GetOk("start_time")
end, endOk := d.GetOk("end_time")
if startOk && endOk && end.(int) > 0 {
// The EffectiveInterval valid value between 00:00 and 23:59
request.EffectiveInterval = fmt.Sprintf("%d:00-%d:59", start.(int), end.(int)-1)
}
}
request.SilenceTime = requests.NewInteger(d.Get("silence_time").(int))
if webhook, ok := d.GetOk("webhook"); ok && webhook.(string) != "" {
request.Webhook = webhook.(string)
}
var dimList []map[string]string
if dimensions, ok := d.GetOk("dimensions"); ok {
for k, v := range dimensions.(map[string]interface{}) {
values := strings.Split(v.(string), COMMA_SEPARATED)
if len(values) > 0 {
for _, vv := range values {
dimList = append(dimList, map[string]string{k: Trim(vv)})
}
} else {
dimList = append(dimList, map[string]string{k: Trim(v.(string))})
}
}
}
if len(dimList) > 0 {
if bytes, err := json.Marshal(dimList); err != nil {
return fmt.Errorf("Marshaling dimensions to json string got an error: %#v.", err)
} else {
request.Resources = string(bytes[:])
}
}
_, err := client.WithCmsClient(func(cmsClient *cms.Client) (interface{}, error) {
return cmsClient.PutResourceMetricRule(request)
})
if err != nil {
return fmt.Errorf("Putting alarm got an error: %#v", err)
}
d.SetPartial("name")
d.SetPartial("period")
d.SetPartial("statistics")
d.SetPartial("operator")
d.SetPartial("threshold")
d.SetPartial("triggered_count")
d.SetPartial("contact_groups")
d.SetPartial("effective_interval")
d.SetPartial("start_time")
d.SetPartial("end_time")
d.SetPartial("silence_time")
d.SetPartial("notify_type")
d.SetPartial("webhook")
if d.Get("enabled").(bool) {
request := cms.CreateEnableMetricRulesRequest()
request.RuleId = &[]string{d.Id()}
wait := incrementalWait(1*time.Second, 2*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
_, err := client.WithCmsClient(func(cmsClient *cms.Client) (interface{}, error) {
return cmsClient.EnableMetricRules(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(fmt.Errorf("Enabling alarm got an error: %#v", err))
}
return nil
})
if err != nil {
return fmt.Errorf("Enabling alarm got an error: %#v", err)
}
} else {
request := cms.CreateDisableMetricRulesRequest()
request.RuleId = &[]string{d.Id()}
wait := incrementalWait(1*time.Second, 2*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
_, err := client.WithCmsClient(func(cmsClient *cms.Client) (interface{}, error) {
return cmsClient.DisableMetricRules(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(fmt.Errorf("Disableing alarm got an error: %#v", err))
}
return nil
})
if err != nil {
return fmt.Errorf("Disableing alarm got an error: %#v", err)
}
}
if err := cmsService.WaitForCmsAlarm(d.Id(), d.Get("enabled").(bool), 102); err != nil {
return err
}
d.Partial(false)
return resourceAlicloudCmsAlarmRead(d, meta)
}
func resourceAlicloudCmsAlarmDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cmsService := CmsService{client}
request := cms.CreateDeleteMetricRulesRequest()
request.Id = &[]string{d.Id()}
wait := incrementalWait(1*time.Second, 2*time.Second)
return resource.Retry(10*time.Minute, func() *resource.RetryError {
_, err := client.WithCmsClient(func(cmsClient *cms.Client) (interface{}, error) {
return cmsClient.DeleteMetricRules(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(fmt.Errorf("Deleting alarm rule got an error: %#v", err))
}
_, err = cmsService.DescribeAlarm(d.Id())
if err != nil {
if NotFoundError(err) {
return nil
}
return resource.NonRetryableError(fmt.Errorf("Describe alarm rule got an error: %#v", err))
}
return resource.RetryableError(fmt.Errorf("Deleting alarm rule got an error: %#v", err))
})
}
func convertOperator(operator string) string {
switch operator {
case MoreThan:
return "GreaterThanThreshold"
case MoreThanOrEqual:
return "GreaterThanOrEqualToThreshold"
case LessThan:
return "LessThanThreshold"
case LessThanOrEqual:
return "LessThanOrEqualToThreshold"
case NotEqual:
return "NotEqualToThreshold"
case Equal:
return "GreaterThanThreshold"
case "GreaterThanThreshold":
return MoreThan
case "GreaterThanOrEqualToThreshold":
return MoreThanOrEqual
case "LessThanThreshold":
return LessThan
case "LessThanOrEqualToThreshold":
return LessThanOrEqual
case "NotEqualToThreshold":
return NotEqual
default:
return ""
}
}
package alicloud
import (
"fmt"
"log"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cms"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCmsAlarmContact() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCmsAlarmContactCreate,
Read: resourceAlicloudCmsAlarmContactRead,
Update: resourceAlicloudCmsAlarmContactUpdate,
Delete: resourceAlicloudCmsAlarmContactDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"alarm_contact_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"channels_aliim": {
Type: schema.TypeString,
Optional: true,
},
"channels_ding_web_hook": {
Type: schema.TypeString,
Optional: true,
},
"channels_mail": {
Type: schema.TypeString,
Optional: true,
},
"channels_sms": {
Type: schema.TypeString,
Optional: true,
},
"describe": {
Type: schema.TypeString,
Required: true,
},
"lang": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"en", "zh-cn"}, false),
},
},
}
}
func resourceAlicloudCmsAlarmContactCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cms.CreatePutContactRequest()
request.ContactName = d.Get("alarm_contact_name").(string)
if v, ok := d.GetOk("channels_aliim"); ok {
request.ChannelsAliIM = v.(string)
}
if v, ok := d.GetOk("channels_ding_web_hook"); ok {
request.ChannelsDingWebHook = v.(string)
}
if v, ok := d.GetOk("channels_mail"); ok {
request.ChannelsMail = v.(string)
}
if v, ok := d.GetOk("channels_sms"); ok {
request.ChannelsSMS = v.(string)
}
request.Describe = d.Get("describe").(string)
if v, ok := d.GetOk("lang"); ok {
request.Lang = v.(string)
}
raw, err := client.WithCmsClient(func(cmsClient *cms.Client) (interface{}, error) {
return cmsClient.PutContact(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cms_alarm_contact", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ := raw.(*cms.PutContactResponse)
if response.Code != "200" {
return WrapError(Error("PutContact failed for " + response.Message))
}
d.SetId(fmt.Sprintf("%v", request.ContactName))
return resourceAlicloudCmsAlarmContactRead(d, meta)
}
func resourceAlicloudCmsAlarmContactRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cmsService := CmsService{client}
object, err := cmsService.DescribeCmsAlarmContact(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cloud_monitor_service_alarm_contact cmsService.DescribeCmsAlarmContact Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("alarm_contact_name", d.Id())
d.Set("channels_aliim", object.Channels.AliIM)
d.Set("channels_ding_web_hook", object.Channels.DingWebHook)
d.Set("channels_mail", object.Channels.Mail)
d.Set("channels_sms", object.Channels.SMS)
d.Set("describe", object.Desc)
d.Set("lang", object.Lang)
return nil
}
func resourceAlicloudCmsAlarmContactUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
update := false
request := cms.CreatePutContactRequest()
request.ContactName = d.Id()
if d.HasChange("channels_aliim") {
update = true
}
request.ChannelsAliIM = d.Get("channels_aliim").(string)
if d.HasChange("channels_ding_web_hook") {
update = true
}
request.ChannelsDingWebHook = d.Get("channels_ding_web_hook").(string)
if d.HasChange("channels_mail") {
update = true
}
request.ChannelsMail = d.Get("channels_mail").(string)
if d.HasChange("channels_sms") {
update = true
}
request.ChannelsSMS = d.Get("channels_sms").(string)
if d.HasChange("describe") {
update = true
}
request.Describe = d.Get("describe").(string)
if d.HasChange("lang") {
update = true
request.Lang = d.Get("lang").(string)
}
if update {
raw, err := client.WithCmsClient(func(cmsClient *cms.Client) (interface{}, error) {
return cmsClient.PutContact(request)
})
addDebug(request.GetActionName(), raw)
response, _ := raw.(*cms.PutContactResponse)
if response.Code != "200" {
return WrapError(Error("PutContact failed for " + response.Message))
}
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudCmsAlarmContactRead(d, meta)
}
func resourceAlicloudCmsAlarmContactDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cms.CreateDeleteContactRequest()
request.ContactName = d.Id()
raw, err := client.WithCmsClient(func(cmsClient *cms.Client) (interface{}, error) {
return cmsClient.DeleteContact(request)
})
addDebug(request.GetActionName(), raw)
response, _ := raw.(*cms.DeleteContactResponse)
if response.Code != "200" {
return WrapError(Error("DeleteContact failed for " + response.Message))
}
if err != nil {
if IsExpectedErrors(err, []string{"400", "403", "404", "ContactNotExists"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cms"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCmsAlarmContactGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCmsAlarmContactGroupCreate,
Read: resourceAlicloudCmsAlarmContactGroupRead,
Update: resourceAlicloudCmsAlarmContactGroupUpdate,
Delete: resourceAlicloudCmsAlarmContactGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"alarm_contact_group_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"contacts": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"describe": {
Type: schema.TypeString,
Optional: true,
},
"enable_subscribed": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
},
}
}
func resourceAlicloudCmsAlarmContactGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cms.CreatePutContactGroupRequest()
request.ContactGroupName = d.Get("alarm_contact_group_name").(string)
if v, ok := d.GetOk("contacts"); ok {
contactNames := expandStringList(v.(*schema.Set).List())
request.ContactNames = &contactNames
}
if v, ok := d.GetOk("describe"); ok {
request.Describe = v.(string)
}
if v, ok := d.GetOkExists("enable_subscribed"); ok {
request.EnableSubscribed = requests.NewBoolean(v.(bool))
}
raw, err := client.WithCmsClient(func(cmsClient *cms.Client) (interface{}, error) {
return cmsClient.PutContactGroup(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cms_alarm_contact_group", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ := raw.(*cms.PutContactGroupResponse)
if response.Code != "200" {
return WrapError(Error("PutContactGroup failed for " + response.Message))
}
d.SetId(fmt.Sprintf("%v", request.ContactGroupName))
return resourceAlicloudCmsAlarmContactGroupRead(d, meta)
}
func resourceAlicloudCmsAlarmContactGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cmsService := CmsService{client}
object, err := cmsService.DescribeCmsAlarmContactGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cloud_monitor_service_alarm_contact_group cmsService.DescribeCmsAlarmContactGroup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("alarm_contact_group_name", d.Id())
d.Set("contacts", object.Contacts.Contact)
d.Set("describe", object.Describe)
d.Set("enable_subscribed", object.EnableSubscribed)
return nil
}
func resourceAlicloudCmsAlarmContactGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
update := false
request := cms.CreatePutContactGroupRequest()
request.ContactGroupName = d.Id()
if d.HasChange("contacts") {
update = true
contactNames := expandStringList(d.Get("contacts").(*schema.Set).List())
request.ContactNames = &contactNames
}
if d.HasChange("describe") {
update = true
request.Describe = d.Get("describe").(string)
}
if d.HasChange("enable_subscribed") {
update = true
request.EnableSubscribed = requests.NewBoolean(d.Get("enable_subscribed").(bool))
}
if update {
raw, err := client.WithCmsClient(func(cmsClient *cms.Client) (interface{}, error) {
return cmsClient.PutContactGroup(request)
})
addDebug(request.GetActionName(), raw)
response, _ := raw.(*cms.PutContactGroupResponse)
if response.Code != "200" {
return WrapError(Error("PutContactGroup failed for " + response.Message))
}
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudCmsAlarmContactGroupRead(d, meta)
}
func resourceAlicloudCmsAlarmContactGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cms.CreateDeleteContactGroupRequest()
request.ContactGroupName = d.Id()
raw, err := client.WithCmsClient(func(cmsClient *cms.Client) (interface{}, error) {
return cmsClient.DeleteContactGroup(request)
})
addDebug(request.GetActionName(), raw)
response, _ := raw.(*cms.DeleteContactGroupResponse)
if response.Code != "200" {
return WrapError(Error("DeleteContactGroup failed for " + response.Message))
}
if err != nil {
if IsExpectedErrors(err, []string{"400", "403", "404", "ContactNotExists"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCmsDynamicTagGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCmsDynamicTagGroupCreate,
Read: resourceAlicloudCmsDynamicTagGroupRead,
Delete: resourceAlicloudCmsDynamicTagGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"contact_group_list": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
ForceNew: true,
},
"tag_key": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"match_express": {
Type: schema.TypeSet,
Required: true,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"tag_value": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"tag_value_match_function": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
},
},
"match_express_filter_relation": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"template_id_list": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudCmsDynamicTagGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateDynamicTagGroup"
request := make(map[string]interface{})
conn, err := client.NewCmsClient()
if err != nil {
return WrapError(err)
}
request["ContactGroupList"] = d.Get("contact_group_list")
if v, ok := d.GetOk("match_express"); ok {
for matchExpressPtr, matchExpress := range v.(*schema.Set).List() {
matchExpressArg := matchExpress.(map[string]interface{})
request["MatchExpress."+fmt.Sprint(matchExpressPtr+1)+".TagValue"] = matchExpressArg["tag_value"]
request["MatchExpress."+fmt.Sprint(matchExpressPtr+1)+".TagValueMatchFunction"] = matchExpressArg["tag_value_match_function"]
}
}
if v, ok := d.GetOk("match_express_filter_relation"); ok {
request["MatchExpressFilterRelation"] = v
}
request["TagRegionId"] = client.RegionId
request["TagKey"] = d.Get("tag_key")
if v, ok := d.GetOk("template_id_list"); ok {
request["TemplateIdList"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cms_dynamic_tag_group", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetId(fmt.Sprint(response["Id"]))
return resourceAlicloudCmsDynamicTagGroupRead(d, meta)
}
func resourceAlicloudCmsDynamicTagGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cmsService := CmsService{client}
object, err := cmsService.DescribeCmsDynamicTagGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cms_dynamic_tag_group cmsService.DescribeCmsDynamicTagGroup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("status", object["Status"])
d.Set("match_express_filter_relation", object["MatchExpressFilterRelation"])
d.Set("template_id_list", object["TemplateIdList"])
if matchExpressMap, ok := object["MatchExpress"]; ok && matchExpressMap != nil {
resourceData := make([]map[string]interface{}, 0)
for _, matchExpressListItem := range matchExpressMap.(map[string]interface{}) {
for _, val := range matchExpressListItem.([]interface{}) {
matchExpressObject := make(map[string]interface{}, 0)
matchExpressObject["tag_value"] = val.(map[string]interface{})["TagValue"]
matchExpressObject["tag_value_match_function"] = val.(map[string]interface{})["TagValueMatchFunction"]
resourceData = append(resourceData, matchExpressObject)
}
}
d.Set("match_express", resourceData)
}
d.Set("tag_key", object["TagKey"])
return nil
}
func resourceAlicloudCmsDynamicTagGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteDynamicTagGroup"
var response map[string]interface{}
conn, err := client.NewCmsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DynamicTagRuleId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCmsGroupMetricRule() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCmsGroupMetricRuleCreate,
Read: resourceAlicloudCmsGroupMetricRuleRead,
Update: resourceAlicloudCmsGroupMetricRuleUpdate,
Delete: resourceAlicloudCmsGroupMetricRuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(3 * time.Minute),
Update: schema.DefaultTimeout(3 * time.Minute),
},
Schema: map[string]*schema.Schema{
"category": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"contact_groups": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"dimensions": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"effective_interval": {
Type: schema.TypeString,
Optional: true,
},
"email_subject": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"escalations": {
Type: schema.TypeSet,
Required: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"critical": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"comparison_operator": {
Type: schema.TypeString,
Optional: true,
},
"statistics": {
Type: schema.TypeString,
Optional: true,
},
"threshold": {
Type: schema.TypeString,
Optional: true,
},
"times": {
Type: schema.TypeInt,
Optional: true,
},
},
},
},
"info": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"comparison_operator": {
Type: schema.TypeString,
Optional: true,
},
"statistics": {
Type: schema.TypeString,
Optional: true,
},
"threshold": {
Type: schema.TypeString,
Optional: true,
},
"times": {
Type: schema.TypeInt,
Optional: true,
},
},
},
},
"warn": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"comparison_operator": {
Type: schema.TypeString,
Optional: true,
},
"statistics": {
Type: schema.TypeString,
Optional: true,
},
"threshold": {
Type: schema.TypeString,
Optional: true,
},
"times": {
Type: schema.TypeInt,
Optional: true,
},
},
},
},
},
},
},
"group_id": {
Type: schema.TypeString,
Required: true,
},
"group_metric_rule_name": {
Type: schema.TypeString,
Required: true,
},
"interval": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"metric_name": {
Type: schema.TypeString,
Required: true,
},
"namespace": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"no_effective_interval": {
Type: schema.TypeString,
Optional: true,
},
"period": {
Type: schema.TypeInt,
Optional: true,
Default: 300,
},
"rule_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"silence_time": {
Type: schema.TypeInt,
Optional: true,
Default: 86400,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"webhook": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudCmsGroupMetricRuleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "PutGroupMetricRule"
request := make(map[string]interface{})
conn, err := client.NewCmsClient()
if err != nil {
return WrapError(err)
}
request["Category"] = d.Get("category")
if v, ok := d.GetOk("contact_groups"); ok {
request["ContactGroups"] = v
}
if v, ok := d.GetOk("dimensions"); ok {
request["Dimensions"] = v
}
if v, ok := d.GetOk("effective_interval"); ok {
request["EffectiveInterval"] = v
}
if v, ok := d.GetOk("email_subject"); ok {
request["EmailSubject"] = v
}
if v, ok := d.GetOk("escalations"); ok {
if v != nil {
escalationsMap := make(map[string]interface{})
for _, escalations := range v.(*schema.Set).List() {
escalationsArg := escalations.(map[string]interface{})
if escalationsArg["critical"] != nil {
criticalMap := make(map[string]interface{})
for _, critical := range escalationsArg["critical"].(*schema.Set).List() {
criticalArg := critical.(map[string]interface{})
criticalMap["ComparisonOperator"] = criticalArg["comparison_operator"].(string)
criticalMap["Statistics"] = criticalArg["statistics"].(string)
criticalMap["Threshold"] = criticalArg["threshold"].(string)
criticalMap["Times"] = requests.NewInteger(criticalArg["times"].(int))
}
escalationsMap["Critical"] = criticalMap
}
if escalationsArg["info"] != nil {
infoMap := make(map[string]interface{})
for _, info := range escalationsArg["info"].(*schema.Set).List() {
infoArg := info.(map[string]interface{})
infoMap["ComparisonOperator"] = infoArg["comparison_operator"].(string)
infoMap["Statistics"] = infoArg["statistics"].(string)
infoMap["Threshold"] = infoArg["threshold"].(string)
infoMap["Times"] = requests.NewInteger(infoArg["times"].(int))
}
escalationsMap["Info"] = infoMap
}
if escalationsArg["warn"] != nil {
warnMap := make(map[string]interface{})
for _, warn := range escalationsArg["warn"].(*schema.Set).List() {
warnArg := warn.(map[string]interface{})
warnMap["ComparisonOperator"] = warnArg["comparison_operator"].(string)
warnMap["Statistics"] = warnArg["statistics"].(string)
warnMap["Threshold"] = warnArg["threshold"].(string)
warnMap["Times"] = requests.NewInteger(warnArg["times"].(int))
}
escalationsMap["Warn"] = warnMap
}
}
request["Escalations"] = escalationsMap
}
}
request["GroupId"] = d.Get("group_id")
request["RuleName"] = d.Get("group_metric_rule_name")
if v, ok := d.GetOk("interval"); ok {
request["Interval"] = v
}
request["MetricName"] = d.Get("metric_name")
request["Namespace"] = d.Get("namespace")
if v, ok := d.GetOk("no_effective_interval"); ok {
request["NoEffectiveInterval"] = v
}
if v, ok := d.GetOk("period"); ok {
request["Period"] = v
}
request["RuleId"] = d.Get("rule_id")
if v, ok := d.GetOk("silence_time"); ok {
request["SilenceTime"] = v
}
if v, ok := d.GetOk("webhook"); ok {
request["Webhook"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ExceedingQuota", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cms_group_metric_rule", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
return WrapError(Error("PutGroupMetricRule failed for " + response["Message"].(string)))
}
d.SetId(fmt.Sprint(request["RuleId"]))
return resourceAlicloudCmsGroupMetricRuleRead(d, meta)
}
func resourceAlicloudCmsGroupMetricRuleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cmsService := CmsService{client}
object, err := cmsService.DescribeCmsGroupMetricRule(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cms_group_metric_rule cmsService.DescribeCmsGroupMetricRule Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("rule_id", d.Id())
d.Set("contact_groups", object["ContactGroups"])
d.Set("dimensions", object["Dimensions"])
d.Set("effective_interval", object["EffectiveInterval"])
d.Set("email_subject", object["MailSubject"])
escalationsSli := make([]map[string]interface{}, 0)
if len(object["Escalations"].(map[string]interface{})) > 0 {
escalations := object["Escalations"]
escalationsMap := make(map[string]interface{})
criticalSli := make([]map[string]interface{}, 0)
if len(escalations.(map[string]interface{})["Critical"].(map[string]interface{})) > 0 {
critical := escalations.(map[string]interface{})["Critical"]
criticalMap := make(map[string]interface{})
criticalMap["comparison_operator"] = critical.(map[string]interface{})["ComparisonOperator"]
criticalMap["statistics"] = critical.(map[string]interface{})["Statistics"]
criticalMap["threshold"] = critical.(map[string]interface{})["Threshold"]
criticalMap["times"] = critical.(map[string]interface{})["Times"]
criticalSli = append(criticalSli, criticalMap)
}
escalationsMap["critical"] = criticalSli
infoSli := make([]map[string]interface{}, 0)
if len(escalations.(map[string]interface{})["Info"].(map[string]interface{})) > 0 {
info := escalations.(map[string]interface{})["Info"]
infoMap := make(map[string]interface{})
infoMap["comparison_operator"] = info.(map[string]interface{})["ComparisonOperator"]
infoMap["statistics"] = info.(map[string]interface{})["Statistics"]
infoMap["threshold"] = info.(map[string]interface{})["Threshold"]
infoMap["times"] = info.(map[string]interface{})["Times"]
infoSli = append(infoSli, infoMap)
}
escalationsMap["info"] = infoSli
warnSli := make([]map[string]interface{}, 0)
if len(escalations.(map[string]interface{})["Warn"].(map[string]interface{})) > 0 {
warn := escalations.(map[string]interface{})["Warn"]
warnMap := make(map[string]interface{})
warnMap["comparison_operator"] = warn.(map[string]interface{})["ComparisonOperator"]
warnMap["statistics"] = warn.(map[string]interface{})["Statistics"]
warnMap["threshold"] = warn.(map[string]interface{})["Threshold"]
warnMap["times"] = warn.(map[string]interface{})["Times"]
warnSli = append(warnSli, warnMap)
}
escalationsMap["warn"] = warnSli
escalationsSli = append(escalationsSli, escalationsMap)
}
d.Set("escalations", escalationsSli)
d.Set("group_id", object["GroupId"])
d.Set("group_metric_rule_name", object["RuleName"])
d.Set("metric_name", object["MetricName"])
d.Set("namespace", object["Namespace"])
d.Set("no_effective_interval", object["NoEffectiveInterval"])
d.Set("period", formatInt(object["Period"]))
d.Set("silence_time", formatInt(object["SilenceTime"]))
d.Set("status", object["AlertState"])
d.Set("webhook", object["Webhook"])
return nil
}
func resourceAlicloudCmsGroupMetricRuleUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"RuleId": d.Id(),
}
if d.HasChange("group_id") {
update = true
}
request["GroupId"] = d.Get("group_id")
if d.HasChange("group_metric_rule_name") {
update = true
}
request["RuleName"] = d.Get("group_metric_rule_name")
if d.HasChange("metric_name") {
update = true
}
request["MetricName"] = d.Get("metric_name")
request["Namespace"] = d.Get("namespace")
if d.HasChange("contact_groups") {
update = true
request["ContactGroups"] = d.Get("contact_groups")
}
if d.HasChange("dimensions") {
update = true
request["Dimensions"] = d.Get("dimensions")
}
if d.HasChange("effective_interval") {
update = true
request["EffectiveInterval"] = d.Get("effective_interval")
}
if d.HasChange("email_subject") {
update = true
request["EmailSubject"] = d.Get("email_subject")
}
if d.HasChange("escalations") {
update = true
if d.Get("escalations") != nil {
escalationsMap := make(map[string]interface{})
for _, escalations := range d.Get("escalations").(*schema.Set).List() {
escalationsArg := escalations.(map[string]interface{})
if escalationsArg["critical"] != nil {
criticalMap := make(map[string]interface{})
for _, critical := range escalationsArg["critical"].(*schema.Set).List() {
criticalArg := critical.(map[string]interface{})
criticalMap["ComparisonOperator"] = criticalArg["comparison_operator"].(string)
criticalMap["Statistics"] = criticalArg["statistics"].(string)
criticalMap["Threshold"] = criticalArg["threshold"].(string)
criticalMap["Times"] = requests.NewInteger(criticalArg["times"].(int))
}
escalationsMap["Critical"] = criticalMap
}
if escalationsArg["info"] != nil {
infoMap := make(map[string]interface{})
for _, info := range escalationsArg["info"].(*schema.Set).List() {
infoArg := info.(map[string]interface{})
infoMap["ComparisonOperator"] = infoArg["comparison_operator"].(string)
infoMap["Statistics"] = infoArg["statistics"].(string)
infoMap["Threshold"] = infoArg["threshold"].(string)
infoMap["Times"] = requests.NewInteger(infoArg["times"].(int))
}
escalationsMap["Info"] = infoMap
}
if escalationsArg["warn"] != nil {
warnMap := make(map[string]interface{})
for _, warn := range escalationsArg["warn"].(*schema.Set).List() {
warnArg := warn.(map[string]interface{})
warnMap["ComparisonOperator"] = warnArg["comparison_operator"].(string)
warnMap["Statistics"] = warnArg["statistics"].(string)
warnMap["Threshold"] = warnArg["threshold"].(string)
warnMap["Times"] = requests.NewInteger(warnArg["times"].(int))
}
escalationsMap["Warn"] = warnMap
}
}
request["Escalations"] = escalationsMap
}
}
if d.HasChange("no_effective_interval") {
update = true
request["NoEffectiveInterval"] = d.Get("no_effective_interval")
}
if d.HasChange("period") {
update = true
request["Period"] = d.Get("period")
}
if d.HasChange("silence_time") {
update = true
request["SilenceTime"] = d.Get("silence_time")
}
if d.HasChange("webhook") {
update = true
request["Webhook"] = d.Get("webhook")
}
if update {
request["Category"] = d.Get("category")
if _, ok := d.GetOk("interval"); ok {
request["Interval"] = d.Get("interval")
}
action := "PutGroupMetricRule"
conn, err := client.NewCmsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ExceedingQuota", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
return WrapError(Error("PutGroupMetricRule failed for " + response["Message"].(string)))
}
}
return resourceAlicloudCmsGroupMetricRuleRead(d, meta)
}
func resourceAlicloudCmsGroupMetricRuleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteMetricRules"
var response map[string]interface{}
conn, err := client.NewCmsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"Id": []string{d.Id()},
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ExceedingQuota", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if IsExpectedErrorCodes(fmt.Sprintf("%v", response["Code"]), []string{"400", "403", "404", "ResourceNotFound"}) {
return nil
}
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
return WrapError(Error("DeleteMetricRules failed for " + response["Message"].(string)))
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCmsMetricRuleTemplate() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCmsMetricRuleTemplateCreate,
Read: resourceAlicloudCmsMetricRuleTemplateRead,
Update: resourceAlicloudCmsMetricRuleTemplateUpdate,
Delete: resourceAlicloudCmsMetricRuleTemplateDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"alert_templates": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"category": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"ecs", "rds", "ads", "slb", "vpc", "apigateway", "cdn", "cs", "dcdn", "ddos", "eip", "elasticsearch", "emr", "ess", "hbase", "iot_edge", "kvstore_sharding", "kvstore_splitrw", "kvstore_standard", "memcache", "mns", "mongodb", "mongodb_cluster", "mongodb_sharding", "mq_topic", "ocs", "opensearch", "oss", "polardb", "petadata", "scdn", "sharebandwidthpackages", "sls", "vpn"}, false),
},
"escalations": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"critical": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"comparison_operator": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"GreaterThanOrEqualToThreshold", "GreaterThanThreshold", "LessThanOrEqualToThreshold", "LessThanThreshold", "NotEqualToThreshold", "GreaterThanYesterday", "LessThanYesterday", "GreaterThanLastWeek", "LessThanLastWeek", "GreaterThanLastPeriod", "LessThanLastPeriod"}, false),
},
"statistics": {
Type: schema.TypeString,
Optional: true,
},
"threshold": {
Type: schema.TypeString,
Optional: true,
},
"times": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"info": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"comparison_operator": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"GreaterThanOrEqualToThreshold", "GreaterThanThreshold", "LessThanOrEqualToThreshold", "LessThanThreshold", "NotEqualToThreshold", "GreaterThanYesterday", "LessThanYesterday", "GreaterThanLastWeek", "LessThanLastWeek", "GreaterThanLastPeriod", "LessThanLastPeriod"}, false),
},
"statistics": {
Type: schema.TypeString,
Optional: true,
},
"threshold": {
Type: schema.TypeString,
Optional: true,
},
"times": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"warn": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"comparison_operator": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"GreaterThanOrEqualToThreshold", "GreaterThanThreshold", "LessThanOrEqualToThreshold", "LessThanThreshold", "NotEqualToThreshold", "GreaterThanYesterday", "LessThanYesterday", "GreaterThanLastWeek", "LessThanLastWeek", "GreaterThanLastPeriod", "LessThanLastPeriod"}, false),
},
"statistics": {
Type: schema.TypeString,
Optional: true,
},
"threshold": {
Type: schema.TypeString,
Optional: true,
},
"times": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
},
},
},
"metric_name": {
Type: schema.TypeString,
Required: true,
},
"namespace": {
Type: schema.TypeString,
Required: true,
},
"rule_name": {
Type: schema.TypeString,
Required: true,
},
"webhook": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"apply_mode": {
Type: schema.TypeString,
Optional: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"enable_end_time": {
Type: schema.TypeString,
Optional: true,
},
"enable_start_time": {
Type: schema.TypeString,
Optional: true,
},
"group_id": {
Type: schema.TypeString,
Optional: true,
},
"metric_rule_template_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"notify_level": {
Type: schema.TypeString,
Optional: true,
},
"rest_version": {
Type: schema.TypeString,
Computed: true,
ForceNew: true,
},
"silence_time": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(0, 86400),
},
"webhook": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudCmsMetricRuleTemplateCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateMetricRuleTemplate"
request := make(map[string]interface{})
conn, err := client.NewCmsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("alert_templates"); ok {
alertTemplatesMaps := make([]map[string]interface{}, 0)
for _, alertTemplates := range v.(*schema.Set).List() {
alertTemplatesArg := alertTemplates.(map[string]interface{})
alertTemplatesMap := map[string]interface{}{}
alertTemplatesMap["Category"] = alertTemplatesArg["category"]
if escalationsMaps, ok := alertTemplatesArg["escalations"]; ok {
escalationsMap := map[string]interface{}{}
for _, escalationsArg := range escalationsMaps.(*schema.Set).List() {
if criticalMaps, ok := escalationsArg.(map[string]interface{})["critical"]; ok {
requestCriticalArg := map[string]interface{}{}
for _, criticalMap := range criticalMaps.(*schema.Set).List() {
criticalArg := criticalMap.(map[string]interface{})
requestCriticalArg["ComparisonOperator"] = criticalArg["comparison_operator"]
requestCriticalArg["Statistics"] = criticalArg["statistics"]
requestCriticalArg["Threshold"] = criticalArg["threshold"]
requestCriticalArg["Times"] = criticalArg["times"]
}
escalationsMap["Critical"] = requestCriticalArg
}
if infoMaps, ok := escalationsArg.(map[string]interface{})["info"]; ok {
requestInfoArg := map[string]interface{}{}
for _, infoMap := range infoMaps.(*schema.Set).List() {
infoArg := infoMap.(map[string]interface{})
requestInfoArg["ComparisonOperator"] = infoArg["comparison_operator"]
requestInfoArg["Statistics"] = infoArg["statistics"]
requestInfoArg["Threshold"] = infoArg["threshold"]
requestInfoArg["Times"] = infoArg["times"]
}
escalationsMap["Info"] = requestInfoArg
}
if warnMaps, ok := escalationsArg.(map[string]interface{})["warn"]; ok {
requestWarnArg := map[string]interface{}{}
for _, warnMap := range warnMaps.(*schema.Set).List() {
warnArg := warnMap.(map[string]interface{})
requestWarnArg["ComparisonOperator"] = warnArg["comparison_operator"]
requestWarnArg["Statistics"] = warnArg["statistics"]
requestWarnArg["Threshold"] = warnArg["threshold"]
requestWarnArg["Times"] = warnArg["times"]
}
escalationsMap["Warn"] = requestWarnArg
}
}
alertTemplatesMap["Escalations"] = escalationsMap
}
alertTemplatesMap["MetricName"] = alertTemplatesArg["metric_name"]
alertTemplatesMap["Namespace"] = alertTemplatesArg["namespace"]
alertTemplatesMap["RuleName"] = alertTemplatesArg["rule_name"]
alertTemplatesMap["Webhook"] = alertTemplatesArg["webhook"]
alertTemplatesMaps = append(alertTemplatesMaps, alertTemplatesMap)
}
request["AlertTemplates"] = alertTemplatesMaps
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["Name"] = d.Get("metric_rule_template_name")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cms_metric_rule_template", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetId(fmt.Sprint(response["Id"]))
return resourceAlicloudCmsMetricRuleTemplateUpdate(d, meta)
}
func resourceAlicloudCmsMetricRuleTemplateRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cmsService := CmsService{client}
object, err := cmsService.DescribeCmsMetricRuleTemplate(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cms_metric_rule_template cmsService.DescribeCmsMetricRuleTemplate Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
if alertTemplatesMap, ok := object["AlertTemplates"].(map[string]interface{}); ok && alertTemplatesMap != nil {
if alertTemplateList, ok := alertTemplatesMap["AlertTemplate"]; ok && alertTemplateList != nil {
alertTemplatesMaps := make([]map[string]interface{}, 0)
for _, alertTemplateListItem := range alertTemplateList.([]interface{}) {
if alertTemplateListItemMap, ok := alertTemplateListItem.(map[string]interface{}); ok {
alertTempArg := make(map[string]interface{}, 0)
alertTempArg["category"] = alertTemplateListItemMap["Category"]
alertTempArg["metric_name"] = alertTemplateListItemMap["MetricName"]
alertTempArg["namespace"] = alertTemplateListItemMap["Namespace"]
alertTempArg["rule_name"] = alertTemplateListItemMap["RuleName"]
alertTempArg["webhook"] = alertTemplateListItemMap["Webhook"]
escalationsMaps := make([]map[string]interface{}, 0)
escalationsMap := map[string]interface{}{}
if EscalationsMap, ok := alertTemplateListItemMap["Escalations"].(map[string]interface{}); ok && len(EscalationsMap) > 0 {
EscalationsArg := EscalationsMap
if criticalMap, ok := EscalationsArg["Critical"].(map[string]interface{}); ok && len(criticalMap) > 0 {
criticalMaps := make([]map[string]interface{}, 0)
criticalArg := map[string]interface{}{}
criticalArg["comparison_operator"] = criticalMap["ComparisonOperator"]
criticalArg["statistics"] = criticalMap["Statistics"]
criticalArg["threshold"] = criticalMap["Threshold"]
criticalArg["times"] = criticalMap["Times"]
criticalMaps = append(criticalMaps, criticalArg)
escalationsMap["critical"] = criticalMaps
}
if infoMap, ok := EscalationsArg["Info"].(map[string]interface{}); ok && len(infoMap) > 0 {
infoMaps := make([]map[string]interface{}, 0)
infoArg := map[string]interface{}{}
infoArg["comparison_operator"] = infoMap["ComparisonOperator"]
infoArg["statistics"] = infoMap["Statistics"]
infoArg["threshold"] = infoMap["Threshold"]
infoArg["times"] = infoMap["Times"]
infoMaps = append(infoMaps, infoArg)
escalationsMap["info"] = infoMaps
}
if warnMap, ok := EscalationsArg["Warn"].(map[string]interface{}); ok && len(warnMap) > 0 {
warnMaps := make([]map[string]interface{}, 0)
warnArg := make(map[string]interface{}, 0)
warnArg["comparison_operator"] = warnMap["ComparisonOperator"]
warnArg["statistics"] = warnMap["Statistics"]
warnArg["threshold"] = warnMap["Threshold"]
warnArg["times"] = warnMap["Times"]
warnMaps = append(warnMaps, warnArg)
escalationsMap["warn"] = warnMaps
}
}
escalationsMaps = append(escalationsMaps, escalationsMap)
alertTempArg["escalations"] = escalationsMaps
alertTemplatesMaps = append(alertTemplatesMaps, alertTempArg)
}
}
d.Set("alert_templates", alertTemplatesMaps)
}
}
d.Set("description", object["Description"])
d.Set("metric_rule_template_name", object["Name"])
d.Set("rest_version", object["RestVersion"])
return nil
}
func resourceAlicloudCmsMetricRuleTemplateUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"TemplateIds": d.Id(),
}
if d.HasChange("group_id") {
update = true
}
if v, ok := d.GetOk("group_id"); ok {
request["GroupId"] = v
}
if update {
if v, ok := d.GetOk("apply_mode"); ok {
request["ApplyMode"] = v
}
if v, ok := d.GetOk("enable_end_time"); ok {
request["EnableEndTime"] = v
}
if v, ok := d.GetOk("enable_start_time"); ok {
request["EnableStartTime"] = v
}
if v, ok := d.GetOk("notify_level"); ok {
request["NotifyLevel"] = v
}
if v, ok := d.GetOk("silence_time"); ok {
request["SilenceTime"] = v
}
if v, ok := d.GetOk("webhook"); ok {
request["Webhook"] = v
}
action := "ApplyMetricRuleTemplate"
conn, err := client.NewCmsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetPartial("group_id")
}
update = false
modifyMetricRuleTemplateReq := map[string]interface{}{
"TemplateId": d.Id(),
}
if v, ok := d.GetOk("rest_version"); ok {
modifyMetricRuleTemplateReq["RestVersion"] = v
}
if !d.IsNewResource() && d.HasChange("alert_templates") {
update = true
if v, ok := d.GetOk("alert_templates"); ok {
alertTemplatesMaps := make([]map[string]interface{}, 0)
for _, alertTemplates := range v.(*schema.Set).List() {
alertTemplatesArg := alertTemplates.(map[string]interface{})
alertTemplatesMap := map[string]interface{}{}
alertTemplatesMap["Category"] = alertTemplatesArg["category"]
if escalationsMaps, ok := alertTemplatesArg["escalations"]; ok {
escalationsMap := map[string]interface{}{}
for _, escalationsArg := range escalationsMaps.(*schema.Set).List() {
if criticalMaps, ok := escalationsArg.(map[string]interface{})["critical"]; ok {
requestCriticalArg := map[string]interface{}{}
for _, criticalMap := range criticalMaps.(*schema.Set).List() {
criticalArg := criticalMap.(map[string]interface{})
requestCriticalArg["ComparisonOperator"] = criticalArg["comparison_operator"]
requestCriticalArg["Statistics"] = criticalArg["statistics"]
requestCriticalArg["Threshold"] = criticalArg["threshold"]
requestCriticalArg["Times"] = criticalArg["times"]
}
escalationsMap["Critical"] = requestCriticalArg
}
if infoMaps, ok := escalationsArg.(map[string]interface{})["info"]; ok {
requestInfoArg := map[string]interface{}{}
for _, infoMap := range infoMaps.(*schema.Set).List() {
infoArg := infoMap.(map[string]interface{})
requestInfoArg["ComparisonOperator"] = infoArg["comparison_operator"]
requestInfoArg["Statistics"] = infoArg["statistics"]
requestInfoArg["Threshold"] = infoArg["threshold"]
requestInfoArg["Times"] = infoArg["times"]
}
escalationsMap["Info"] = requestInfoArg
}
if warnMaps, ok := escalationsArg.(map[string]interface{})["warn"]; ok {
requestWarnArg := map[string]interface{}{}
for _, warnMap := range warnMaps.(*schema.Set).List() {
warnArg := warnMap.(map[string]interface{})
requestWarnArg["ComparisonOperator"] = warnArg["comparison_operator"]
requestWarnArg["Statistics"] = warnArg["statistics"]
requestWarnArg["Threshold"] = warnArg["threshold"]
requestWarnArg["Times"] = warnArg["times"]
}
escalationsMap["Warn"] = requestWarnArg
}
}
alertTemplatesMap["Escalations"] = escalationsMap
}
alertTemplatesMap["MetricName"] = alertTemplatesArg["metric_name"]
alertTemplatesMap["Namespace"] = alertTemplatesArg["namespace"]
alertTemplatesMap["RuleName"] = alertTemplatesArg["rule_name"]
alertTemplatesMap["Webhook"] = alertTemplatesArg["webhook"]
alertTemplatesMaps = append(alertTemplatesMaps, alertTemplatesMap)
}
modifyMetricRuleTemplateReq["AlertTemplates"] = alertTemplatesMaps
}
}
if !d.IsNewResource() && d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
modifyMetricRuleTemplateReq["Description"] = v
}
}
if !d.IsNewResource() && d.HasChange("metric_rule_template_name") {
update = true
modifyMetricRuleTemplateReq["Name"] = d.Get("metric_rule_template_name")
}
if update {
action := "ModifyMetricRuleTemplate"
conn, err := client.NewCmsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, modifyMetricRuleTemplateReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyMetricRuleTemplateReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetPartial("rest_version")
d.SetPartial("alert_templates")
d.SetPartial("description")
d.SetPartial("metric_rule_template_name")
}
d.Partial(false)
return resourceAlicloudCmsMetricRuleTemplateRead(d, meta)
}
func resourceAlicloudCmsMetricRuleTemplateDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteMetricRuleTemplate"
var response map[string]interface{}
conn, err := client.NewCmsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"TemplateId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if IsExpectedErrorCodes(fmt.Sprint(response["Code"]), []string{"ResourceNotFound"}) {
return nil
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCmsMonitorGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCmsMonitorGroupCreate,
Read: resourceAlicloudCmsMonitorGroupRead,
Update: resourceAlicloudCmsMonitorGroupUpdate,
Delete: resourceAlicloudCmsMonitorGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"contact_groups": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"monitor_group_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"tags": tagsSchema(),
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
},
"resource_group_name": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudCmsMonitorGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewCmsClient()
var response map[string]interface{}
request := make(map[string]interface{})
if v, exist := d.GetOk("resource_group_id"); exist {
action := "CreateMonitorGroupByResourceGroupId"
request["RegionId"] = client.RegionId
request["ResourceGroupId"] = v.(string)
request["ResourceGroupName"] = d.Get("resource_group_name")
for k, v := range d.Get("contact_groups").([]interface{}) {
request[fmt.Sprintf("ContactGroupList.%d", k+1)] = v.(string)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cms_monitor_group", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["Id"]))
return resourceAlicloudCmsMonitorGroupUpdate(d, meta)
}
action := "CreateMonitorGroup"
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("contact_groups"); ok && v != nil {
request["ContactGroups"] = convertListToCommaSeparate(v.([]interface{}))
}
request["GroupName"] = d.Get("monitor_group_name")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cms_monitor_group", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
return WrapError(Error("CreateMonitorGroup failed for " + response["Message"].(string)))
}
d.SetId(fmt.Sprint(formatInt(response["GroupId"])))
return resourceAlicloudCmsMonitorGroupUpdate(d, meta)
}
func resourceAlicloudCmsMonitorGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cmsService := CmsService{client}
object, err := cmsService.DescribeCmsMonitorGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cms_monitor_group cmsService.DescribeCmsMonitorGroup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
var contactGroups []interface{}
if v, ok := object["ContactGroups"].(map[string]interface{})["ContactGroup"]; ok {
for _, contactGroup := range v.([]interface{}) {
contactGroups = append(contactGroups, contactGroup.(map[string]interface{})["Name"])
}
}
d.Set("contact_groups", contactGroups)
d.Set("monitor_group_name", object["GroupName"])
d.Set("tags", tagsToMap(object["Tags"].(map[string]interface{})["Tag"]))
return nil
}
func resourceAlicloudCmsMonitorGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cmsService := CmsService{client}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"GroupId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("contact_groups") {
update = true
request["ContactGroups"] = convertListToCommaSeparate(d.Get("contact_groups").([]interface{}))
}
if d.HasChange("monitor_group_name") {
update = true
request["GroupName"] = d.Get("monitor_group_name")
}
if update {
action := "ModifyMonitorGroup"
conn, err := client.NewCmsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if !response["Success"].(bool) {
return WrapError(Error("ModifyMonitorGroup failed for " + response["Message"].(string)))
}
d.SetPartial("contact_groups")
d.SetPartial("monitor_group_name")
}
if d.HasChange("tags") {
if err := cmsService.SetResourceTags(d, ""); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
d.Partial(false)
return resourceAlicloudCmsMonitorGroupRead(d, meta)
}
func resourceAlicloudCmsMonitorGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteMonitorGroup"
var response map[string]interface{}
conn, err := client.NewCmsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"GroupId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if IsExpectedErrorCodes(fmt.Sprintf("%v", response["Code"]), []string{"400", "403", "404", "ResourceNotFound"}) {
return nil
}
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
return WrapError(Error("DeleteMonitorGroup failed for " + response["Message"].(string)))
}
return nil
}
package alicloud
import (
"fmt"
"log"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCmsMonitorGroupInstances() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCmsMonitorGroupInstancesCreate,
Read: resourceAlicloudCmsMonitorGroupInstancesRead,
Update: resourceAlicloudCmsMonitorGroupInstancesUpdate,
Delete: resourceAlicloudCmsMonitorGroupInstancesDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instances": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"category": {
Type: schema.TypeString,
Required: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
},
"instance_name": {
Type: schema.TypeString,
Required: true,
},
"region_id": {
Type: schema.TypeString,
Required: true,
},
},
},
},
},
}
}
func resourceAlicloudCmsMonitorGroupInstancesCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateMonitorGroupInstances"
request := make(map[string]interface{})
conn, err := client.NewCmsClient()
if err != nil {
return WrapError(err)
}
request["GroupId"] = d.Get("group_id")
Instances := make([]map[string]interface{}, len(d.Get("instances").(*schema.Set).List()))
for i, InstancesValue := range d.Get("instances").(*schema.Set).List() {
InstancesMap := InstancesValue.(map[string]interface{})
Instances[i] = make(map[string]interface{})
Instances[i]["Category"] = InstancesMap["category"]
Instances[i]["InstanceId"] = InstancesMap["instance_id"]
Instances[i]["InstanceName"] = InstancesMap["instance_name"]
Instances[i]["RegionId"] = InstancesMap["region_id"]
}
request["Instances"] = Instances
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cms_monitor_group_instances", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
return WrapError(Error("CreateMonitorGroupInstances failed for " + response["Message"].(string)))
}
d.SetId(fmt.Sprint(request["GroupId"]))
return resourceAlicloudCmsMonitorGroupInstancesRead(d, meta)
}
func resourceAlicloudCmsMonitorGroupInstancesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cmsService := CmsService{client}
object, err := cmsService.DescribeCmsMonitorGroupInstances(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cms_monitor_group_instances cmsService.DescribeCmsMonitorGroupInstances Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("group_id", d.Id())
resourceMap := make([]map[string]interface{}, 0)
for _, v := range object {
temp1 := map[string]interface{}{
"category": strings.ToLower(v["Category"].(string)),
"instance_id": v["InstanceId"],
"instance_name": v["InstanceName"],
"region_id": v["RegionId"],
}
resourceMap = append(resourceMap, temp1)
}
if err := d.Set("instances", resourceMap); err != nil {
return WrapError(err)
}
return nil
}
func resourceAlicloudCmsMonitorGroupInstancesUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
if d.HasChange("instances") {
request := map[string]interface{}{
"GroupId": d.Id(),
}
Instances := make([]map[string]interface{}, len(d.Get("instances").(*schema.Set).List()))
for i, InstancesValue := range d.Get("instances").(*schema.Set).List() {
InstancesMap := InstancesValue.(map[string]interface{})
Instances[i] = make(map[string]interface{})
Instances[i]["Category"] = InstancesMap["category"]
Instances[i]["InstanceId"] = InstancesMap["instance_id"]
Instances[i]["InstanceName"] = InstancesMap["instance_name"]
Instances[i]["RegionId"] = InstancesMap["region_id"]
}
request["Instances"] = Instances
action := "ModifyMonitorGroupInstances"
conn, err := client.NewCmsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
return WrapError(Error("ModifyMonitorGroupInstances failed for " + response["Message"].(string)))
}
}
return resourceAlicloudCmsMonitorGroupInstancesRead(d, meta)
}
func resourceAlicloudCmsMonitorGroupInstancesDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteMonitorGroupInstances"
var response map[string]interface{}
conn, err := client.NewCmsClient()
if err != nil {
return WrapError(err)
}
info := make(map[string]string)
for _, InstancesValue := range d.Get("instances").(*schema.Set).List() {
InstancesMap := InstancesValue.(map[string]interface{})
if value, ok := info[InstancesMap["category"].(string)]; ok {
info[InstancesMap["category"].(string)] = value + "," + InstancesMap["instance_id"].(string)
} else {
info[InstancesMap["category"].(string)] = InstancesMap["instance_id"].(string)
}
}
for category, instanceIds := range info {
request := map[string]interface{}{
"GroupId": d.Id(),
"Category": category,
"InstanceIdList": instanceIds,
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if IsExpectedErrorCodes(fmt.Sprintf("%v", response["Code"]), []string{"ResourceNotFound"}) {
return nil
}
if fmt.Sprintf("%v", response["Code"]) != "200" {
return WrapError(Error("DeleteMonitorGroupInstances failed for " + response["Message"].(string)))
}
}
return nil
}
package alicloud
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cms"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
)
func resourceAlicloudCmsSiteMonitor() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCmsSiteMonitorCreate,
Read: resourceAlicloudCmsSiteMonitorRead,
Update: resourceAlicloudCmsSiteMonitorUpdate,
Delete: resourceAlicloudCmsSiteMonitorDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"address": {
Type: schema.TypeString,
Required: true,
},
"task_name": {
Type: schema.TypeString,
Required: true,
},
"task_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{SiteMonitorHTTP, SiteMonitorDNS, SiteMonitorFTP, SiteMonitorPOP3,
SiteMonitorPing, SiteMonitorSMTP, SiteMonitorTCP, SiteMonitorUDP}, false),
},
"alert_ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"interval": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
ValidateFunc: validation.IntInSlice([]int{1, 5, 15}),
},
"options_json": {
Type: schema.TypeString,
Optional: true,
},
"isp_cities": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"city": {
Type: schema.TypeString,
Required: true,
},
"isp": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"task_state": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"update_time": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudCmsSiteMonitorCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
taskName := d.Get("task_name").(string)
request := cms.CreateCreateSiteMonitorRequest()
request.Address = d.Get("address").(string)
request.TaskName = taskName
request.TaskType = d.Get("task_type").(string)
request.Interval = strconv.Itoa(d.Get("interval").(int))
request.OptionsJson = d.Get("options_json").(string)
alertIds := d.Get("alert_ids").([]interface{})
alertId := getAlertId(alertIds)
if alertId != "" {
request.AlertIds = alertId
}
if isp_cities, ok := d.GetOk("isp_cities"); ok {
var a []map[string]interface{}
for _, element := range isp_cities.(*schema.Set).List() {
isp_city := element.(map[string]interface{})
a = append(a, isp_city)
}
b, err := json.Marshal(a)
if err != nil {
return WrapError(err)
}
request.IspCities = bytes.NewBuffer(b).String()
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithCmsClient(func(cmsClient *cms.Client) (interface{}, error) {
return cmsClient.CreateSiteMonitor(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ExceedingQuota"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), request.RpcRequest, request)
resp, _ := raw.(*cms.CreateSiteMonitorResponse)
d.SetId(resp.CreateResultList.CreateResultListItem[0].TaskId)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cms_site_monitor", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return resourceAlicloudCmsSiteMonitorRead(d, meta)
}
func resourceAlicloudCmsSiteMonitorRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cmsService := CmsService{client}
siteMonitor, err := cmsService.DescribeSiteMonitor(d.Id(), "")
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("address", siteMonitor.Address)
d.Set("task_name", siteMonitor.TaskName)
d.Set("task_type", siteMonitor.TaskType)
d.Set("task_state", siteMonitor.TaskState)
d.Set("interval", siteMonitor.Interval)
d.Set("options_json", siteMonitor.OptionsJson)
d.Set("create_time", siteMonitor.CreateTime)
d.Set("update_time", siteMonitor.UpdateTime)
ispCities, err := cmsService.GetIspCities(d.Id())
var list []map[string]interface{}
for _, e := range ispCities {
list = append(list, map[string]interface{}{"city": e["city"], "isp": e["isp"]})
}
if err = d.Set("isp_cities", list); err != nil {
return WrapError(err)
}
return nil
}
func resourceAlicloudCmsSiteMonitorUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := cms.CreateModifySiteMonitorRequest()
request.TaskId = d.Id()
request.Address = d.Get("address").(string)
request.Interval = strconv.Itoa(d.Get("interval").(int))
request.OptionsJson = d.Get("options_json").(string)
request.TaskName = d.Get("task_name").(string)
alertIds := d.Get("alert_ids").([]interface{})
alertId := getAlertId(alertIds)
if alertId != "" {
request.AlertIds = alertId
}
if isp_cities, ok := d.GetOk("isp_cities"); ok {
var a []map[string]interface{}
for _, element := range isp_cities.(*schema.Set).List() {
isp_city := element.(map[string]interface{})
a = append(a, isp_city)
}
b, err := json.Marshal(a)
if err != nil {
return WrapError(err)
}
request.IspCities = bytes.NewBuffer(b).String()
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
_, err := client.WithCmsClient(func(cmsClient *cms.Client) (interface{}, error) {
return cmsClient.ModifySiteMonitor(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ExceedingQuota"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), request.RpcRequest, request)
return nil
})
if err != nil {
return WrapError(err)
}
return resourceAlicloudCmsSiteMonitorRead(d, meta)
}
func resourceAlicloudCmsSiteMonitorDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cmsService := CmsService{client}
request := cms.CreateDeleteSiteMonitorsRequest()
request.TaskIds = d.Id()
request.IsDeleteAlarms = "false"
wait := incrementalWait(3*time.Second, 5*time.Second)
return resource.Retry(3*time.Minute, func() *resource.RetryError {
_, err := client.WithCmsClient(func(cmsClient *cms.Client) (interface{}, error) {
return cmsClient.DeleteSiteMonitors(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ExceedingQuota"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(fmt.Errorf("Deleting site monitor got an error: %#v", err))
}
_, err = cmsService.DescribeSiteMonitor(d.Id(), "")
if err != nil {
if NotFoundError(err) {
return nil
}
return resource.NonRetryableError(fmt.Errorf("DescribeSiteMonitor got an error: %#v", err))
}
return resource.RetryableError(fmt.Errorf("Deleting site monitor got an error: %#v", err))
})
}
func getAlertId(alertIds []interface{}) string {
if alertIds != nil && len(alertIds) > 0 {
alertId := strings.Join(expandStringList(alertIds), ",")
return alertId
}
return ""
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCommonBandwidthPackage() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCommonBandwidthPackageCreate,
Read: resourceAlicloudCommonBandwidthPackageRead,
Update: resourceAlicloudCommonBandwidthPackageUpdate,
Delete: resourceAlicloudCommonBandwidthPackageDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"bandwidth": {
Type: schema.TypeString,
Required: true,
},
"bandwidth_package_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"name"},
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Field 'name' has been deprecated from provider version 1.120.0. New field 'bandwidth_package_name' instead.",
ConflictsWith: []string{"bandwidth_package_name"},
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"force": {
Type: schema.TypeString,
Optional: true,
},
"isp": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"BGP", "BGP_PRO"}, false),
Default: "BGP",
},
"internet_charge_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PayBy95", "PayByBandwidth", "PayByTraffic"}, false),
Default: "PayByTraffic",
},
"ratio": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IntBetween(10, 100),
Default: 100,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"zone": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"deletion_protection": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
},
}
}
func resourceAlicloudCommonBandwidthPackageCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
action := "CreateCommonBandwidthPackage"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request["Bandwidth"] = d.Get("bandwidth")
if v, ok := d.GetOk("bandwidth_package_name"); ok {
request["Name"] = v
} else if v, ok := d.GetOk("name"); ok {
request["Name"] = v
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("isp"); ok {
request["ISP"] = v
}
if v, ok := d.GetOk("internet_charge_type"); ok {
request["InternetChargeType"] = v
}
if v, ok := d.GetOk("ratio"); ok {
request["Ratio"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("zone"); ok {
request["Zone"] = v
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("CreateCommonBandwidthPackage")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"BandwidthPackageOperation.conflict", "Throttling"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_common_bandwidth_package", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["BandwidthPackageId"]))
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, vpcService.CommonBandwidthPackageStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudCommonBandwidthPackageRead(d, meta)
}
func resourceAlicloudCommonBandwidthPackageRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeCommonBandwidthPackage(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_common_bandwidth_package vpcService.DescribeCommonBandwidthPackage Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("bandwidth", object["Bandwidth"])
d.Set("bandwidth_package_name", object["Name"])
d.Set("name", object["Name"])
d.Set("description", object["Description"])
d.Set("isp", object["ISP"])
d.Set("internet_charge_type", object["InternetChargeType"])
d.Set("ratio", formatInt(object["Ratio"]))
d.Set("resource_group_id", object["ResourceGroupId"])
d.Set("status", object["Status"])
d.Set("deletion_protection", object["DeletionProtection"])
return nil
}
func resourceAlicloudCommonBandwidthPackageUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
d.Partial(true)
if d.HasChange("deletion_protection") {
var response map[string]interface{}
action := "DeletionProtection"
request := map[string]interface{}{
"RegionId": client.RegionId,
"InstanceId": d.Id(),
"ProtectionEnable": d.Get("deletion_protection"),
"Type": "CBWP",
}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken(action)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("deletion_protection")
}
update := false
request := map[string]interface{}{
"BandwidthPackageId": d.Id(),
}
if d.HasChange("bandwidth") {
update = true
}
request["Bandwidth"] = d.Get("bandwidth")
request["RegionId"] = client.RegionId
if update {
action := "ModifyCommonBandwidthPackageSpec"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("bandwidth")
}
update = false
modifyCommonBandwidthPackageAttributeReq := map[string]interface{}{
"BandwidthPackageId": d.Id(),
}
modifyCommonBandwidthPackageAttributeReq["RegionId"] = client.RegionId
if d.HasChange("bandwidth_package_name") {
update = true
modifyCommonBandwidthPackageAttributeReq["Name"] = d.Get("bandwidth_package_name")
}
if d.HasChange("name") {
update = true
modifyCommonBandwidthPackageAttributeReq["Name"] = d.Get("name")
}
if d.HasChange("description") {
update = true
modifyCommonBandwidthPackageAttributeReq["Description"] = d.Get("description")
}
if update {
action := "ModifyCommonBandwidthPackageAttribute"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, modifyCommonBandwidthPackageAttributeReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, modifyCommonBandwidthPackageAttributeReq)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("name")
d.SetPartial("bandwidth_package_name")
d.SetPartial("description")
}
update = false
moveResourceGroupReq := map[string]interface{}{
"ResourceId": d.Id(),
}
moveResourceGroupReq["RegionId"] = client.RegionId
if d.HasChange("resource_group_id") {
update = true
}
moveResourceGroupReq["NewResourceGroupId"] = d.Get("resource_group_id")
moveResourceGroupReq["ResourceType"] = "bandwidthpackage"
if update {
action := "MoveResourceGroup"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, moveResourceGroupReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, moveResourceGroupReq)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("resource_group_id")
}
d.Partial(false)
return resourceAlicloudCommonBandwidthPackageRead(d, meta)
}
func resourceAlicloudCommonBandwidthPackageDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
action := "DeleteCommonBandwidthPackage"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"BandwidthPackageId": d.Id(),
}
if v, ok := d.GetOk("force"); ok {
request["Force"] = v
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidBandwidthPackageId.NotFound", "InvalidRegionId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, vpcService.CommonBandwidthPackageStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliyunCommonBandwidthPackageAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunCommonBandwidthPackageAttachmentCreate,
Read: resourceAliyunCommonBandwidthPackageAttachmentRead,
Delete: resourceAliyunCommonBandwidthPackageAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"bandwidth_package_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAliyunCommonBandwidthPackageAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
request := vpc.CreateAddCommonBandwidthPackageIpRequest()
request.RegionId = client.RegionId
request.BandwidthPackageId = Trim(d.Get("bandwidth_package_id").(string))
request.IpInstanceId = Trim(d.Get("instance_id").(string))
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.AddCommonBandwidthPackageIp(request)
})
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.AddCommonBandwidthPackageIp(request)
})
//Waiting for unassociate the common bandwidth package
if err != nil && !IsExpectedErrors(err, []string{"IpInstanceId.AlreadyInBandwidthPackage"}) {
if IsExpectedErrors(err, []string{"TaskConflict"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_common_bandwidth_package_attachment", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
//check the common bandwidth package attachment
d.SetId(request.BandwidthPackageId + COLON_SEPARATED + request.IpInstanceId)
if err := vpcService.WaitForCommonBandwidthPackageAttachment(d.Id(), Available, 5*DefaultTimeout); err != nil {
return WrapError(err)
}
return resourceAliyunCommonBandwidthPackageAttachmentRead(d, meta)
}
func resourceAliyunCommonBandwidthPackageAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
bandwidthPackageId, ipInstanceId := parts[0], parts[1]
_, err = vpcService.DescribeCommonBandwidthPackageAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("bandwidth_package_id", bandwidthPackageId)
d.Set("instance_id", ipInstanceId)
return nil
}
func resourceAliyunCommonBandwidthPackageAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
bandwidthPackageId, ipInstanceId := parts[0], parts[1]
request := vpc.CreateRemoveCommonBandwidthPackageIpRequest()
request.BandwidthPackageId = bandwidthPackageId
request.IpInstanceId = ipInstanceId
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.RemoveCommonBandwidthPackageIp(request)
})
//Waiting for unassociate the common bandwidth package
if err != nil {
if IsExpectedErrors(err, []string{"TaskConflict", "OperationConflict"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"OperationUnsupported.IpNotInCbwp"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(vpcService.WaitForCommonBandwidthPackageAttachment(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudConfigAggregateCompliancePack() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudConfigAggregateCompliancePackCreate,
Read: resourceAlicloudConfigAggregateCompliancePackRead,
Update: resourceAlicloudConfigAggregateCompliancePackUpdate,
Delete: resourceAlicloudConfigAggregateCompliancePackDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"aggregate_compliance_pack_name": {
Type: schema.TypeString,
Required: true,
},
"aggregator_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"compliance_pack_template_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"config_rules": {
Type: schema.TypeSet,
Optional: true,
Deprecated: "Field 'config_rules' has been deprecated from provider version 1.141.0. New field 'config_rule_ids' instead.",
ConflictsWith: []string{"config_rule_ids"},
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"config_rule_parameters": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"parameter_name": {
Type: schema.TypeString,
Optional: true,
},
"parameter_value": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"managed_rule_identifier": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"config_rule_ids": {
Type: schema.TypeSet,
Optional: true,
ConflictsWith: []string{"config_rules"},
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"config_rule_id": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"description": {
Type: schema.TypeString,
Required: true,
},
"risk_level": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3}),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudConfigAggregateCompliancePackCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
configService := ConfigService{client}
var response map[string]interface{}
action := "CreateAggregateCompliancePack"
request := make(map[string]interface{})
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
request["CompliancePackName"] = d.Get("aggregate_compliance_pack_name")
request["AggregatorId"] = d.Get("aggregator_id")
if v, ok := d.GetOk("compliance_pack_template_id"); ok {
request["CompliancePackTemplateId"] = v
}
configRulesMaps := make([]map[string]interface{}, 0)
if _, ok := d.GetOk("config_rules"); ok {
for _, configRules := range d.Get("config_rules").(*schema.Set).List() {
configRulesArg := configRules.(map[string]interface{})
configRulesMap := map[string]interface{}{
"ManagedRuleIdentifier": configRulesArg["managed_rule_identifier"],
}
configRuleParametersMaps := make([]map[string]interface{}, 0)
for _, configRuleParameters := range configRulesArg["config_rule_parameters"].(*schema.Set).List() {
configRuleParametersArg := configRuleParameters.(map[string]interface{})
configRuleParametersMap := map[string]interface{}{
"ParameterName": configRuleParametersArg["parameter_name"],
"ParameterValue": configRuleParametersArg["parameter_value"],
}
configRuleParametersMaps = append(configRuleParametersMaps, configRuleParametersMap)
}
configRulesMap["ConfigRuleParameters"] = configRuleParametersMaps
configRulesMaps = append(configRulesMaps, configRulesMap)
}
} else {
for _, configRuleIds := range d.Get("config_rule_ids").(*schema.Set).List() {
configRulesIdArg := configRuleIds.(map[string]interface{})
configRuleIdMap := map[string]interface{}{
"ConfigRuleId": configRulesIdArg["config_rule_id"],
}
configRulesMaps = append(configRulesMaps, configRuleIdMap)
}
}
if v, err := convertArrayObjectToJsonString(configRulesMaps); err == nil {
request["ConfigRules"] = v
} else {
return WrapError(err)
}
request["Description"] = d.Get("description")
request["RiskLevel"] = d.Get("risk_level")
request["ClientToken"] = buildClientToken("CreateAggregateCompliancePack")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-07"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_config_aggregate_compliance_pack", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["AggregatorId"], ":", response["CompliancePackId"]))
stateConf := BuildStateConf([]string{}, []string{"ACTIVE"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, configService.ConfigAggregateCompliancePackStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudConfigAggregateCompliancePackRead(d, meta)
}
func resourceAlicloudConfigAggregateCompliancePackRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
configService := ConfigService{client}
object, err := configService.DescribeConfigAggregateCompliancePack(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_config_aggregate_compliance_pack configService.DescribeConfigAggregateCompliancePack Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("aggregator_id", parts[0])
d.Set("aggregate_compliance_pack_name", object["CompliancePackName"])
d.Set("compliance_pack_template_id", object["CompliancePackTemplateId"])
if _, ok := d.GetOk("config_rules"); ok {
configRules := make([]map[string]interface{}, 0)
if configRulesList, ok := object["ConfigRules"].([]interface{}); ok {
for _, v := range configRulesList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"managed_rule_identifier": m1["ManagedRuleIdentifier"],
}
if m1["ConfigRuleParameters"] != nil {
configRuleParametersMaps := make([]map[string]interface{}, 0)
for _, configRuleParametersValue := range m1["ConfigRuleParameters"].([]interface{}) {
configRuleParameters := configRuleParametersValue.(map[string]interface{})
configRuleParametersMap := map[string]interface{}{
"parameter_name": configRuleParameters["ParameterName"],
"parameter_value": configRuleParameters["ParameterValue"],
}
configRuleParametersMaps = append(configRuleParametersMaps, configRuleParametersMap)
}
temp1["config_rule_parameters"] = configRuleParametersMaps
}
configRules = append(configRules, temp1)
}
}
}
d.Set("config_rules", configRules)
} else {
configRuleIds := make([]map[string]interface{}, 0)
if configRuleIdsList, ok := object["ConfigRules"].([]interface{}); ok {
for _, v := range configRuleIdsList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"config_rule_id": m1["ConfigRuleId"],
}
configRuleIds = append(configRuleIds, temp1)
}
}
}
d.Set("config_rule_ids", configRuleIds)
}
d.Set("description", object["Description"])
d.Set("risk_level", formatInt(object["RiskLevel"]))
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudConfigAggregateCompliancePackUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
configService := ConfigService{client}
var response map[string]interface{}
d.Partial(true)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"CompliancePackId": parts[1],
"AggregatorId": parts[0],
}
if _, ok := d.GetOk("config_rules"); ok {
configRulesMaps := make([]map[string]interface{}, 0)
if d.HasChange("config_rules") {
update = true
for _, configRules := range d.Get("config_rules").(*schema.Set).List() {
configRulesArg := configRules.(map[string]interface{})
configRulesMap := map[string]interface{}{
"ConfigRuleName": configRulesArg["config_rule_name"],
"ManagedRuleIdentifier": configRulesArg["managed_rule_identifier"],
}
configRuleParametersMaps := make([]map[string]interface{}, 0)
for _, configRuleParameters := range configRulesArg["config_rule_parameters"].(*schema.Set).List() {
configRuleParametersArg := configRuleParameters.(map[string]interface{})
configRuleParametersMap := map[string]interface{}{
"ParameterName": configRuleParametersArg["parameter_name"],
"ParameterValue": configRuleParametersArg["parameter_value"],
}
configRuleParametersMaps = append(configRuleParametersMaps, configRuleParametersMap)
}
configRulesMap["ConfigRuleParameters"] = configRuleParametersMaps
configRulesMaps = append(configRulesMaps, configRulesMap)
}
}
if v, err := convertArrayObjectToJsonString(configRulesMaps); err == nil {
request["ConfigRules"] = v
} else {
return WrapError(err)
}
}
if d.HasChange("description") {
update = true
}
request["Description"] = d.Get("description")
if d.HasChange("risk_level") {
update = true
}
request["RiskLevel"] = d.Get("risk_level")
if d.HasChange("aggregate_compliance_pack_name") {
update = true
}
request["CompliancePackName"] = d.Get("aggregate_compliance_pack_name")
if update {
action := "UpdateAggregateCompliancePack"
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("UpdateAggregateCompliancePack")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-07"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"ACTIVE"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, configService.ConfigAggregateCompliancePackStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("risk_level")
d.SetPartial("description")
d.SetPartial("config_rules")
}
if d.HasChange("config_rule_ids") {
oraw, nraw := d.GetChange("config_rule_ids")
remove := oraw.(*schema.Set).Difference(nraw.(*schema.Set)).List()
create := nraw.(*schema.Set).Difference(oraw.(*schema.Set)).List()
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
if len(remove) > 0 {
removeRulesReq := map[string]interface{}{
"AggregatorId": parts[0],
"CompliancePackId": parts[1],
}
ruleMaps := make([]interface{}, 0)
for _, rule := range remove {
ruleArg := rule.(map[string]interface{})
ruleMaps = append(ruleMaps, ruleArg["config_rule_id"].(string))
}
removeRulesReq["ConfigRuleIds"] = convertListToCommaSeparate(ruleMaps)
action := "DetachAggregateConfigRuleToCompliancePack"
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
removeRulesReq["ClientToken"] = buildClientToken("DetachAggregateConfigRuleToCompliancePack")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-07"), StringPointer("AK"), nil, removeRulesReq, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, removeRulesReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if len(create) > 0 {
addRulesReq := map[string]interface{}{
"AggregatorId": parts[0],
"CompliancePackId": parts[1],
}
ruleMaps := make([]interface{}, 0)
for _, rule := range create {
ruleArg := rule.(map[string]interface{})
ruleMaps = append(ruleMaps, ruleArg["config_rule_id"].(string))
}
addRulesReq["ConfigRuleIds"] = convertListToCommaSeparate(ruleMaps)
action := "AttachAggregateConfigRuleToCompliancePack"
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
addRulesReq["ClientToken"] = buildClientToken("AttachAggregateConfigRuleToCompliancePack")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-07"), StringPointer("AK"), nil, addRulesReq, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, addRulesReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("config_rule_ids")
}
d.Partial(false)
return resourceAlicloudConfigAggregateCompliancePackRead(d, meta)
}
func resourceAlicloudConfigAggregateCompliancePackDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteAggregateCompliancePacks"
var response map[string]interface{}
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"CompliancePackIds": parts[1],
"AggregatorId": parts[0],
}
request["ClientToken"] = buildClientToken("DeleteAggregateCompliancePacks")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-07"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Invalid.AggregatorId.Value", "Invalid.CompliancePackId.Value"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudConfigAggregateConfigRule() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudConfigAggregateConfigRuleCreate,
Read: resourceAlicloudConfigAggregateConfigRuleRead,
Update: resourceAlicloudConfigAggregateConfigRuleUpdate,
Delete: resourceAlicloudConfigAggregateConfigRuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"aggregate_config_rule_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"aggregator_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"config_rule_id": {
Type: schema.TypeString,
Computed: true,
},
"config_rule_trigger_types": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"ConfigurationItemChangeNotification", "ScheduledNotification"}, false),
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"exclude_resource_ids_scope": {
Type: schema.TypeString,
Optional: true,
},
"input_parameters": {
Type: schema.TypeMap,
Optional: true,
},
"maximum_execution_frequency": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"One_Hour", "Six_Hours", "Three_Hours", "Twelve_Hours", "TwentyFour_Hours"}, false),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if fmt.Sprint(d.Get("config_rule_trigger_types")) == "ConfigurationItemChangeNotification" {
return true
}
return false
},
},
"region_ids_scope": {
Type: schema.TypeString,
Optional: true,
},
"resource_group_ids_scope": {
Type: schema.TypeString,
Optional: true,
},
"resource_types_scope": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"risk_level": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3}),
},
"source_identifier": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"source_owner": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ALIYUN", "CUSTOM_FC"}, false),
},
"status": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"ACTIVE", "INACTIVE"}, false),
Computed: true,
},
"tag_key_scope": {
Type: schema.TypeString,
Optional: true,
},
"tag_value_scope": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudConfigAggregateConfigRuleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateAggregateConfigRule"
request := make(map[string]interface{})
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
request["ConfigRuleName"] = d.Get("aggregate_config_rule_name")
request["AggregatorId"] = d.Get("aggregator_id")
request["ConfigRuleTriggerTypes"] = d.Get("config_rule_trigger_types")
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("exclude_resource_ids_scope"); ok {
request["ExcludeResourceIdsScope"] = v
}
if v, ok := d.GetOk("input_parameters"); ok {
if v, err := convertMaptoJsonString(v.(map[string]interface{})); err == nil {
request["InputParameters"] = v
} else {
return WrapError(err)
}
}
if v, ok := d.GetOk("maximum_execution_frequency"); ok {
request["MaximumExecutionFrequency"] = v
}
if v, ok := d.GetOk("region_ids_scope"); ok {
request["RegionIdsScope"] = v
}
if v, ok := d.GetOk("resource_group_ids_scope"); ok {
request["ResourceGroupIdsScope"] = v
}
request["ResourceTypesScope"] = convertListToCommaSeparate(d.Get("resource_types_scope").([]interface{}))
request["RiskLevel"] = d.Get("risk_level")
request["SourceIdentifier"] = d.Get("source_identifier")
request["SourceOwner"] = d.Get("source_owner")
if v, ok := d.GetOk("tag_key_scope"); ok {
request["TagKeyScope"] = v
}
if v, ok := d.GetOk("tag_value_scope"); ok {
request["TagValueScope"] = v
}
request["ClientToken"] = buildClientToken("CreateAggregateConfigRule")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-07"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_config_aggregate_config_rule", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["AggregatorId"], ":", response["ConfigRuleId"]))
return resourceAlicloudConfigAggregateConfigRuleUpdate(d, meta)
}
func resourceAlicloudConfigAggregateConfigRuleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
configService := ConfigService{client}
object, err := configService.DescribeConfigAggregateConfigRule(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_config_aggregate_config_rule configService.DescribeConfigAggregateConfigRule Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("aggregator_id", parts[0])
d.Set("config_rule_id", parts[1])
d.Set("aggregate_config_rule_name", object["ConfigRuleName"])
d.Set("config_rule_trigger_types", object["ConfigRuleTriggerTypes"])
d.Set("description", object["Description"])
d.Set("exclude_resource_ids_scope", object["ExcludeResourceIdsScope"])
d.Set("input_parameters", object["InputParameters"])
d.Set("maximum_execution_frequency", object["MaximumExecutionFrequency"])
d.Set("region_ids_scope", object["RegionIdsScope"])
d.Set("resource_group_ids_scope", object["ResourceGroupIdsScope"])
d.Set("resource_types_scope", object["Scope"].(map[string]interface{})["ComplianceResourceTypes"])
d.Set("risk_level", formatInt(object["RiskLevel"]))
d.Set("source_identifier", object["Source"].(map[string]interface{})["Identifier"])
d.Set("source_owner", object["Source"].(map[string]interface{})["Owner"])
d.Set("status", object["ConfigRuleState"])
d.Set("tag_key_scope", object["TagKeyScope"])
d.Set("tag_value_scope", object["TagValueScope"])
return nil
}
func resourceAlicloudConfigAggregateConfigRuleUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
configService := ConfigService{client}
d.Partial(true)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"AggregatorId": parts[0],
"ConfigRuleId": parts[1],
}
if !d.IsNewResource() && d.HasChange("config_rule_trigger_types") {
update = true
}
request["ConfigRuleTriggerTypes"] = d.Get("config_rule_trigger_types")
if !d.IsNewResource() && d.HasChange("resource_types_scope") {
update = true
}
request["ResourceTypesScope"] = convertListToCommaSeparate(d.Get("resource_types_scope").([]interface{}))
if !d.IsNewResource() && d.HasChange("risk_level") {
update = true
}
request["RiskLevel"] = d.Get("risk_level")
if !d.IsNewResource() && d.HasChange("description") {
update = true
request["Description"] = d.Get("description")
}
if !d.IsNewResource() && d.HasChange("exclude_resource_ids_scope") {
update = true
request["ExcludeResourceIdsScope"] = d.Get("exclude_resource_ids_scope")
}
if !d.IsNewResource() && d.HasChange("input_parameters") {
update = true
if v, err := convertMaptoJsonString(d.Get("input_parameters").(map[string]interface{})); err == nil {
request["InputParameters"] = v
} else {
return WrapError(err)
}
}
if !d.IsNewResource() && d.HasChange("maximum_execution_frequency") {
update = true
request["MaximumExecutionFrequency"] = d.Get("maximum_execution_frequency")
}
if !d.IsNewResource() && d.HasChange("region_ids_scope") {
update = true
request["RegionIdsScope"] = d.Get("region_ids_scope")
}
if !d.IsNewResource() && d.HasChange("resource_group_ids_scope") {
update = true
request["ResourceGroupIdsScope"] = d.Get("resource_group_ids_scope")
}
if !d.IsNewResource() && d.HasChange("tag_key_scope") {
update = true
request["TagKeyScope"] = d.Get("tag_key_scope")
}
if !d.IsNewResource() && d.HasChange("tag_value_scope") {
update = true
request["TagValueScope"] = d.Get("tag_value_scope")
}
if update {
action := "UpdateAggregateConfigRule"
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("UpdateAggregateConfigRule")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-07"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
update = false
if d.HasChange("status") {
update = true
}
if update {
configService := ConfigService{client}
object, err := configService.DescribeConfigAggregateConfigRule(d.Id())
if err != nil {
return WrapError(err)
}
target := d.Get("status").(string)
if value, exist := object["ConfigRuleState"]; exist && value.(string) != target {
if target == "ACTIVE" {
err := configService.ActiveAggregateConfigRules(parts[1], parts[0])
if err != nil {
return WrapError(err)
}
}
if target == "INACTIVE" {
err := configService.DeactiveAggregateConfigRules(parts[1], parts[0])
if err != nil {
return WrapError(err)
}
}
}
d.SetPartial("status")
}
d.Partial(false)
stateConf := BuildStateConf([]string{}, []string{"ACTIVE", "INACTIVE"}, d.Timeout(schema.TimeoutCreate), 10*time.Second, configService.ConfigAggregateConfigRuleStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudConfigAggregateConfigRuleRead(d, meta)
}
func resourceAlicloudConfigAggregateConfigRuleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteAggregateConfigRules"
var response map[string]interface{}
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AggregatorId": parts[0],
"ConfigRuleIds": parts[1],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-07"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ConfigRuleCanNotDelete", "ConfigRuleNotExists", "Invalid.AggregatorId.Value", "Invalid.ConfigRuleId.Value"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudConfigAggregator() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudConfigAggregatorCreate,
Read: resourceAlicloudConfigAggregatorRead,
Update: resourceAlicloudConfigAggregatorUpdate,
Delete: resourceAlicloudConfigAggregatorDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"aggregator_accounts": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_id": {
Type: schema.TypeString,
Required: true,
},
"account_name": {
Type: schema.TypeString,
Required: true,
},
"account_type": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"aggregator_name": {
Type: schema.TypeString,
Required: true,
},
"aggregator_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"CUSTOM", "RD"}, false),
},
"description": {
Type: schema.TypeString,
Required: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudConfigAggregatorCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
configService := ConfigService{client}
var response map[string]interface{}
action := "CreateAggregator"
request := make(map[string]interface{})
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
aggregatorAccountsMaps := make([]map[string]interface{}, 0)
for _, aggregatorAccounts := range d.Get("aggregator_accounts").(*schema.Set).List() {
aggregatorAccountsArg := aggregatorAccounts.(map[string]interface{})
aggregatorAccountsMap := map[string]interface{}{
"AccountId": aggregatorAccountsArg["account_id"],
"AccountName": aggregatorAccountsArg["account_name"],
"AccountType": aggregatorAccountsArg["account_type"],
}
aggregatorAccountsMaps = append(aggregatorAccountsMaps, aggregatorAccountsMap)
}
if v, err := convertArrayObjectToJsonString(aggregatorAccountsMaps); err == nil {
request["AggregatorAccounts"] = v
} else {
return WrapError(err)
}
request["AggregatorName"] = d.Get("aggregator_name")
if v, ok := d.GetOk("aggregator_type"); ok {
request["AggregatorType"] = v
}
request["Description"] = d.Get("description")
request["ClientToken"] = buildClientToken("CreateAggregator")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-07"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_config_aggregator", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["AggregatorId"]))
stateConf := BuildStateConf([]string{}, []string{"1"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, configService.ConfigAggregatorStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudConfigAggregatorRead(d, meta)
}
func resourceAlicloudConfigAggregatorRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
configService := ConfigService{client}
object, err := configService.DescribeConfigAggregator(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_config_aggregator configService.DescribeConfigAggregator Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
aggregatorAccounts := make([]map[string]interface{}, 0)
if aggregatorAccountsList, ok := object["AggregatorAccounts"].([]interface{}); ok {
for _, v := range aggregatorAccountsList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"account_id": fmt.Sprint(m1["AccountId"]),
"account_name": m1["AccountName"],
"account_type": m1["AccountType"],
}
aggregatorAccounts = append(aggregatorAccounts, temp1)
}
}
}
if err := d.Set("aggregator_accounts", aggregatorAccounts); err != nil {
return WrapError(err)
}
d.Set("aggregator_name", object["AggregatorName"])
d.Set("aggregator_type", object["AggregatorType"])
d.Set("description", object["Description"])
d.Set("status", convertConfigAggregatorStatusResponse(formatInt(object["AggregatorStatus"])))
return nil
}
func resourceAlicloudConfigAggregatorUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"AggregatorId": d.Id(),
}
if d.HasChange("aggregator_accounts") {
update = true
}
aggregatorAccountsMaps := make([]map[string]interface{}, 0)
for _, aggregatorAccounts := range d.Get("aggregator_accounts").(*schema.Set).List() {
aggregatorAccountsArg := aggregatorAccounts.(map[string]interface{})
aggregatorAccountsMap := map[string]interface{}{
"AccountId": aggregatorAccountsArg["account_id"],
"AccountName": aggregatorAccountsArg["account_name"],
"AccountType": aggregatorAccountsArg["account_type"],
}
aggregatorAccountsMaps = append(aggregatorAccountsMaps, aggregatorAccountsMap)
}
if v, err := convertArrayObjectToJsonString(aggregatorAccountsMaps); err == nil {
request["AggregatorAccounts"] = v
} else {
return WrapError(err)
}
if d.HasChange("aggregator_name") {
update = true
}
request["AggregatorName"] = d.Get("aggregator_name")
if d.HasChange("description") {
update = true
}
request["Description"] = d.Get("description")
if update {
action := "UpdateAggregator"
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("UpdateAggregator")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-07"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudConfigAggregatorRead(d, meta)
}
func resourceAlicloudConfigAggregatorDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteAggregators"
var response map[string]interface{}
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AggregatorIds": d.Id(),
}
request["ClientToken"] = buildClientToken("DeleteAggregators")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-07"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"AccountNotExisted", "Invalid.AggregatorIds.Empty"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func convertConfigAggregatorStatusResponse(source interface{}) interface{} {
switch source {
case 0:
return "Creating"
case 2:
return "Deleting"
case 1:
return "Normal"
}
return ""
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudConfigCompliancePack() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudConfigCompliancePackCreate,
Read: resourceAlicloudConfigCompliancePackRead,
Update: resourceAlicloudConfigCompliancePackUpdate,
Delete: resourceAlicloudConfigCompliancePackDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(2 * time.Minute),
},
Schema: map[string]*schema.Schema{
"compliance_pack_name": {
Type: schema.TypeString,
Required: true,
},
"compliance_pack_template_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"config_rules": {
Type: schema.TypeSet,
Optional: true,
Deprecated: "Field 'config_rules' has been deprecated from provider version 1.141.0. New field 'config_rule_ids' instead.",
ConflictsWith: []string{"config_rule_ids"},
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"config_rule_parameters": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"parameter_name": {
Type: schema.TypeString,
Optional: true,
},
"parameter_value": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"managed_rule_identifier": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"config_rule_ids": {
Type: schema.TypeSet,
Optional: true,
ConflictsWith: []string{"config_rules"},
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"config_rule_id": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"description": {
Type: schema.TypeString,
Required: true,
},
"risk_level": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3}),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudConfigCompliancePackCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
configService := ConfigService{client}
var response map[string]interface{}
action := "CreateCompliancePack"
request := make(map[string]interface{})
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
request["CompliancePackName"] = d.Get("compliance_pack_name")
if v, ok := d.GetOk("compliance_pack_template_id"); ok {
request["CompliancePackTemplateId"] = v
}
configRulesMaps := make([]map[string]interface{}, 0)
if _, ok := d.GetOk("config_rules"); ok {
for _, configRules := range d.Get("config_rules").(*schema.Set).List() {
configRulesArg := configRules.(map[string]interface{})
configRulesMap := map[string]interface{}{
"ManagedRuleIdentifier": configRulesArg["managed_rule_identifier"],
}
configRuleParametersMaps := make([]map[string]interface{}, 0)
for _, configRuleParameters := range configRulesArg["config_rule_parameters"].(*schema.Set).List() {
configRuleParametersArg := configRuleParameters.(map[string]interface{})
configRuleParametersMap := map[string]interface{}{
"ParameterName": configRuleParametersArg["parameter_name"],
"ParameterValue": configRuleParametersArg["parameter_value"],
}
configRuleParametersMaps = append(configRuleParametersMaps, configRuleParametersMap)
}
configRulesMap["ConfigRuleParameters"] = configRuleParametersMaps
configRulesMaps = append(configRulesMaps, configRulesMap)
}
} else {
for _, configRuleIds := range d.Get("config_rule_ids").(*schema.Set).List() {
configRulesIdArg := configRuleIds.(map[string]interface{})
configRuleIdMap := map[string]interface{}{
"ConfigRuleId": configRulesIdArg["config_rule_id"],
}
configRulesMaps = append(configRulesMaps, configRuleIdMap)
}
}
if v, err := convertArrayObjectToJsonString(configRulesMaps); err == nil {
request["ConfigRules"] = v
} else {
return WrapError(err)
}
request["Description"] = d.Get("description")
request["RiskLevel"] = d.Get("risk_level")
request["ClientToken"] = buildClientToken("CreateCompliancePack")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 30*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-07"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_config_compliance_pack", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["CompliancePackId"]))
stateConf := BuildStateConf([]string{}, []string{"ACTIVE"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, configService.ConfigCompliancePackStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudConfigCompliancePackRead(d, meta)
}
func resourceAlicloudConfigCompliancePackRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
configService := ConfigService{client}
object, err := configService.DescribeConfigCompliancePack(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_config_compliance_pack configService.DescribeConfigCompliancePack Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("compliance_pack_name", object["CompliancePackName"])
d.Set("compliance_pack_template_id", object["CompliancePackTemplateId"])
if _, ok := d.GetOk("config_rules"); ok {
configRules := make([]map[string]interface{}, 0)
if configRulesList, ok := object["ConfigRules"].([]interface{}); ok {
for _, v := range configRulesList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"managed_rule_identifier": m1["ManagedRuleIdentifier"],
}
if m1["ConfigRuleParameters"] != nil {
configRuleParametersMaps := make([]map[string]interface{}, 0)
for _, configRuleParametersValue := range m1["ConfigRuleParameters"].([]interface{}) {
configRuleParameters := configRuleParametersValue.(map[string]interface{})
configRuleParametersMap := map[string]interface{}{
"parameter_name": configRuleParameters["ParameterName"],
"parameter_value": configRuleParameters["ParameterValue"],
}
configRuleParametersMaps = append(configRuleParametersMaps, configRuleParametersMap)
}
temp1["config_rule_parameters"] = configRuleParametersMaps
}
configRules = append(configRules, temp1)
}
}
}
d.Set("config_rules", configRules)
} else {
configRuleIds := make([]map[string]interface{}, 0)
if configRuleIdsList, ok := object["ConfigRules"].([]interface{}); ok {
for _, v := range configRuleIdsList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"config_rule_id": m1["ConfigRuleId"],
}
configRuleIds = append(configRuleIds, temp1)
}
}
}
d.Set("config_rule_ids", configRuleIds)
}
d.Set("description", object["Description"])
d.Set("risk_level", formatInt(object["RiskLevel"]))
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudConfigCompliancePackUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
configService := ConfigService{client}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"CompliancePackId": d.Id(),
}
if _, ok := d.GetOk("config_rules"); ok {
configRulesMaps := make([]map[string]interface{}, 0)
if d.HasChange("config_rules") {
update = true
for _, configRules := range d.Get("config_rules").(*schema.Set).List() {
configRulesArg := configRules.(map[string]interface{})
configRulesMap := map[string]interface{}{
"ConfigRuleName": configRulesArg["config_rule_name"],
"ManagedRuleIdentifier": configRulesArg["managed_rule_identifier"],
}
configRuleParametersMaps := make([]map[string]interface{}, 0)
for _, configRuleParameters := range configRulesArg["config_rule_parameters"].(*schema.Set).List() {
configRuleParametersArg := configRuleParameters.(map[string]interface{})
configRuleParametersMap := map[string]interface{}{
"ParameterName": configRuleParametersArg["parameter_name"],
"ParameterValue": configRuleParametersArg["parameter_value"],
}
configRuleParametersMaps = append(configRuleParametersMaps, configRuleParametersMap)
}
configRulesMap["ConfigRuleParameters"] = configRuleParametersMaps
configRulesMaps = append(configRulesMaps, configRulesMap)
}
}
if v, err := convertArrayObjectToJsonString(configRulesMaps); err == nil {
request["ConfigRules"] = v
} else {
return WrapError(err)
}
}
if d.HasChange("description") {
update = true
}
request["Description"] = d.Get("description")
if d.HasChange("risk_level") {
update = true
}
request["RiskLevel"] = d.Get("risk_level")
if !d.IsNewResource() && d.HasChange("compliance_pack_name") {
update = true
}
request["CompliancePackName"] = d.Get("compliance_pack_name")
if update {
action := "UpdateCompliancePack"
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("UpdateCompliancePack")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 30*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-07"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"CompliancePackAlreadyPending"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"ACTIVE"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, configService.ConfigCompliancePackStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("risk_level")
d.SetPartial("description")
d.SetPartial("config_rules")
}
if d.HasChange("config_rule_ids") {
oraw, nraw := d.GetChange("config_rule_ids")
remove := oraw.(*schema.Set).Difference(nraw.(*schema.Set)).List()
create := nraw.(*schema.Set).Difference(oraw.(*schema.Set)).List()
if len(remove) > 0 {
removeRulesReq := map[string]interface{}{
"CompliancePackId": d.Id(),
}
ruleMaps := make([]interface{}, 0)
for _, rule := range remove {
ruleArg := rule.(map[string]interface{})
ruleMaps = append(ruleMaps, ruleArg["config_rule_id"].(string))
}
removeRulesReq["ConfigRuleIds"] = convertListToCommaSeparate(ruleMaps)
action := "DetachConfigRuleToCompliancePack"
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
removeRulesReq["ClientToken"] = buildClientToken("DetachConfigRuleToCompliancePack")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-07"), StringPointer("AK"), nil, removeRulesReq, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, removeRulesReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if len(create) > 0 {
addRulesReq := map[string]interface{}{
"CompliancePackId": d.Id(),
}
ruleMaps := make([]interface{}, 0)
for _, rule := range create {
ruleArg := rule.(map[string]interface{})
ruleMaps = append(ruleMaps, ruleArg["config_rule_id"].(string))
}
addRulesReq["ConfigRuleIds"] = convertListToCommaSeparate(ruleMaps)
action := "AttachConfigRuleToCompliancePack"
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
addRulesReq["ClientToken"] = buildClientToken("AttachConfigRuleToCompliancePack")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-07"), StringPointer("AK"), nil, addRulesReq, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, addRulesReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("config_rule_ids")
}
d.Partial(false)
return resourceAlicloudConfigCompliancePackRead(d, meta)
}
func resourceAlicloudConfigCompliancePackDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteCompliancePacks"
var response map[string]interface{}
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"CompliancePackIds": d.Id(),
}
request["ClientToken"] = buildClientToken("DeleteCompliancePacks")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-07"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudConfigConfigurationRecorder() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudConfigConfigurationRecorderCreate,
Read: resourceAlicloudConfigConfigurationRecorderRead,
Update: resourceAlicloudConfigConfigurationRecorderUpdate,
Delete: resourceAlicloudConfigConfigurationRecorderDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Update: schema.DefaultTimeout(11 * time.Minute),
},
Schema: map[string]*schema.Schema{
"enterprise_edition": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Computed: true,
},
"organization_enable_status": {
Type: schema.TypeString,
Computed: true,
},
"organization_master_id": {
Type: schema.TypeInt,
Computed: true,
},
"resource_types": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudConfigConfigurationRecorderCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "StartConfigurationRecorder"
request := make(map[string]interface{})
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("enterprise_edition"); ok {
request["EnterpriseEdition"] = v
}
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_config_configuration_recorder", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
response = response["ConfigurationRecorder"].(map[string]interface{})
d.SetId(fmt.Sprint(formatInt(response["AccountId"])))
return resourceAlicloudConfigConfigurationRecorderUpdate(d, meta)
}
func resourceAlicloudConfigConfigurationRecorderRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
configService := ConfigService{client}
object, err := configService.DescribeConfigConfigurationRecorder(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_config_configuration_recorder configService.DescribeConfigConfigurationRecorder Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("organization_enable_status", object["OrganizationEnableStatus"])
d.Set("organization_master_id", formatInt(object["OrganizationMasterId"]))
d.Set("resource_types", object["ResourceTypes"])
d.Set("status", object["ConfigurationRecorderStatus"])
return nil
}
func resourceAlicloudConfigConfigurationRecorderUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
configService := ConfigService{client}
var response map[string]interface{}
update := false
request := make(map[string]interface{})
if !d.IsNewResource() && d.HasChange("resource_types") {
update = true
}
request["ResourceTypes"] = convertListToCommaSeparate(d.Get("resource_types").(*schema.Set).List())
if update {
action := "PutConfigurationRecorder"
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"REGISTERED"}, d.Timeout(schema.TimeoutUpdate), 10*time.Second, configService.ConfigConfigurationRecorderStateRefreshFunc(d.Id(), []string{"REGISTRABLE"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudConfigConfigurationRecorderRead(d, meta)
}
func resourceAlicloudConfigConfigurationRecorderDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudConfigConfigurationRecorder. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudConfigDeliveryChannel() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudConfigDeliveryChannelCreate,
Read: resourceAlicloudConfigDeliveryChannelRead,
Update: resourceAlicloudConfigDeliveryChannelUpdate,
Delete: resourceAlicloudConfigDeliveryChannelDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(3 * time.Minute),
Update: schema.DefaultTimeout(3 * time.Minute),
},
Schema: map[string]*schema.Schema{
"delivery_channel_assume_role_arn": {
Type: schema.TypeString,
Required: true,
},
"delivery_channel_condition": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"delivery_channel_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"delivery_channel_target_arn": {
Type: schema.TypeString,
Required: true,
},
"delivery_channel_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"MNS", "OSS", "SLS"}, false),
},
"description": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"status": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntInSlice([]int{0, 1}),
},
},
}
}
func resourceAlicloudConfigDeliveryChannelCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "PutDeliveryChannel"
request := make(map[string]interface{})
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
request["DeliveryChannelAssumeRoleArn"] = d.Get("delivery_channel_assume_role_arn")
if v, ok := d.GetOk("delivery_channel_condition"); ok {
request["DeliveryChannelCondition"] = v
}
if v, ok := d.GetOk("delivery_channel_name"); ok {
request["DeliveryChannelName"] = v
}
request["DeliveryChannelTargetArn"] = d.Get("delivery_channel_target_arn")
request["DeliveryChannelType"] = d.Get("delivery_channel_type")
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"DeliveryChannelSlsUnreachableError"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
d.SetId(fmt.Sprint(response["DeliveryChannelId"]))
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_config_delivery_channel", action, AlibabaCloudSdkGoERROR)
}
return resourceAlicloudConfigDeliveryChannelRead(d, meta)
}
func resourceAlicloudConfigDeliveryChannelRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
configService := ConfigService{client}
object, err := configService.DescribeConfigDeliveryChannel(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_config_delivery_channel configService.DescribeConfigDeliveryChannel Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("delivery_channel_assume_role_arn", object["DeliveryChannelAssumeRoleArn"])
d.Set("delivery_channel_condition", object["DeliveryChannelCondition"])
d.Set("delivery_channel_name", object["DeliveryChannelName"])
d.Set("delivery_channel_target_arn", object["DeliveryChannelTargetArn"])
d.Set("delivery_channel_type", object["DeliveryChannelType"])
d.Set("description", object["Description"])
d.Set("status", formatInt(object["Status"]))
return nil
}
func resourceAlicloudConfigDeliveryChannelUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"DeliveryChannelId": d.Id(),
}
if d.HasChange("delivery_channel_assume_role_arn") {
update = true
}
request["DeliveryChannelAssumeRoleArn"] = d.Get("delivery_channel_assume_role_arn")
if d.HasChange("delivery_channel_target_arn") {
update = true
}
request["DeliveryChannelTargetArn"] = d.Get("delivery_channel_target_arn")
request["DeliveryChannelType"] = d.Get("delivery_channel_type")
if d.HasChange("delivery_channel_condition") {
update = true
request["DeliveryChannelCondition"] = d.Get("delivery_channel_condition")
}
if d.HasChange("delivery_channel_name") {
update = true
request["DeliveryChannelName"] = d.Get("delivery_channel_name")
}
if d.HasChange("description") {
update = true
request["Description"] = d.Get("description")
}
if d.HasChange("status") {
update = true
request["Status"] = d.Get("status")
}
if update {
action := "PutDeliveryChannel"
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"DeliveryChannelSlsUnreachableError"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudConfigDeliveryChannelRead(d, meta)
}
func resourceAlicloudConfigDeliveryChannelDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudConfigDeliveryChannel. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudConfigRule() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudConfigRuleCreate,
Read: resourceAlicloudConfigRuleRead,
Update: resourceAlicloudConfigRuleUpdate,
Delete: resourceAlicloudConfigRuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"member_id": {
Type: schema.TypeInt,
Optional: true,
Removed: "Field 'member_id' has been removed from provider version 1.124.1.",
},
"multi_account": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Removed: "Field 'multi_account' has been removed from provider version 1.124.1.",
},
"scope_compliance_resource_id": {
Type: schema.TypeString,
Optional: true,
Removed: "Field 'scope_compliance_resource_id' has been removed from provider version 1.124.1.",
},
"config_rule_trigger_types": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"source_detail_message_type"},
},
"source_detail_message_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Field 'source_detail_message_type' has been deprecated from provider version 1.124.1. New field 'config_rule_trigger_types' instead.",
ConflictsWith: []string{"config_rule_trigger_types"},
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"exclude_resource_ids_scope": {
Type: schema.TypeString,
Optional: true,
},
"input_parameters": {
Type: schema.TypeMap,
Optional: true,
},
"maximum_execution_frequency": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"One_Hour", "Six_Hours", "Three_Hours", "Twelve_Hours", "TwentyFour_Hours"}, false),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if fmt.Sprint(d.Get("config_rule_trigger_types")) == "ConfigurationItemChangeNotification" || fmt.Sprint(d.Get("source_detail_message_type")) == "ConfigurationItemChangeNotification" {
return true
}
return false
},
ConflictsWith: []string{"source_maximum_execution_frequency"},
},
"source_maximum_execution_frequency": {
Type: schema.TypeString,
Optional: true,
Computed: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if fmt.Sprint(d.Get("config_rule_trigger_types")) == "ConfigurationItemChangeNotification" || fmt.Sprint(d.Get("source_detail_message_type")) == "ConfigurationItemChangeNotification" {
return true
}
return false
},
ValidateFunc: validation.StringInSlice([]string{"One_Hour", "Six_Hours", "Three_Hours", "Twelve_Hours", "TwentyFour_Hours"}, false),
Deprecated: "Field 'source_maximum_execution_frequency' has been deprecated from provider version 1.124.1. New field 'maximum_execution_frequency' instead.",
ConflictsWith: []string{"maximum_execution_frequency"},
},
"region_ids_scope": {
Type: schema.TypeString,
Optional: true,
},
"resource_group_ids_scope": {
Type: schema.TypeString,
Optional: true,
},
"resource_types_scope": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
ConflictsWith: []string{"scope_compliance_resource_types"},
},
"scope_compliance_resource_types": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
Deprecated: "Field 'scope_compliance_resource_types' has been deprecated from provider version 1.124.1. New field 'resource_types_scope' instead.",
ConflictsWith: []string{"resource_types_scope"},
},
"risk_level": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3}),
},
"rule_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"source_identifier": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"source_owner": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ALIYUN", "CUSTOM_FC"}, false),
},
"status": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"ACTIVE", "INACTIVE"}, false),
Computed: true,
},
"tag_key_scope": {
Type: schema.TypeString,
Optional: true,
},
"tag_value_scope": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudConfigRuleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateConfigRule"
request := make(map[string]interface{})
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("config_rule_trigger_types"); ok {
request["ConfigRuleTriggerTypes"] = v
} else if v, ok := d.GetOk("source_detail_message_type"); ok {
request["ConfigRuleTriggerTypes"] = v
} else {
return WrapError(Error("[ERROR] Argument 'source_detail_message_type' or 'config_rule_trigger_types' must be set one!"))
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("exclude_resource_ids_scope"); ok {
request["ExcludeResourceIdsScope"] = v
}
if v, ok := d.GetOk("input_parameters"); ok {
if v, err := convertMaptoJsonString(v.(map[string]interface{})); err == nil {
request["InputParameters"] = v
} else {
return WrapError(err)
}
}
if v, ok := d.GetOk("maximum_execution_frequency"); ok {
request["MaximumExecutionFrequency"] = v
} else if v, ok := d.GetOk("source_maximum_execution_frequency"); ok {
request["MaximumExecutionFrequency"] = v
}
if v, ok := d.GetOk("region_ids_scope"); ok {
request["RegionIdsScope"] = v
}
if v, ok := d.GetOk("resource_group_ids_scope"); ok {
request["ResourceGroupIdsScope"] = v
}
if v, ok := d.GetOk("resource_types_scope"); ok && v != nil {
request["ResourceTypesScope"] = convertListToCommaSeparate(v.([]interface{}))
} else if v, ok := d.GetOk("scope_compliance_resource_types"); ok && v != nil {
request["ResourceTypesScope"] = convertListToCommaSeparate(v.([]interface{}))
} else {
return WrapError(Error("[ERROR] Argument 'scope_compliance_resource_types' or 'resource_types_scope' must be set one!"))
}
request["RiskLevel"] = d.Get("risk_level")
request["ConfigRuleName"] = d.Get("rule_name")
request["SourceIdentifier"] = d.Get("source_identifier")
request["SourceOwner"] = d.Get("source_owner")
if v, ok := d.GetOk("tag_key_scope"); ok {
request["TagKeyScope"] = v
}
if v, ok := d.GetOk("tag_value_scope"); ok {
request["TagValueScope"] = v
}
request["ClientToken"] = buildClientToken("CreateConfigRule")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-07"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_config_rule", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["ConfigRuleId"]))
return resourceAlicloudConfigRuleUpdate(d, meta)
}
func resourceAlicloudConfigRuleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
configService := ConfigService{client}
object, err := configService.DescribeConfigRule(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_config_rule configService.DescribeConfigRule Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", object["Description"])
d.Set("exclude_resource_ids_scope", object["ExcludeResourceIdsScope"])
d.Set("input_parameters", object["InputParameters"])
d.Set("maximum_execution_frequency", object["MaximumExecutionFrequency"])
d.Set("source_maximum_execution_frequency", object["MaximumExecutionFrequency"])
d.Set("region_ids_scope", object["RegionIdsScope"])
d.Set("resource_group_ids_scope", object["ResourceGroupIdsScope"])
d.Set("resource_types_scope", object["Scope"].(map[string]interface{})["ComplianceResourceTypes"])
d.Set("scope_compliance_resource_types", object["Scope"].(map[string]interface{})["ComplianceResourceTypes"])
d.Set("risk_level", formatInt(object["RiskLevel"]))
d.Set("rule_name", object["ConfigRuleName"])
d.Set("source_identifier", object["Source"].(map[string]interface{})["Identifier"])
d.Set("source_owner", object["Source"].(map[string]interface{})["Owner"])
d.Set("status", object["ConfigRuleState"])
d.Set("tag_key_scope", object["TagKeyScope"])
d.Set("tag_value_scope", object["TagValueScope"])
if v := object["Source"].(map[string]interface{})["SourceDetails"].([]interface{}); len(v) > 0 {
d.Set("config_rule_trigger_types", v[0].(map[string]interface{})["MessageType"])
d.Set("source_detail_message_type", v[0].(map[string]interface{})["MessageType"])
}
return nil
}
func resourceAlicloudConfigRuleUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
configService := ConfigService{client}
d.Partial(true)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"ConfigRuleId": d.Id(),
}
if !d.IsNewResource() && (d.HasChange("config_rule_trigger_types") || d.HasChange("source_detail_message_type")) {
update = true
}
if !d.IsNewResource() && (d.HasChange("config_rule_trigger_types") || d.HasChange("source_detail_message_type")) {
update = true
}
if _, ok := d.GetOk("config_rule_trigger_types"); ok {
request["ConfigRuleTriggerTypes"] = d.Get("config_rule_trigger_types")
} else {
request["ConfigRuleTriggerTypes"] = d.Get("source_detail_message_type")
}
if !d.IsNewResource() && (d.HasChange("resource_types_scope") || d.HasChange("scope_compliance_resource_types")) {
update = true
}
if _, ok := d.GetOk("resource_types_scope"); ok {
request["ResourceTypesScope"] = convertListToCommaSeparate(d.Get("resource_types_scope").([]interface{}))
} else {
request["ResourceTypesScope"] = convertListToCommaSeparate(d.Get("scope_compliance_resource_types").([]interface{}))
}
if !d.IsNewResource() && d.HasChange("risk_level") {
update = true
}
request["RiskLevel"] = d.Get("risk_level")
if !d.IsNewResource() && d.HasChange("description") {
update = true
request["Description"] = d.Get("description")
}
if !d.IsNewResource() && d.HasChange("exclude_resource_ids_scope") {
update = true
request["ExcludeResourceIdsScope"] = d.Get("exclude_resource_ids_scope")
}
if !d.IsNewResource() && d.HasChange("input_parameters") {
update = true
if v, err := convertMaptoJsonString(d.Get("input_parameters").(map[string]interface{})); err == nil {
request["InputParameters"] = v
} else {
return WrapError(err)
}
}
if !d.IsNewResource() && d.HasChange("maximum_execution_frequency") || d.HasChange("source_maximum_execution_frequency") {
update = true
if _, ok := d.GetOk("maximum_execution_frequency"); ok {
request["MaximumExecutionFrequency"] = d.Get("maximum_execution_frequency")
} else {
request["MaximumExecutionFrequency"] = d.Get("source_maximum_execution_frequency")
}
}
if !d.IsNewResource() && d.HasChange("region_ids_scope") {
update = true
request["RegionIdsScope"] = d.Get("region_ids_scope")
}
if !d.IsNewResource() && d.HasChange("resource_group_ids_scope") {
update = true
request["ResourceGroupIdsScope"] = d.Get("resource_group_ids_scope")
}
if !d.IsNewResource() && d.HasChange("tag_key_scope") {
update = true
request["TagKeyScope"] = d.Get("tag_key_scope")
}
if !d.IsNewResource() && d.HasChange("tag_value_scope") {
update = true
request["TagValueScope"] = d.Get("tag_value_scope")
}
if update {
action := "UpdateConfigRule"
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("UpdateConfigRule")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-07"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"ACTIVE"}, d.Timeout(schema.TimeoutUpdate), 10*time.Second, configService.ConfigRuleStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
update = false
if d.HasChange("status") {
update = true
}
if update {
configService := ConfigService{client}
object, err := configService.DescribeConfigRule(d.Id())
if err != nil {
return WrapError(err)
}
target := d.Get("status").(string)
if value, exist := object["ConfigRuleState"]; exist && value.(string) != target {
if target == "ACTIVE" {
err := configService.ActiveConfigRule(d.Id())
if err != nil {
return WrapError(err)
}
}
if target == "INACTIVE" {
err := configService.StopConfigRule(d.Id())
if err != nil {
return WrapError(err)
}
}
}
d.SetPartial("status")
}
d.Partial(false)
stateConf := BuildStateConf([]string{}, []string{"ACTIVE", "INACTIVE"}, d.Timeout(schema.TimeoutCreate), 10*time.Second, configService.ConfigRuleStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudConfigRuleRead(d, meta)
}
func resourceAlicloudConfigRuleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteConfigRules"
var response map[string]interface{}
conn, err := client.NewConfigClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ConfigRuleIds": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"AccountNotExisted", "ConfigRuleNotExists"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCrChartNamespace() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCrChartNamespaceCreate,
Read: resourceAlicloudCrChartNamespaceRead,
Update: resourceAlicloudCrChartNamespaceUpdate,
Delete: resourceAlicloudCrChartNamespaceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"auto_create_repo": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"default_repo_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"PRIVATE", "PUBLIC"}, false),
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"namespace_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudCrChartNamespaceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateChartNamespace"
request := make(map[string]interface{})
conn, err := client.NewAcrClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("auto_create_repo"); ok {
request["AutoCreateRepo"] = v
}
if v, ok := d.GetOk("default_repo_type"); ok {
request["DefaultRepoType"] = v
}
request["InstanceId"] = d.Get("instance_id")
request["NamespaceName"] = d.Get("namespace_name")
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cr_chart_namespace", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["InstanceId"], ":", request["NamespaceName"]))
return resourceAlicloudCrChartNamespaceRead(d, meta)
}
func resourceAlicloudCrChartNamespaceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
crService := CrService{client}
object, err := crService.DescribeCrChartNamespace(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cr_chart_namespace crService.DescribeCrChartNamespace Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("instance_id", parts[0])
d.Set("namespace_name", parts[1])
d.Set("auto_create_repo", object["AutoCreateRepo"])
d.Set("default_repo_type", object["DefaultRepoType"])
return nil
}
func resourceAlicloudCrChartNamespaceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewAcrClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"InstanceId": parts[0],
"NamespaceName": parts[1],
}
request["RegionId"] = client.RegionId
if d.HasChange("auto_create_repo") {
update = true
if v, ok := d.GetOkExists("auto_create_repo"); ok {
request["AutoCreateRepo"] = v
}
}
if d.HasChange("default_repo_type") {
update = true
if v, ok := d.GetOk("default_repo_type"); ok {
request["DefaultRepoType"] = v
}
}
if update {
action := "UpdateChartNamespace"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudCrChartNamespaceRead(d, meta)
}
func resourceAlicloudCrChartNamespaceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteChartNamespace"
var response map[string]interface{}
conn, err := client.NewAcrClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"InstanceId": parts[0],
"NamespaceName": parts[1],
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCrChartRepository() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCrChartRepositoryCreate,
Read: resourceAlicloudCrChartRepositoryRead,
Update: resourceAlicloudCrChartRepositoryUpdate,
Delete: resourceAlicloudCrChartRepositoryDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"repo_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"repo_namespace_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"repo_type": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"PRIVATE", "PUBLIC"}, false),
},
"summary": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudCrChartRepositoryCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateChartRepository"
request := make(map[string]interface{})
conn, err := client.NewAcrClient()
if err != nil {
return WrapError(err)
}
request["InstanceId"] = d.Get("instance_id")
request["RepoName"] = d.Get("repo_name")
request["RepoNamespaceName"] = d.Get("repo_namespace_name")
if v, ok := d.GetOk("repo_type"); ok {
request["RepoType"] = v
}
if v, ok := d.GetOk("summary"); ok {
request["Summary"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cr_chart_repository", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["InstanceId"], ":", request["RepoNamespaceName"], ":", request["RepoName"]))
return resourceAlicloudCrChartRepositoryRead(d, meta)
}
func resourceAlicloudCrChartRepositoryRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
crService := CrService{client}
object, err := crService.DescribeCrChartRepository(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cr_chart_repository crService.DescribeCrChartRepository Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
d.Set("repo_name", parts[2])
d.Set("repo_namespace_name", parts[1])
d.Set("instance_id", parts[0])
d.Set("repo_type", object["RepoType"])
d.Set("summary", object["Summary"])
return nil
}
func resourceAlicloudCrChartRepositoryUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewAcrClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"RepoName": parts[2],
"RepoNamespaceName": parts[1],
"InstanceId": parts[0],
}
if d.HasChange("repo_type") {
update = true
}
if v, ok := d.GetOk("repo_type"); ok {
request["RepoType"] = v
}
if d.HasChange("summary") {
update = true
if v, ok := d.GetOk("summary"); ok {
request["Summary"] = v
}
}
if update {
action := "UpdateChartRepository"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudCrChartRepositoryRead(d, meta)
}
func resourceAlicloudCrChartRepositoryDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
action := "DeleteChartRepository"
var response map[string]interface{}
conn, err := client.NewAcrClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"RepoName": parts[2],
"RepoNamespaceName": parts[1],
"InstanceId": parts[0],
}
request["InstanceId"] = d.Get("instance_id")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cr_ee"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/bssopenapi"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCrEEInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCrEEInstanceCreate,
Read: resourceAlicloudCrEEInstanceRead,
Update: resourceAlicloudCrEEInstanceUpdate,
Delete: resourceAlicloudCrEEInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"payment_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Subscription"}, false),
Default: "Subscription",
},
"period": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 6, 12, 24, 36, 48, 60}),
Default: 12,
},
"renew_period": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Default: 0,
},
"renewal_status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"AutoRenewal", "ManualRenewal"}, false),
Default: "ManualRenewal",
},
"instance_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Basic", "Standard", "Advanced"}, false),
},
"instance_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"custom_oss_bucket": {
Type: schema.TypeString,
Optional: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"created_time": {
Type: schema.TypeString,
Computed: true,
},
"end_time": {
Type: schema.TypeString,
Computed: true,
},
"password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"kms_encrypted_password": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: kmsDiffSuppressFunc,
},
"kms_encryption_context": {
Type: schema.TypeMap,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("kms_encrypted_password").(string) == ""
},
Elem: schema.TypeString,
},
},
}
}
func resourceAlicloudCrEEInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := bssopenapi.CreateCreateInstanceRequest()
request.Scheme = "https"
request.RegionId = "cn-hangzhou"
request.ProductCode = "acr"
request.ProductType = "acr_ee_public_cn"
request.SubscriptionType = d.Get("payment_type").(string)
request.Period = requests.NewInteger(d.Get("period").(int))
if v, ok := d.GetOk("renew_period"); ok {
request.RenewPeriod = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("renewal_status"); ok {
request.RenewalStatus = v.(string)
}
parameters := []bssopenapi.CreateInstanceParameter{
{
Code: "InstanceType",
Value: d.Get("instance_type").(string),
},
{
Code: "InstanceName",
Value: d.Get("instance_name").(string),
},
{
Code: "Region",
Value: client.RegionId,
},
}
if v, ok := d.GetOk("custom_oss_bucket"); ok {
parameters = append(parameters, bssopenapi.CreateInstanceParameter{
Code: "DefaultOssBucket",
Value: "false",
})
parameters = append(parameters, bssopenapi.CreateInstanceParameter{
Code: "InstanceStorageName",
Value: v.(string),
})
} else {
parameters = append(parameters, bssopenapi.CreateInstanceParameter{
Code: "DefaultOssBucket",
Value: "true",
})
}
request.Parameter = ¶meters
raw, err := client.WithBssopenapiClient(func(bssopenapiClient *bssopenapi.Client) (interface{}, error) {
resp, errCreate := bssopenapiClient.CreateInstance(request)
if errCreate != nil {
// if account site is international, should route to ap-southeast-1
if serverErr, ok := errCreate.(*errors.ServerError); ok && serverErr.ErrorCode() == "NotApplicable" {
request.RegionId = "ap-southeast-1"
request.Domain = "business.ap-southeast-1.aliyuncs.com"
request.ProductType = "acr_ee_public_intl"
resp, errCreate = bssopenapiClient.CreateInstance(request)
}
}
return resp, errCreate
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cr_ee_instance", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ := raw.(*bssopenapi.CreateInstanceResponse)
if !response.Success {
return WrapErrorf(fmt.Errorf("%v", response), DefaultErrorMsg, "alicloud_cr_ee_instance", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprintf("%v", response.Data.InstanceId))
crService := &CrService{client}
stateConf := BuildStateConf([]string{"PENDING", "STARTING"}, []string{"RUNNING"}, d.Timeout(schema.TimeoutCreate), 15*time.Second, crService.InstanceStatusRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudCrEEInstanceUpdate(d, meta)
}
func resourceAlicloudCrEEInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
crService := &CrService{client}
resp, err := crService.DescribeCrEEInstance(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cr_ee_instance crService.DescribeCrEEInstance Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_name", resp.InstanceName)
d.Set("instance_type", strings.TrimPrefix(resp.InstanceSpecification, "Enterprise_"))
d.Set("status", resp.InstanceStatus)
request := bssopenapi.CreateQueryAvailableInstancesRequest()
request.Scheme = "https"
request.RegionId = "cn-hangzhou"
request.ProductCode = "acr"
request.ProductType = "acr_ee_public_cn"
request.InstanceIDs = resp.InstanceId
raw, err := client.WithBssopenapiClient(func(bssopenapiClient *bssopenapi.Client) (interface{}, error) {
resp, errQuery := bssopenapiClient.QueryAvailableInstances(request)
regionRedirect := false
if serverErr, ok := errQuery.(*errors.ServerError); ok && serverErr.ErrorCode() == "NotApplicable" {
regionRedirect = true
} else if !resp.Success && strings.Contains(resp.Message, "code=40001") {
regionRedirect = true
}
if regionRedirect {
// if account site is international, should route to ap-southeast-1
request.RegionId = "ap-southeast-1"
request.Domain = "business.ap-southeast-1.aliyuncs.com"
request.ProductType = "acr_ee_public_intl"
resp, errQuery = bssopenapiClient.QueryAvailableInstances(request)
}
return resp, errQuery
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cr_ee_instance", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ := raw.(*bssopenapi.QueryAvailableInstancesResponse)
if !response.Success {
return WrapErrorf(fmt.Errorf("%v", response), DefaultErrorMsg, "alicloud_cr_ee_instance", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
instance := response.Data.InstanceList[0]
d.Set("payment_type", instance.SubscriptionType)
d.Set("renewal_status", instance.RenewStatus)
if instance.RenewalDurationUnit == "M" {
d.Set("renew_period", instance.RenewalDuration)
} else {
d.Set("renew_period", instance.RenewalDuration*12)
}
d.Set("created_time", instance.CreateTime)
d.Set("end_time", instance.EndTime)
return nil
}
func resourceAlicloudCrEEInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
response := &cr_ee.ResetLoginPasswordResponse{}
request := cr_ee.CreateResetLoginPasswordRequest()
request.InstanceId = d.Id()
action := request.GetActionName()
if d.HasChanges("password", "kms_encrypted_password") {
password := d.Get("password").(string)
kmsPassword := d.Get("kms_encrypted_password").(string)
if password == "" && kmsPassword == "" {
return WrapError(Error("One of the 'password' and 'kms_encrypted_password' should be set."))
}
if password != "" {
request.Password = password
} else {
kmsService := KmsService{meta.(*connectivity.AliyunClient)}
decryptResp, err := kmsService.Decrypt(kmsPassword, d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request.Password = decryptResp
}
raw, err := client.WithCrEEClient(func(creeClient *cr_ee.Client) (interface{}, error) {
return creeClient.ResetLoginPassword(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
response, _ = raw.(*cr_ee.ResetLoginPasswordResponse)
if !response.ResetLoginPasswordIsSuccess {
return WrapErrorf(fmt.Errorf(response.Code), DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudCrEEInstanceRead(d, meta)
}
func resourceAlicloudCrEEInstanceDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudCrEEInstance. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
package alicloud
import (
"fmt"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cr_ee"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCrEENamespace() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCrEENamespaceCreate,
Read: resourceAlicloudCrEENamespaceRead,
Update: resourceAlicloudCrEENamespaceUpdate,
Delete: resourceAlicloudCrEENamespaceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(2, 30),
},
"auto_create": {
Type: schema.TypeBool,
Required: true,
},
"default_visibility": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{RepoTypePublic, RepoTypePrivate}, false),
},
},
}
}
func resourceAlicloudCrEENamespaceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
crService := &CrService{client}
instanceId := d.Get("instance_id").(string)
namespace := d.Get("name").(string)
autoCreate := d.Get("auto_create").(bool)
visibility := d.Get("default_visibility").(string)
response := &cr_ee.CreateNamespaceResponse{}
request := cr_ee.CreateCreateNamespaceRequest()
request.RegionId = crService.client.RegionId
request.InstanceId = instanceId
request.NamespaceName = namespace
request.AutoCreateRepo = requests.NewBoolean(autoCreate)
request.DefaultRepoType = visibility
action := request.GetActionName()
raw, err := crService.client.WithCrEEClient(func(creeClient *cr_ee.Client) (interface{}, error) {
return creeClient.CreateNamespace(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cr_ee_namespace", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, raw, request.RpcRequest, request)
response, _ = raw.(*cr_ee.CreateNamespaceResponse)
if !response.CreateNamespaceIsSuccess {
return WrapErrorf(fmt.Errorf("%v", response), DefaultErrorMsg, "alicloud_cr_ee_namespace", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(instanceId, ":", namespace))
return resourceAlicloudCrEENamespaceRead(d, meta)
}
func resourceAlicloudCrEENamespaceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
crService := &CrService{client}
resp, err := crService.DescribeCrEENamespace(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_id", resp.InstanceId)
d.Set("name", resp.NamespaceName)
d.Set("auto_create", resp.AutoCreateRepo)
d.Set("default_visibility", resp.DefaultRepoType)
return nil
}
func resourceAlicloudCrEENamespaceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
crService := &CrService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
if d.HasChanges("auto_create", "default_visibility") {
autoCreate := d.Get("auto_create").(bool)
visibility := d.Get("default_visibility").(string)
response := &cr_ee.UpdateNamespaceResponse{}
request := cr_ee.CreateUpdateNamespaceRequest()
request.RegionId = crService.client.RegionId
request.InstanceId = parts[0]
request.NamespaceName = parts[1]
request.AutoCreateRepo = requests.NewBoolean(autoCreate)
request.DefaultRepoType = visibility
action := request.GetActionName()
raw, err := crService.client.WithCrEEClient(func(creeClient *cr_ee.Client) (interface{}, error) {
return creeClient.UpdateNamespace(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, raw, request.RpcRequest, request)
response, _ = raw.(*cr_ee.UpdateNamespaceResponse)
if !response.UpdateNamespaceIsSuccess {
return WrapErrorf(fmt.Errorf("%v", response), DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudCrEENamespaceRead(d, meta)
}
func resourceAlicloudCrEENamespaceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
crService := &CrService{client}
_, err := crService.DeleteCrEENamespace(d.Id())
if err != nil {
if NotFoundError(err) {
return nil
} else {
return WrapError(err)
}
}
return WrapError(crService.WaitForCrEENamespace(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"fmt"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cr_ee"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCrEERepo() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCrEERepoCreate,
Read: resourceAlicloudCrEERepoRead,
Update: resourceAlicloudCrEERepoUpdate,
Delete: resourceAlicloudCrEERepoDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"namespace": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(2, 30),
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(2, 64),
},
"summary": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(1, 100),
},
"repo_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{RepoTypePublic, RepoTypePrivate}, false),
},
"detail": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(0, 2000),
},
//Computed
"repo_id": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudCrEERepoCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
crService := &CrService{client}
instanceId := d.Get("instance_id").(string)
namespace := d.Get("namespace").(string)
repoName := d.Get("name").(string)
repoType := d.Get("repo_type").(string)
summary := d.Get("summary").(string)
response := &cr_ee.CreateRepositoryResponse{}
request := cr_ee.CreateCreateRepositoryRequest()
request.RegionId = crService.client.RegionId
request.InstanceId = instanceId
request.RepoNamespaceName = namespace
request.RepoName = repoName
request.RepoType = repoType
request.Summary = summary
if detail, ok := d.GetOk("detail"); ok && detail.(string) != "" {
request.Detail = detail.(string)
}
action := request.GetActionName()
raw, err := crService.client.WithCrEEClient(func(creeClient *cr_ee.Client) (interface{}, error) {
return creeClient.CreateRepository(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cr_ee_repo", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, raw, request.RpcRequest, request)
response, _ = raw.(*cr_ee.CreateRepositoryResponse)
if !response.CreateRepositoryIsSuccess {
return WrapErrorf(fmt.Errorf("%v", response), DefaultErrorMsg, "alicloud_cr_ee_repo", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(instanceId, ":", namespace, ":", repoName))
return resourceAlicloudCrEERepoRead(d, meta)
}
func resourceAlicloudCrEERepoRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
crService := &CrService{client}
resp, err := crService.DescribeCrEERepo(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_id", resp.InstanceId)
d.Set("namespace", resp.RepoNamespaceName)
d.Set("name", resp.RepoName)
d.Set("repo_type", resp.RepoType)
d.Set("summary", resp.Summary)
d.Set("detail", resp.Detail)
d.Set("repo_id", resp.RepoId)
return nil
}
func resourceAlicloudCrEERepoUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
crService := &CrService{client}
if d.HasChanges("repo_type", "summary", "detail") {
response := &cr_ee.UpdateRepositoryResponse{}
request := cr_ee.CreateUpdateRepositoryRequest()
request.RegionId = crService.client.RegionId
request.InstanceId = d.Get("instance_id").(string)
request.RepoId = d.Get("repo_id").(string)
request.RepoType = d.Get("repo_type").(string)
request.Summary = d.Get("summary").(string)
if d.HasChange("detail") {
request.Detail = d.Get("detail").(string)
}
action := request.GetActionName()
raw, err := crService.client.WithCrEEClient(func(creeClient *cr_ee.Client) (interface{}, error) {
return creeClient.UpdateRepository(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, raw, request.RpcRequest, request)
response, _ = raw.(*cr_ee.UpdateRepositoryResponse)
if !response.UpdateRepositoryIsSuccess {
return WrapErrorf(fmt.Errorf("%v", response), DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudCrEERepoRead(d, meta)
}
func resourceAlicloudCrEERepoDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
crService := &CrService{client}
repoId := d.Get("repo_id").(string)
_, err := crService.DeleteCrEERepo(d.Id(), repoId)
if err != nil {
if NotFoundError(err) {
return nil
} else {
return WrapError(err)
}
}
return WrapError(crService.WaitForCrEERepo(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"fmt"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cr_ee"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCrEESyncRule() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCrEESyncRuleCreate,
Read: resourceAlicloudCrEESyncRuleRead,
Delete: resourceAlicloudCrEESyncRuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"namespace_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(2, 30),
},
"repo_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(2, 64),
},
"target_region_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"target_instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"target_namespace_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(2, 30),
},
"target_repo_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(2, 64),
},
"tag_filter": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"rule_id": {
Type: schema.TypeString,
Computed: true,
ForceNew: true,
},
"sync_direction": {
Type: schema.TypeString,
Computed: true,
},
"sync_scope": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudCrEESyncRuleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
crService := &CrService{client}
syncRuleName := d.Get("name").(string)
instanceId := d.Get("instance_id").(string)
namespaceName := d.Get("namespace_name").(string)
targetRegionId := d.Get("target_region_id").(string)
targetInstanceId := d.Get("target_instance_id").(string)
targetNamespaceName := d.Get("target_namespace_name").(string)
tagFilter := d.Get("tag_filter").(string)
var repoName, targetRepoName string
if v, ok := d.GetOk("repo_name"); ok {
repoName = v.(string)
}
if v, ok := d.GetOk("target_repo_name"); ok {
targetRepoName = v.(string)
}
if (repoName != "" && targetRepoName == "") || (repoName == "" && targetRepoName != "") {
return WrapError(Error(DefaultErrorMsg, syncRuleName, "create", "[Params repo_name or target_repo_name is empty]"))
}
response := &cr_ee.CreateRepoSyncRuleResponse{}
request := cr_ee.CreateCreateRepoSyncRuleRequest()
request.RegionId = crService.client.RegionId
request.SyncRuleName = syncRuleName
request.InstanceId = instanceId
request.NamespaceName = namespaceName
request.TargetRegionId = targetRegionId
request.TargetInstanceId = targetInstanceId
request.TargetNamespaceName = targetNamespaceName
request.TagFilter = tagFilter
request.SyncTrigger = "PASSIVE"
if repoName != "" && targetRepoName != "" {
request.SyncScope = "REPO"
request.RepoName = repoName
request.TargetRepoName = targetRepoName
} else {
request.SyncScope = "NAMESPACE"
}
raw, err := crService.client.WithCrEEClient(func(creeClient *cr_ee.Client) (interface{}, error) {
return creeClient.CreateRepoSyncRule(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cr_ee_sync_rule", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*cr_ee.CreateRepoSyncRuleResponse)
if !response.CreateRepoSyncRuleIsSuccess {
return WrapErrorf(fmt.Errorf("%v", response), DefaultErrorMsg, "alicloud_cr_ee_sync_rule", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(instanceId, ":", namespaceName, ":", response.SyncRuleId))
return resourceAlicloudCrEESyncRuleRead(d, meta)
}
func resourceAlicloudCrEESyncRuleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
crService := &CrService{client}
resp, err := crService.DescribeCrEESyncRule(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", resp.SyncRuleName)
d.Set("rule_id", resp.SyncRuleId)
d.Set("instance_id", resp.LocalInstanceId)
d.Set("namespace_name", resp.LocalNamespaceName)
d.Set("repo_name", resp.LocalRepoName)
d.Set("target_region_id", resp.TargetRegionId)
d.Set("target_instance_id", resp.TargetInstanceId)
d.Set("target_namespace_name", resp.TargetNamespaceName)
d.Set("target_repo_name", resp.TargetRepoName)
d.Set("tag_filter", resp.TagFilter)
d.Set("sync_direction", resp.SyncDirection)
d.Set("sync_scope", resp.SyncScope)
return nil
}
func resourceAlicloudCrEESyncRuleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
crService := &CrService{client}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
syncDirection := d.Get("sync_direction").(string)
if syncDirection != "FROM" {
return WrapError(Error(DefaultErrorMsg, d.Id(), "delete", "[Please delete sync rule in the source instance]"))
}
response := &cr_ee.DeleteRepoSyncRuleResponse{}
request := cr_ee.CreateDeleteRepoSyncRuleRequest()
request.RegionId = crService.client.RegionId
request.InstanceId = parts[0]
request.SyncRuleId = parts[2]
raw, err := crService.client.WithCrEEClient(func(creeClient *cr_ee.Client) (interface{}, error) {
return creeClient.DeleteRepoSyncRule(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*cr_ee.DeleteRepoSyncRuleResponse)
if !response.DeleteRepoSyncRuleIsSuccess {
return WrapErrorf(fmt.Errorf("%v", response), DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudCrEndpointAclPolicy() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCrEndpointAclPolicyCreate,
Read: resourceAlicloudCrEndpointAclPolicyRead,
Delete: resourceAlicloudCrEndpointAclPolicyDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"endpoint_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"internet"}, false),
},
"entry": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"module_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Registry"}, false),
},
},
}
}
func resourceAlicloudCrEndpointAclPolicyCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateInstanceEndpointAclPolicy"
request := make(map[string]interface{})
conn, err := client.NewAcrClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Comment"] = v
}
request["EndpointType"] = d.Get("endpoint_type")
request["Entry"] = d.Get("entry")
request["InstanceId"] = d.Get("instance_id")
if v, ok := d.GetOk("module_name"); ok {
request["ModuleName"] = v
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"SLB_SERVICE_ERROR"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cr_instance_endpoint_acl_policy", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["InstanceId"], ":", request["EndpointType"], ":", request["Entry"]))
return resourceAlicloudCrEndpointAclPolicyRead(d, meta)
}
func resourceAlicloudCrEndpointAclPolicyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
crService := CrService{client}
object, err := crService.DescribeCrEndpointAclPolicy(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_cr_instance_endpoint_acl_policy crService.DescribeCrEndpointAclPolicy Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
d.Set("endpoint_type", parts[1])
d.Set("entry", parts[2])
d.Set("instance_id", parts[0])
d.Set("description", object["Comment"])
return nil
}
func resourceAlicloudCrEndpointAclPolicyDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
action := "DeleteInstanceEndpointAclPolicy"
var response map[string]interface{}
conn, err := client.NewAcrClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"EndpointType": parts[1],
"Entry": parts[2],
"InstanceId": parts[0],
}
if v, ok := d.GetOk("module_name"); ok {
request["ModuleName"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"SLB_SERVICE_ERROR"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"encoding/json"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cr"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCRNamespace() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCRNamespaceCreate,
Read: resourceAlicloudCRNamespaceRead,
Update: resourceAlicloudCRNamespaceUpdate,
Delete: resourceAlicloudCRNamespaceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(2, 30),
},
"auto_create": {
Type: schema.TypeBool,
Required: true,
},
"default_visibility": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"PUBLIC", "PRIVATE"}, false),
},
},
}
}
func resourceAlicloudCRNamespaceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
namespaceName := d.Get("name").(string)
payload := &crCreateNamespaceRequestPayload{}
payload.Namespace.Namespace = namespaceName
serialized, err := json.Marshal(payload)
if err != nil {
return WrapError(err)
}
request := cr.CreateCreateNamespaceRequest()
request.SetContent(serialized)
raw, err := client.WithCrClient(func(crClient *cr.Client) (interface{}, error) {
return crClient.CreateNamespace(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cr_namespace", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
d.SetId(namespaceName)
return resourceAlicloudCRNamespaceUpdate(d, meta)
}
func resourceAlicloudCRNamespaceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
if d.HasChange("auto_create") || d.HasChange("default_visibility") {
payload := &crUpdateNamespaceRequestPayload{}
payload.Namespace.DefaultVisibility = d.Get("default_visibility").(string)
payload.Namespace.AutoCreate = d.Get("auto_create").(bool)
serialized, err := json.Marshal(payload)
if err != nil {
return WrapError(err)
}
request := cr.CreateUpdateNamespaceRequest()
request.RegionId = client.RegionId
request.SetContent(serialized)
request.Namespace = d.Get("name").(string)
raw, err := client.WithCrClient(func(crClient *cr.Client) (interface{}, error) {
return crClient.UpdateNamespace(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
}
return resourceAlicloudCRNamespaceRead(d, meta)
}
func resourceAlicloudCRNamespaceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
crService := CrService{client}
object, err := crService.DescribeCrNamespace(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
var response crDescribeNamespaceResponse
err = json.Unmarshal(object.GetHttpContentBytes(), &response)
if err != nil {
return WrapError(err)
}
d.Set("name", response.Data.Namespace.Namespace)
d.Set("auto_create", response.Data.Namespace.AutoCreate)
d.Set("default_visibility", response.Data.Namespace.DefaultVisibility)
return nil
}
func resourceAlicloudCRNamespaceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
crService := CrService{client}
request := cr.CreateDeleteNamespaceRequest()
request.Namespace = d.Id()
raw, err := client.WithCrClient(func(crClient *cr.Client) (interface{}, error) {
return crClient.DeleteNamespace(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"NAMESPACE_NOT_EXIST"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
return WrapError(crService.WaitForCRNamespace(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"encoding/json"
"fmt"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cr"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCRRepo() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCRRepoCreate,
Read: resourceAlicloudCRRepoRead,
Update: resourceAlicloudCRRepoUpdate,
Delete: resourceAlicloudCRRepoDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"namespace": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(2, 30),
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(2, 30),
},
"summary": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(1, 100),
},
"repo_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{RepoTypePublic, RepoTypePrivate}, false),
},
"detail": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(0, 2000),
},
// computed
"domain_list": {
Type: schema.TypeMap,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"vpc": {
Type: schema.TypeString,
Computed: true,
},
"public": {
Type: schema.TypeString,
Computed: true,
},
"internal": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func resourceAlicloudCRRepoCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
repoNamespace := d.Get("namespace").(string)
repoName := d.Get("name").(string)
payload := &crCreateRepoRequestPayload{}
payload.Repo.RepoNamespace = repoNamespace
payload.Repo.RepoName = repoName
payload.Repo.Summary = d.Get("summary").(string)
payload.Repo.Detail = d.Get("detail").(string)
payload.Repo.RepoType = d.Get("repo_type").(string)
serialized, err := json.Marshal(payload)
if err != nil {
return WrapError(err)
}
request := cr.CreateCreateRepoRequest()
request.RegionId = client.RegionId
request.SetContent(serialized)
raw, err := client.WithCrClient(func(crClient *cr.Client) (interface{}, error) {
return crClient.CreateRepo(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cr_repo", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
d.SetId(fmt.Sprintf("%s%s%s", repoNamespace, SLASH_SEPARATED, repoName))
return resourceAlicloudCRRepoRead(d, meta)
}
func resourceAlicloudCRRepoUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
if d.HasChange("summary") || d.HasChange("detail") || d.HasChange("repo_type") {
payload := &crUpdateRepoRequestPayload{}
payload.Repo.Summary = d.Get("summary").(string)
payload.Repo.Detail = d.Get("detail").(string)
payload.Repo.RepoType = d.Get("repo_type").(string)
serialized, err := json.Marshal(payload)
if err != nil {
return WrapError(err)
}
request := cr.CreateUpdateRepoRequest()
request.RegionId = client.RegionId
request.SetContent(serialized)
request.RepoName = d.Get("name").(string)
request.RepoNamespace = d.Get("namespace").(string)
raw, err := client.WithCrClient(func(crClient *cr.Client) (interface{}, error) {
return crClient.UpdateRepo(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
}
return resourceAlicloudCRRepoRead(d, meta)
}
func resourceAlicloudCRRepoRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
crService := CrService{client}
object, err := crService.DescribeCrRepo(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
var response crDescribeRepoResponse
err = json.Unmarshal(object.GetHttpContentBytes(), &response)
if err != nil {
return WrapError(err)
}
d.Set("namespace", response.Data.Repo.RepoNamespace)
d.Set("name", response.Data.Repo.RepoName)
d.Set("detail", response.Data.Repo.Detail)
d.Set("summary", response.Data.Repo.Summary)
d.Set("repo_type", response.Data.Repo.RepoType)
domainList := make(map[string]string)
domainList["public"] = response.Data.Repo.RepoDomainList.Public
domainList["internal"] = response.Data.Repo.RepoDomainList.Internal
domainList["vpc"] = response.Data.Repo.RepoDomainList.Vpc
d.Set("domain_list", domainList)
return nil
}
func resourceAlicloudCRRepoDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
crService := CrService{client}
sli := strings.Split(d.Id(), SLASH_SEPARATED)
repoNamespace := sli[0]
repoName := sli[1]
request := cr.CreateDeleteRepoRequest()
request.RegionId = client.RegionId
request.RepoNamespace = repoNamespace
request.RepoName = repoName
raw, err := client.WithCrClient(func(crClient *cr.Client) (interface{}, error) {
return crClient.DeleteRepo(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"REPO_NOT_EXIST"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
return WrapError(crService.WaitForCrRepo(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"fmt"
"regexp"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"sort"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/denverdino/aliyungo/cs"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCSApplication() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCSApplicationCreate,
Read: resourceAlicloudCSApplicationRead,
Update: resourceAlicloudCSApplicationUpdate,
Delete: resourceAlicloudCSApplicationDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"cluster_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-zA-Z0-9]{1}[a-zA-Z0-9-]{0,63}$`), "should be 1-64 characters long, and can contain numbers, English letters and hyphens, but cannot start with hyphens."),
},
"description": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return !d.HasChange("version")
},
},
"template": {
Type: schema.TypeString,
Required: true,
StateFunc: func(v interface{}) string {
yaml, _ := normalizeYamlString(v)
return yaml
},
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if !d.HasChange("version") {
return true
}
equal, _ := compareYamlTemplateAreEquivalent(old, new)
return equal
},
ValidateFunc: validateYamlString,
},
"version": {
Type: schema.TypeString,
Optional: true,
Default: "1.0",
},
"environment": {
Type: schema.TypeMap,
Optional: true,
Elem: schema.TypeString,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return !d.HasChange("version")
},
},
"latest_image": {
Type: schema.TypeBool,
Optional: true,
Default: false,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return !d.HasChange("version")
},
},
"blue_green": {
Type: schema.TypeBool,
Optional: true,
Default: false,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.IsNewResource()
},
},
"blue_green_confirm": {
Type: schema.TypeBool,
Optional: true,
Default: false,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return !d.Get("blue_green").(bool)
},
},
"services": {
Type: schema.TypeList,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"version": {
Type: schema.TypeString,
Computed: true,
},
},
},
Computed: true,
},
"default_domain": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudCSApplicationCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
csService := CsService{client}
clusterName := Trim(d.Get("cluster_name").(string))
args := &cs.ProjectCreationArgs{
Name: d.Get("name").(string),
Description: d.Get("description").(string),
Template: d.Get("template").(string),
Version: d.Get("version").(string),
LatestImage: d.Get("latest_image").(bool),
}
if environment, ok := d.GetOk("environment"); ok {
env := make(map[string]string)
for k, v := range environment.(map[string]interface{}) {
env[k] = v.(string)
}
args.Environment = env
}
invoker := NewInvoker()
if err := invoker.Run(func() error {
cluster, certs, err := csService.GetContainerClusterAndCertsByName(clusterName)
if err == nil {
_, err = client.WithCsProjectClient(cluster.ClusterID, cluster.MasterURL, *certs, func(csProjectClient *cs.ProjectClient) (interface{}, error) {
return nil, csProjectClient.CreateProject(args)
})
}
return err
}); err != nil {
return fmt.Errorf("Creating container application got an error: %#v", err)
}
d.SetId(fmt.Sprintf("%s%s%s", clusterName, COLON_SEPARATED, args.Name))
if err := csService.WaitForContainerApplication(clusterName, args.Name, Running, DefaultTimeoutMedium); err != nil {
return fmt.Errorf("Waitting for container application %#v got an error: %#v", cs.Running, err)
}
return resourceAlicloudCSApplicationRead(d, meta)
}
func resourceAlicloudCSApplicationRead(d *schema.ResourceData, meta interface{}) error {
parts := strings.Split(d.Id(), COLON_SEPARATED)
client := meta.(*connectivity.AliyunClient)
csService := CsService{client}
application, err := csService.DescribeContainerApplication(parts[0], parts[1])
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return err
}
d.Set("cluster_name", parts[0])
d.Set("name", application.Name)
d.Set("description", application.Description)
d.Set("version", application.Version)
d.Set("template", application.Template)
env := make(map[string]string)
for k, v := range application.Environment {
if k == "COMPOSE_PROJECT_NAME" || k == "ACS_PROJECT_VERSION" {
continue
}
if k == "ACS_DEFAULT_DOMAIN" {
d.Set("default_domain", v)
continue
}
env[k] = v
}
d.Set("environment", env)
var services []map[string]interface{}
serviceIds := make([]string, len(application.Services))
for _, s := range application.Services {
serviceIds = append(serviceIds, s.ID)
}
if len(serviceIds) > 0 {
sort.Strings(serviceIds)
}
for _, id := range serviceIds {
for _, s := range application.Services {
if s.ID != id {
continue
}
mapping := map[string]interface{}{
"id": s.ID,
"name": s.Name,
"status": s.CurrentState,
"version": s.Version,
}
services = append(services, mapping)
}
}
if err := d.Set("services", services); err != nil {
return err
}
return nil
}
func resourceAlicloudCSApplicationUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
csService := CsService{client}
parts := strings.Split(d.Id(), COLON_SEPARATED)
clusterName := parts[0]
invoker := NewInvoker()
args := &cs.ProjectUpdationArgs{
Name: parts[1],
Description: d.Get("description").(string),
Template: d.Get("template").(string),
Version: d.Get("version").(string),
LatestImage: d.Get("latest_image").(bool),
}
if environment, ok := d.GetOk("environment"); ok {
env := make(map[string]string)
for k, v := range environment.(map[string]interface{}) {
env[k] = v.(string)
}
args.Environment = env
}
blue_green := d.Get("blue_green").(bool)
if blue_green {
args.UpdateMethod = "blue-green"
}
d.Partial(true)
update := false
if d.HasChange("description") {
update = true
d.SetPartial("description")
}
if d.HasChange("template") {
update = true
d.SetPartial("template")
}
if d.HasChange("environment") {
update = true
d.SetPartial("environment")
}
if d.HasChange("version") {
update = true
d.SetPartial("version")
}
if d.HasChange("latest_image") {
update = true
}
if d.HasChange("blue_green") {
update = true
d.SetPartial("blue_green")
}
if !d.HasChange("version") && !blue_green {
cluster, certs, err := csService.GetContainerClusterAndCertsByName(clusterName)
if err == nil {
_, err = client.WithCsProjectClient(cluster.ClusterID, cluster.MasterURL, *certs, func(csProjectClient *cs.ProjectClient) (interface{}, error) {
return nil, csProjectClient.RollBackBlueGreenProject(parts[1], true)
})
}
return fmt.Errorf("Rollbacking container application blue-green got an error: %#v", err)
}
if update {
for {
err := invoker.Run(func() error {
cluster, certs, err := csService.GetContainerClusterAndCertsByName(clusterName)
if err == nil {
_, err = client.WithCsProjectClient(cluster.ClusterID, cluster.MasterURL, *certs, func(csProjectClient *cs.ProjectClient) (interface{}, error) {
return nil, csProjectClient.UpdateProject(args)
})
}
return err
})
if err != nil {
if IsExpectedErrors(err, []string{"Conflicts with unconfirmed updates for operation"}) {
err := invoker.Run(func() error {
cluster, certs, err := csService.GetContainerClusterAndCertsByName(clusterName)
if err == nil {
_, err = client.WithCsProjectClient(cluster.ClusterID, cluster.MasterURL, *certs, func(csProjectClient *cs.ProjectClient) (interface{}, error) {
return nil, csProjectClient.RollBackBlueGreenProject(parts[1], true)
})
}
return err
})
if err != nil {
return fmt.Errorf("Rollbacking container application blue-green got an error: %#v", err)
}
err = csService.WaitForContainerApplication(parts[0], parts[1], Running, DefaultTimeoutMedium)
if err != nil {
return fmt.Errorf("After rolling back blue-green project, waitting for container application %#v got an error: %#v", Running, err)
}
continue
}
return fmt.Errorf("Updating container application got an error: %#v", err)
}
break
}
}
if d.Get("blue_green_confirm").(bool) {
err := invoker.Run(func() error {
cluster, certs, err := csService.GetContainerClusterAndCertsByName(clusterName)
if err == nil {
_, err = client.WithCsProjectClient(cluster.ClusterID, cluster.MasterURL, *certs, func(csProjectClient *cs.ProjectClient) (interface{}, error) {
return nil, csProjectClient.ConfirmBlueGreenProject(parts[1], true)
})
}
return err
})
if err != nil {
return fmt.Errorf("Confirmming container application blue-green got an error: %#v", err)
}
}
if err := csService.WaitForContainerApplication(parts[0], parts[1], Running, DefaultTimeoutMedium); err != nil {
return fmt.Errorf("After updating, waitting for container application %#v got an error: %#v", Running, err)
}
d.Partial(false)
return resourceAlicloudCSApplicationRead(d, meta)
}
func resourceAlicloudCSApplicationDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
csService := CsService{client}
parts := strings.Split(d.Id(), COLON_SEPARATED)
clusterName := parts[0]
appName := parts[1]
invoker := NewInvoker()
return resource.Retry(3*time.Minute, func() *resource.RetryError {
err := invoker.Run(func() error {
cluster, certs, err := csService.GetContainerClusterAndCertsByName(clusterName)
if err == nil {
_, err = client.WithCsProjectClient(cluster.ClusterID, cluster.MasterURL, *certs, func(csProjectClient *cs.ProjectClient) (interface{}, error) {
return nil, csProjectClient.DeleteProject(appName, true, false)
})
}
return err
})
if err != nil {
if IsExpectedErrors(err, []string{"Not Found"}) {
return nil
}
if !IsExpectedErrors(err, []string{"Unable to reach primary cluster manager", AliyunGoClientFailure}) {
return resource.NonRetryableError(fmt.Errorf("Deleting container application %s got an error: %#v.", appName, err))
}
}
var project cs.GetProjectResponse
if err := invoker.Run(func() error {
cluster, certs, err := csService.GetContainerClusterAndCertsByName(clusterName)
if err != nil {
return err
}
raw, err := client.WithCsProjectClient(cluster.ClusterID, cluster.MasterURL, *certs, func(csProjectClient *cs.ProjectClient) (interface{}, error) {
return csProjectClient.GetProject(appName)
})
if err != nil {
return err
}
project, _ = raw.(cs.GetProjectResponse)
return nil
}); err != nil {
if IsExpectedErrors(err, []string{"Not Found", "Unable to reach primary cluster manager"}) {
return nil
}
return resource.NonRetryableError(fmt.Errorf("Getting container application %s got an error: %#v.", appName, err))
}
if project.Name == "" {
return nil
}
return resource.RetryableError(fmt.Errorf("Deleting container application %s timeout: %#v.", appName, err))
})
}
package alicloud
import (
"time"
"github.com/alibabacloud-go/tea/tea"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
cs "github.com/alibabacloud-go/cs-20151215/v2/client"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
const resourceName = "resource_alicloud_cs_autoscaling_config"
func resourceAlicloudCSAutoscalingConfig() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCSAutoscalingConfigCreate,
Read: resourceAlicloudCSAutoscalingConfigRead,
Update: resourceAlicloudCSAutoscalingConfigUpdate,
Delete: resourceAlicloudCSAutoscalingConfigDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(90 * time.Minute),
Update: schema.DefaultTimeout(60 * time.Minute),
Delete: schema.DefaultTimeout(60 * time.Minute),
},
Schema: map[string]*schema.Schema{
"cluster_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"cool_down_duration": {
Type: schema.TypeString,
Optional: true,
Default: "10m",
},
"unneeded_duration": {
Type: schema.TypeString,
Optional: true,
Default: "10m",
},
"utilization_threshold": {
Type: schema.TypeString,
Optional: true,
Default: "0.5",
},
"gpu_utilization_threshold": {
Type: schema.TypeString,
Optional: true,
Default: "0.5",
},
"scan_interval": {
Type: schema.TypeString,
Optional: true,
Default: "30s",
},
},
}
}
func resourceAlicloudCSAutoscalingConfigCreate(d *schema.ResourceData, meta interface{}) error {
return resourceAlicloudCSAutoscalingConfigUpdate(d, meta)
}
func resourceAlicloudCSAutoscalingConfigRead(d *schema.ResourceData, meta interface{}) error {
return nil
}
func resourceAlicloudCSAutoscalingConfigUpdate(d *schema.ResourceData, meta interface{}) error {
d.Partial(true)
client, err := meta.(*connectivity.AliyunClient).NewRoaCsClient()
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceName, "InitializeClient", err)
}
// cluster id
var clusterId string
if v, ok := d.GetOk("cluster_id"); ok {
clusterId = v.(string)
}
// auto scaling config
updateAutoscalingConfigRequest := &cs.CreateAutoscalingConfigRequest{}
if v, ok := d.GetOk("cool_down_duration"); ok {
updateAutoscalingConfigRequest.CoolDownDuration = tea.String(v.(string))
}
if v, ok := d.GetOk("unneeded_duration"); ok {
updateAutoscalingConfigRequest.UnneededDuration = tea.String(v.(string))
}
if v, ok := d.GetOk("utilization_threshold"); ok {
updateAutoscalingConfigRequest.UtilizationThreshold = tea.String(v.(string))
}
if v, ok := d.GetOk("gpu_utilization_threshold"); ok {
updateAutoscalingConfigRequest.GpuUtilizationThreshold = tea.String(v.(string))
}
if v, ok := d.GetOk("scan_interval"); ok {
updateAutoscalingConfigRequest.ScanInterval = tea.String(v.(string))
}
_, err = client.CreateAutoscalingConfig(tea.String(clusterId), updateAutoscalingConfigRequest)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceName, "CreateAutoscalingConfig", AliyunTablestoreGoSdk)
}
addDebug("CreateAutoscalingConfig", updateAutoscalingConfigRequest, err)
d.SetId(clusterId)
d.Partial(false)
return resourceAlicloudCSAutoscalingConfigRead(d, meta)
}
func resourceAlicloudCSAutoscalingConfigDelete(d *schema.ResourceData, meta interface{}) error {
return nil
}
package alicloud
import (
"encoding/base64"
"fmt"
"regexp"
"time"
aliyungoecs "github.com/denverdino/aliyungo/ecs"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/denverdino/aliyungo/common"
"github.com/denverdino/aliyungo/cs"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
const (
EdgeKubernetesDefaultTimeoutInMinutes = 60
EdgeProfile = "Edge"
)
func resourceAlicloudCSEdgeKubernetes() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCSEdgeKubernetesCreate,
Read: resourceAlicloudCSKubernetesRead,
Update: resourceAlicloudCSEdgeKubernetesUpdate,
Delete: resourceAlicloudCSKubernetesDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(EdgeKubernetesDefaultTimeoutInMinutes * time.Minute),
Update: schema.DefaultTimeout(EdgeKubernetesDefaultTimeoutInMinutes * time.Minute),
Delete: schema.DefaultTimeout(EdgeKubernetesDefaultTimeoutInMinutes * time.Minute),
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringLenBetween(1, 63),
ConflictsWith: []string{"name_prefix"},
},
"name_prefix": {
Type: schema.TypeString,
Optional: true,
Default: "Terraform-Creation",
ValidateFunc: validation.StringLenBetween(0, 37),
ConflictsWith: []string{"name"},
},
// worker configurations
"worker_vswitch_ids": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^vsw-[a-z0-9]*$`), "should start with 'vsw-'."),
},
MinItems: 1,
},
"force_update": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: false,
},
"worker_instance_types": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
MinItems: 1,
MaxItems: 10,
},
//cloud worker number
"worker_number": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntAtLeast(1),
},
"worker_disk_size": {
Type: schema.TypeInt,
Optional: true,
Default: 40,
ValidateFunc: validation.IntBetween(20, 32768),
},
"worker_disk_category": {
Type: schema.TypeString,
Optional: true,
Default: DiskCloudEfficiency,
ValidateFunc: validation.StringInSlice([]string{
string(DiskCloudEfficiency), string(DiskCloudSSD), string(DiskCloudESSD)}, false),
},
"worker_disk_performance_level": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"PL0", "PL1", "PL2", "PL3"}, false),
DiffSuppressFunc: workerDiskPerformanceLevelDiffSuppressFunc,
},
"worker_disk_snapshot_policy_id": {
Type: schema.TypeString,
Optional: true,
},
"proxy_mode": {
Type: schema.TypeString,
Optional: true,
Default: "ipvs",
ValidateFunc: validation.StringInSlice([]string{"iptables", "ipvs"}, false),
},
"worker_instance_charge_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{string(common.PrePaid), string(common.PostPaid)}, false),
Default: PostPaid,
},
"worker_data_disks": {
Optional: true,
Type: schema.TypeList,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"size": {
Type: schema.TypeString,
Optional: true,
},
"category": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"all", "cloud", "ephemeral_ssd", "cloud_essd", "cloud_efficiency", "cloud_ssd", "local_disk"}, false),
},
"snapshot_id": {
Type: schema.TypeString,
Optional: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
},
"device": {
Type: schema.TypeString,
Optional: true,
},
"kms_key_id": {
Type: schema.TypeString,
Optional: true,
},
"encrypted": {
Type: schema.TypeString,
Optional: true,
},
"auto_snapshot_policy_id": {
Type: schema.TypeString,
Optional: true,
},
"performance_level": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
// global configurations
"pod_cidr": {
Type: schema.TypeString,
Optional: true,
},
"service_cidr": {
Type: schema.TypeString,
Optional: true,
},
"node_cidr_mask": {
Type: schema.TypeInt,
Optional: true,
Default: KubernetesClusterNodeCIDRMasksByDefault,
ValidateFunc: validation.IntBetween(24, 28),
},
"new_nat_gateway": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
ConflictsWith: []string{"key_name"},
},
"key_name": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"password"},
},
"install_cloud_monitor": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"version": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"user_data": {
Type: schema.TypeString,
Optional: true,
},
"addons": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
},
"config": {
Type: schema.TypeString,
Optional: true,
},
"disabled": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
},
},
"slb_internet_enabled": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"kube_config": {
Type: schema.TypeString,
Optional: true,
},
"client_cert": {
Type: schema.TypeString,
Optional: true,
},
"client_key": {
Type: schema.TypeString,
Optional: true,
},
"cluster_ca_cert": {
Type: schema.TypeString,
Optional: true,
},
"deletion_protection": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"rds_instances": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
// computed parameters start
"certificate_authority": {
Type: schema.TypeMap,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cluster_cert": {
Type: schema.TypeString,
Computed: true,
},
"client_cert": {
Type: schema.TypeString,
Computed: true,
},
"client_key": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"connections": {
Type: schema.TypeMap,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"api_server_internet": {
Type: schema.TypeString,
Computed: true,
},
"api_server_intranet": {
Type: schema.TypeString,
Computed: true,
},
"master_public_ip": {
Type: schema.TypeString,
Computed: true,
},
"service_domain": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"slb_internet": {
Type: schema.TypeString,
Computed: true,
},
"slb_intranet": {
Type: schema.TypeString,
Computed: true,
},
"security_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"is_enterprise_security_group": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
ConflictsWith: []string{"security_group_id"},
},
"nat_gateway_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"worker_nodes": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"private_ip": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"availability_zone": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
// computed params end
// too hard to use this config
"log_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"type": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{KubernetesClusterLoggingTypeSLS}, false),
Required: true,
},
"project": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"tags": {
Type: schema.TypeMap,
Optional: true,
},
"retain_resources": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
}
}
func resourceAlicloudCSEdgeKubernetesCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
invoker := NewInvoker()
csService := CsService{client}
args, err := buildKubernetesArgs(d, meta)
if err != nil {
return WrapError(err)
}
var requestInfo *cs.Client
var response interface{}
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
args.RegionId = common.Region(client.RegionId)
args.ClusterType = cs.ManagedKubernetes
args.Profile = EdgeProfile
return csClient.CreateManagedKubernetesCluster(&cs.ManagedKubernetesClusterCreationRequest{
ClusterArgs: args.ClusterArgs,
WorkerArgs: args.WorkerArgs,
})
})
response = raw
return err
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cs_edge_kubernetes", "CreateKubernetesCluster", response)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["RegionId"] = common.Region(client.RegionId)
requestMap["Args"] = args
addDebug("CreateKubernetesCluster", response, requestInfo, requestMap)
}
cluster, _ := response.(*cs.ClusterCommonResponse)
d.SetId(cluster.ClusterID)
stateConf := BuildStateConf([]string{"initial"}, []string{"running"}, d.Timeout(schema.TimeoutCreate), 10*time.Minute, csService.CsKubernetesInstanceStateRefreshFunc(d.Id(), []string{"deleting", "failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudCSKubernetesRead(d, meta)
}
func resourceAlicloudCSEdgeKubernetesUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
csService := CsService{client}
d.Partial(true)
invoker := NewInvoker()
//scale up cloud worker nodes
var resp interface{}
if d.HasChanges("worker_number") {
oldV, newV := d.GetChange("worker_number")
oldValue, ok := oldV.(int)
if !ok {
return WrapErrorf(fmt.Errorf("worker_number old value can not be parsed"), "parseError %d", oldValue)
}
newValue, ok := newV.(int)
if !ok {
return WrapErrorf(fmt.Errorf("worker_number new value can not be parsed"), "parseError %d", oldValue)
}
// Edge cluster node support remove nodes.
if newValue < oldValue {
return WrapErrorf(fmt.Errorf("worker_number can not be less than before"), "scaleOutCloudWorkersFailed %d:%d", newValue, oldValue)
}
// scale out cluster.
if newValue > oldValue {
password := d.Get("password").(string)
keyPair := d.Get("key_name").(string)
args := &cs.ScaleOutKubernetesClusterRequest{
KeyPair: keyPair,
LoginPassword: password,
Count: int64(newValue) - int64(oldValue),
WorkerVSwitchIds: expandStringList(d.Get("worker_vswitch_ids").([]interface{})),
WorkerInstanceTypes: expandStringList(d.Get("worker_instance_types").([]interface{})),
}
if userData, ok := d.GetOk("user_data"); ok {
_, base64DecodeError := base64.StdEncoding.DecodeString(userData.(string))
if base64DecodeError == nil {
args.UserData = userData.(string)
} else {
args.UserData = base64.StdEncoding.EncodeToString([]byte(userData.(string)))
}
}
if imageID, ok := d.GetOk("image_id"); ok {
args.ImageId = imageID.(string)
}
if v, ok := d.GetOk("worker_disk_category"); ok {
args.WorkerSystemDiskCategory = aliyungoecs.DiskCategory(v.(string))
}
if v, ok := d.GetOk("worker_disk_size"); ok {
args.WorkerSystemDiskSize = int64(v.(int))
}
if v, ok := d.GetOk("worker_disk_snapshot_policy_id"); ok {
args.WorkerSnapshotPolicyId = v.(string)
}
if v, ok := d.GetOk("worker_disk_performance_level"); ok {
args.WorkerSystemDiskPerformanceLevel = v.(string)
}
if dds, ok := d.GetOk("worker_data_disks"); ok {
disks := dds.([]interface{})
createDataDisks := make([]cs.DataDisk, 0, len(disks))
for _, e := range disks {
pack := e.(map[string]interface{})
dataDisk := cs.DataDisk{
Size: pack["size"].(string),
DiskName: pack["name"].(string),
Category: pack["category"].(string),
Device: pack["device"].(string),
AutoSnapshotPolicyId: pack["auto_snapshot_policy_id"].(string),
KMSKeyId: pack["kms_key_id"].(string),
Encrypted: pack["encrypted"].(string),
PerformanceLevel: pack["performance_level"].(string),
}
createDataDisks = append(createDataDisks, dataDisk)
}
args.WorkerDataDisks = createDataDisks
}
if d.HasChange("tags") && !d.IsNewResource() {
if tags, err := ConvertCsTags(d); err == nil {
args.Tags = tags
}
d.SetPartial("tags")
}
if err := invoker.Run(func() error {
var err error
resp, err = client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
resp, err := csClient.ScaleOutKubernetesCluster(d.Id(), args)
return resp, err
})
return err
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "ScaleOutCloudWorkers", DenverdinoAliyungo)
}
if debugOn() {
resizeRequestMap := make(map[string]interface{})
resizeRequestMap["ClusterId"] = d.Id()
resizeRequestMap["Args"] = args
addDebug("ResizeKubernetesCluster", resp, resizeRequestMap)
}
stateConf := BuildStateConf([]string{"scaling"}, []string{"running"}, d.Timeout(schema.TimeoutUpdate), 10*time.Second, csService.CsKubernetesInstanceStateRefreshFunc(d.Id(), []string{"deleting", "failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("worker_data_disks")
d.SetPartial("worker_number")
d.SetPartial("worker_disk_category")
d.SetPartial("worker_disk_size")
d.SetPartial("worker_disk_snapshot_policy_id")
d.SetPartial("worker_disk_performance_level")
}
}
// modify cluster name
if !d.IsNewResource() && (d.HasChange("name") || d.HasChange("name_prefix")) {
var clusterName string
if v, ok := d.GetOk("name"); ok {
clusterName = v.(string)
} else {
clusterName = resource.PrefixedUniqueId(d.Get("name_prefix").(string))
}
var requestInfo *cs.Client
var response interface{}
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
return nil, csClient.ModifyClusterName(d.Id(), clusterName)
})
response = raw
return err
}); err != nil && !IsExpectedErrors(err, []string{"ErrorClusterNameAlreadyExist"}) {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "ModifyClusterName", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["ClusterId"] = d.Id()
requestMap["ClusterName"] = clusterName
addDebug("ModifyClusterName", response, requestInfo, requestMap)
}
d.SetPartial("name")
d.SetPartial("name_prefix")
}
// modify cluster deletion protection
if !d.IsNewResource() && d.HasChange("deletion_protection") {
var requestInfo cs.ModifyClusterArgs
if v, ok := d.GetOk("deletion_protection"); ok {
requestInfo.DeletionProtection = v.(bool)
}
var response interface{}
if err := invoker.Run(func() error {
_, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
return nil, csClient.ModifyCluster(d.Id(), &requestInfo)
})
return err
}); err != nil && !IsExpectedErrors(err, []string{"ErrorModifyDeletionProtectionFailed"}) {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "ModifyCluster", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["ClusterId"] = d.Id()
requestMap["deletion_protection"] = requestInfo.DeletionProtection
addDebug("ModifyCluster", response, requestInfo, requestMap)
}
d.SetPartial("deletion_protection")
}
// modify cluster tag
if d.HasChange("tags") {
err := updateKubernetesClusterTag(d, meta)
if err != nil {
return WrapErrorf(err, ResponseCodeMsg, d.Id(), "ModifyClusterTags", AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("tags")
// upgrade cluster version
err := UpgradeAlicloudKubernetesCluster(d, meta)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "UpgradeClusterVersion", DenverdinoAliyungo)
}
d.Partial(false)
return resourceAlicloudCSKubernetesRead(d, meta)
}
package alicloud
import (
"encoding/base64"
"encoding/json"
"fmt"
"log"
"regexp"
"strings"
"time"
roacs "github.com/alibabacloud-go/cs-20151215/v2/client"
"github.com/alibabacloud-go/tea/tea"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"strconv"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/denverdino/aliyungo/common"
"github.com/denverdino/aliyungo/cs"
aliyungoecs "github.com/denverdino/aliyungo/ecs"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"gopkg.in/yaml.v2"
)
const (
KubernetesClusterNetworkTypeFlannel = "flannel"
KubernetesClusterNetworkTypeTerway = "terway"
KubernetesClusterLoggingTypeSLS = "SLS"
)
var (
KubernetesClusterNodeCIDRMasksByDefault = 24
)
func resourceAlicloudCSKubernetes() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCSKubernetesCreate,
Read: resourceAlicloudCSKubernetesRead,
Update: resourceAlicloudCSKubernetesUpdate,
Delete: resourceAlicloudCSKubernetesDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(90 * time.Minute),
Update: schema.DefaultTimeout(60 * time.Minute),
Delete: schema.DefaultTimeout(60 * time.Minute),
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringLenBetween(1, 63),
ConflictsWith: []string{"name_prefix"},
},
"name_prefix": {
Type: schema.TypeString,
Optional: true,
Default: "Terraform-Creation",
ValidateFunc: validation.StringLenBetween(0, 37),
ConflictsWith: []string{"name"},
Deprecated: "Field 'name_prefix' has been deprecated from provider version 1.75.0.",
},
// master configurations
"master_vswitch_ids": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^vsw-[a-z0-9]*$`), "should start with 'vsw-'."),
},
MinItems: 3,
MaxItems: 5,
},
"master_instance_types": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
MinItems: 3,
MaxItems: 5,
},
"master_disk_size": {
Type: schema.TypeInt,
Optional: true,
Default: 40,
ValidateFunc: validation.IntBetween(40, 500),
},
"master_disk_category": {
Type: schema.TypeString,
Optional: true,
Default: DiskCloudEfficiency,
},
"master_disk_performance_level": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PL0", "PL1", "PL2", "PL3"}, false),
DiffSuppressFunc: masterDiskPerformanceLevelDiffSuppressFunc,
},
"master_disk_snapshot_policy_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"master_instance_charge_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{string(common.PrePaid), string(common.PostPaid)}, false),
Default: PostPaid,
},
"master_period_unit": {
Type: schema.TypeString,
Optional: true,
Default: Month,
ValidateFunc: validation.StringInSlice([]string{"Week", "Month"}, false),
DiffSuppressFunc: csKubernetesMasterPostPaidDiffSuppressFunc,
},
"master_period": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
// must be a valid period, expected [1-9], 12, 24, 36, 48 or 60,
ValidateFunc: validation.Any(
validation.IntBetween(1, 9),
validation.IntInSlice([]int{12, 24, 36, 48, 60})),
DiffSuppressFunc: csKubernetesMasterPostPaidDiffSuppressFunc,
},
"master_auto_renew": {
Type: schema.TypeBool,
Default: false,
Optional: true,
DiffSuppressFunc: csKubernetesMasterPostPaidDiffSuppressFunc,
},
"master_auto_renew_period": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 6, 12}),
DiffSuppressFunc: csKubernetesMasterPostPaidDiffSuppressFunc,
},
// worker configurations
"worker_vswitch_ids": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^vsw-[a-z0-9]*$`), "should start with 'vsw-'."),
},
MinItems: 1,
},
"worker_instance_types": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
MinItems: 1,
MaxItems: 10,
},
"worker_number": {
Type: schema.TypeInt,
Required: true,
},
"worker_disk_size": {
Type: schema.TypeInt,
Optional: true,
Default: 40,
ValidateFunc: validation.IntBetween(20, 32768),
},
"worker_disk_category": {
Type: schema.TypeString,
Optional: true,
Default: DiskCloudEfficiency,
},
"worker_disk_performance_level": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"PL0", "PL1", "PL2", "PL3"}, false),
DiffSuppressFunc: workerDiskPerformanceLevelDiffSuppressFunc,
},
"worker_disk_snapshot_policy_id": {
Type: schema.TypeString,
Optional: true,
},
"worker_data_disk_size": {
Type: schema.TypeInt,
Optional: true,
Default: 40,
ValidateFunc: validation.IntBetween(20, 32768),
DiffSuppressFunc: workerDataDiskSizeSuppressFunc,
},
"worker_data_disk_category": {
Type: schema.TypeString,
Optional: true,
},
"worker_data_disks": {
Optional: true,
Type: schema.TypeList,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"size": {
Type: schema.TypeString,
Optional: true,
},
"category": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"all", "cloud", "ephemeral_ssd", "cloud_essd", "cloud_efficiency", "cloud_ssd", "local_disk"}, false),
},
"snapshot_id": {
Type: schema.TypeString,
Optional: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
},
"device": {
Type: schema.TypeString,
Optional: true,
},
"kms_key_id": {
Type: schema.TypeString,
Optional: true,
},
"encrypted": {
Type: schema.TypeString,
Optional: true,
},
"auto_snapshot_policy_id": {
Type: schema.TypeString,
Optional: true,
},
"performance_level": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"worker_instance_charge_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{string(common.PrePaid), string(common.PostPaid)}, false),
Default: PostPaid,
},
"worker_period_unit": {
Type: schema.TypeString,
Optional: true,
Default: Month,
ValidateFunc: validation.StringInSlice([]string{"Week", "Month"}, false),
DiffSuppressFunc: csKubernetesWorkerPostPaidDiffSuppressFunc,
},
"worker_period": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
ValidateFunc: validation.Any(
validation.IntBetween(1, 9),
validation.IntInSlice([]int{12, 24, 36, 48, 60})),
DiffSuppressFunc: csKubernetesWorkerPostPaidDiffSuppressFunc,
},
"worker_auto_renew": {
Type: schema.TypeBool,
Default: false,
Optional: true,
DiffSuppressFunc: csKubernetesWorkerPostPaidDiffSuppressFunc,
},
"worker_auto_renew_period": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 6, 12}),
DiffSuppressFunc: csKubernetesWorkerPostPaidDiffSuppressFunc,
},
"exclude_autoscaler_nodes": {
Type: schema.TypeBool,
Default: false,
Optional: true,
},
// global configurations
// Terway network
"pod_vswitch_ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^vsw-[a-z0-9]*$`), "should start with 'vsw-'."),
},
MaxItems: 10,
},
// Flannel network
"pod_cidr": {
Type: schema.TypeString,
Optional: true,
},
"service_cidr": {
Type: schema.TypeString,
Optional: true,
},
"node_cidr_mask": {
Type: schema.TypeInt,
Optional: true,
Default: KubernetesClusterNodeCIDRMasksByDefault,
ValidateFunc: validation.IntBetween(24, 28),
},
"new_nat_gateway": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
ConflictsWith: []string{"key_name", "kms_encrypted_password"},
},
"key_name": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"password", "kms_encrypted_password"},
},
"kms_encrypted_password": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"password", "key_name"},
},
"kms_encryption_context": {
Type: schema.TypeMap,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("kms_encrypted_password").(string) == ""
},
Elem: schema.TypeString,
},
"user_ca": {
Type: schema.TypeString,
Optional: true,
},
"enable_ssh": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"load_balancer_spec": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"slb.s1.small", "slb.s2.small", "slb.s2.medium", "slb.s3.small", "slb.s3.medium", "slb.s3.large"}, false),
Default: "slb.s1.small",
},
"image_id": {
Type: schema.TypeString,
Optional: true,
},
"install_cloud_monitor": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"version": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
// cpu policy options of kubelet
"cpu_policy": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"none", "static"}, false),
},
"proxy_mode": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"iptables", "ipvs"}, false),
},
"addons": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
},
"config": {
Type: schema.TypeString,
Optional: true,
},
"disabled": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
},
},
"tags": {
Type: schema.TypeMap,
Optional: true,
},
"slb_internet_enabled": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"deletion_protection": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"timezone": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"os_type": {
Type: schema.TypeString,
Optional: true,
Default: "Linux",
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Windows", "Linux"}, false),
},
"platform": {
Type: schema.TypeString,
Optional: true,
Default: "CentOS",
ForceNew: true,
},
"node_port_range": {
Type: schema.TypeString,
Optional: true,
Default: "30000-32767",
ForceNew: true,
},
"runtime": {
Type: schema.TypeMap,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Default: "docker",
},
"version": {
Type: schema.TypeString,
Optional: true,
Default: "19.03.5",
},
},
},
},
"cluster_domain": {
Type: schema.TypeString,
Optional: true,
Default: "cluster.local",
ForceNew: true,
Description: "cluster local domain",
},
"taints": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Optional: true,
},
"value": {
Type: schema.TypeString,
Optional: true,
},
"effect": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"NoSchedule", "NoExecute", "PreferNoSchedule"}, false),
},
},
},
},
"rds_instances": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"custom_san": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
// computed parameters
"kube_config": {
Type: schema.TypeString,
Optional: true,
},
"client_cert": {
Type: schema.TypeString,
Optional: true,
},
"client_key": {
Type: schema.TypeString,
Optional: true,
},
"cluster_ca_cert": {
Type: schema.TypeString,
Optional: true,
},
"certificate_authority": {
Type: schema.TypeMap,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cluster_cert": {
Type: schema.TypeString,
Computed: true,
},
"client_cert": {
Type: schema.TypeString,
Computed: true,
},
"client_key": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"connections": {
Type: schema.TypeMap,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"api_server_internet": {
Type: schema.TypeString,
Computed: true,
},
"api_server_intranet": {
Type: schema.TypeString,
Computed: true,
},
"master_public_ip": {
Type: schema.TypeString,
Computed: true,
},
"service_domain": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"slb_id": {
Type: schema.TypeString,
Computed: true,
Deprecated: "Field 'slb_id' has been deprecated from provider version 1.9.2. New field 'slb_internet' replaces it.",
},
"slb_internet": {
Type: schema.TypeString,
Computed: true,
},
"slb_intranet": {
Type: schema.TypeString,
Computed: true,
},
"security_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"is_enterprise_security_group": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
ConflictsWith: []string{"security_group_id"},
},
"nat_gateway_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"master_nodes": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"private_ip": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"worker_nodes": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"private_ip": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
// remove parameters below
// mix vswitch_ids between master and worker is not a good guidance to create cluster
"worker_instance_type": {
Type: schema.TypeString,
Optional: true,
Removed: "Field 'worker_instance_type' has been removed from provider version 1.75.0. New field 'worker_instance_types' replaces it.",
},
"vswitch_ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^vsw-[a-z0-9]*$`), "should start with 'vsw-'."),
},
MinItems: 3,
MaxItems: 5,
Removed: "Field 'vswitch_ids' has been removed from provider version 1.75.0. New field 'master_vswitch_ids' and 'worker_vswitch_ids' replace it.",
},
// single instance type would cause extra troubles
"master_instance_type": {
Type: schema.TypeString,
Optional: true,
Removed: "Field 'master_instance_type' has been removed from provider version 1.75.0. New field 'master_instance_types' replaces it.",
},
// force update is a high risk operation
"force_update": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Removed: "Field 'force_update' has been removed from provider version 1.75.0.",
},
"availability_zone": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
// single az would be never supported.
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
Removed: "Field 'vswitch_id' has been removed from provider version 1.75.0. New field 'master_vswitch_ids' and 'worker_vswitch_ids' replaces it.",
},
// worker_numbers in array is a hell of management
"worker_numbers": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeInt,
Default: 3,
},
MinItems: 1,
MaxItems: 3,
Removed: "Field 'worker_numbers' has been removed from provider version 1.75.0. New field 'worker_number' replaces it.",
},
"nodes": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Removed: "Field 'nodes' has been removed from provider version 1.9.4. New field 'master_nodes' replaces it.",
},
// too hard to use this config
"log_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"type": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{KubernetesClusterLoggingTypeSLS}, false),
Required: true,
},
"project": {
Type: schema.TypeString,
Optional: true,
},
},
},
Removed: "Field 'log_config' has been removed from provider version 1.75.0. New field 'addons' replaces it.",
},
"cluster_network_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{KubernetesClusterNetworkTypeFlannel, KubernetesClusterNetworkTypeTerway}, false),
Removed: "Field 'cluster_network_type' has been removed from provider version 1.75.0. New field 'addons' replaces it.",
},
"user_data": {
Type: schema.TypeString,
Optional: true,
},
"node_name_mode": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^customized,[a-z0-9]([-a-z0-9\.])*,([5-9]|[1][0-2]),([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`), "Each node name consists of a prefix, an IP substring, and a suffix. For example, if the node IP address is 192.168.0.55, the prefix is aliyun.com, IP substring length is 5, and the suffix is test, the node name will be aliyun.com00055test."),
},
"worker_ram_role_name": {
Type: schema.TypeString,
Computed: true,
},
"service_account_issuer": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"api_audiences": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
ForceNew: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"retain_resources": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
}
}
func resourceAlicloudCSKubernetesCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
csService := CsService{client}
invoker := NewInvoker()
var requestInfo *cs.Client
var raw interface{}
// prepare args and set default value
args, err := buildKubernetesArgs(d, meta)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cs_kubernetes", "PrepareKubernetesClusterArgs", err)
}
if err = invoker.Run(func() error {
raw, err = client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
args.RegionId = common.Region(client.RegionId)
args.ClusterType = cs.DelicatedKubernetes
return csClient.CreateDelicatedKubernetesCluster(args)
})
return err
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cs_kubernetes", "CreateKubernetesCluster", raw)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["RegionId"] = common.Region(client.RegionId)
requestMap["Params"] = args
addDebug("CreateKubernetesCluster", raw, requestInfo, requestMap)
}
cluster, ok := raw.(*cs.ClusterCommonResponse)
if ok != true {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cs_kubernetes", "ParseKubernetesClusterResponse", raw)
}
d.SetId(cluster.ClusterID)
// reset interval to 10s
stateConf := BuildStateConf([]string{"initial"}, []string{"running"}, d.Timeout(schema.TimeoutCreate), 10*time.Second, csService.CsKubernetesInstanceStateRefreshFunc(d.Id(), []string{"deleting", "failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudCSKubernetesRead(d, meta)
}
func resourceAlicloudCSKubernetesUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
csService := CsService{client}
d.Partial(true)
invoker := NewInvoker()
if !d.IsNewResource() && d.HasChange("resource_group_id") {
var requestInfo cs.ModifyClusterArgs
requestInfo.ResourceGroupId = d.Get("resource_group_id").(string)
response, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
return nil, csClient.ModifyCluster(d.Id(), &requestInfo)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "ModifyCluster", DenverdinoAliyungo)
}
addDebug("ModifyCluster", response, requestInfo)
d.SetPartial("resource_group_id")
}
if d.HasChange("worker_number") && !d.IsNewResource() {
oldV, newV := d.GetChange("worker_number")
oldValue, ok := oldV.(int)
if ok != true {
return WrapErrorf(fmt.Errorf("worker_number old value can not be parsed"), "parseError %d", oldValue)
}
newValue, ok := newV.(int)
if ok != true {
return WrapErrorf(fmt.Errorf("worker_number new value can not be parsed"), "parseError %d", newValue)
}
// scale out cluster.
if newValue > oldValue {
password := d.Get("password").(string)
if password == "" {
if v := d.Get("kms_encrypted_password").(string); v != "" {
kmsService := KmsService{client}
decryptResp, err := kmsService.Decrypt(v, d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return WrapError(err)
}
password = decryptResp
}
}
keyPair := d.Get("key_name").(string)
args := &cs.ScaleOutKubernetesClusterRequest{
KeyPair: keyPair,
LoginPassword: password,
ImageId: d.Get("image_id").(string),
UserData: d.Get("user_data").(string),
Count: int64(newValue) - int64(oldValue),
WorkerVSwitchIds: expandStringList(d.Get("worker_vswitch_ids").([]interface{})),
WorkerInstanceTypes: expandStringList(d.Get("worker_instance_types").([]interface{})),
}
if v := d.Get("user_data").(string); v != "" {
_, base64DecodeError := base64.StdEncoding.DecodeString(v)
if base64DecodeError == nil {
args.UserData = v
} else {
args.UserData = base64.StdEncoding.EncodeToString([]byte(v))
}
}
if v, ok := d.GetOk("worker_instance_charge_type"); ok {
args.WorkerInstanceChargeType = v.(string)
if args.WorkerInstanceChargeType == string(PrePaid) {
args.WorkerAutoRenew = d.Get("worker_auto_renew").(bool)
args.WorkerAutoRenewPeriod = d.Get("worker_auto_renew_period").(int)
args.WorkerPeriod = d.Get("worker_period").(int)
args.WorkerPeriodUnit = d.Get("worker_period_unit").(string)
}
}
if v, ok := d.GetOk("worker_disk_category"); ok {
args.WorkerSystemDiskCategory = aliyungoecs.DiskCategory(v.(string))
}
if v, ok := d.GetOk("worker_disk_size"); ok {
args.WorkerSystemDiskSize = int64(v.(int))
}
if v, ok := d.GetOk("worker_disk_snapshot_policy_id"); ok {
args.WorkerSnapshotPolicyId = v.(string)
}
if v, ok := d.GetOk("worker_disk_performance_level"); ok {
args.WorkerSystemDiskPerformanceLevel = v.(string)
}
if dds, ok := d.GetOk("worker_data_disks"); ok {
disks := dds.([]interface{})
createDataDisks := make([]cs.DataDisk, 0, len(disks))
for _, e := range disks {
pack := e.(map[string]interface{})
dataDisk := cs.DataDisk{
Size: pack["size"].(string),
DiskName: pack["name"].(string),
Category: pack["category"].(string),
Device: pack["device"].(string),
AutoSnapshotPolicyId: pack["auto_snapshot_policy_id"].(string),
KMSKeyId: pack["kms_key_id"].(string),
Encrypted: pack["encrypted"].(string),
PerformanceLevel: pack["performance_level"].(string),
}
createDataDisks = append(createDataDisks, dataDisk)
}
args.WorkerDataDisks = createDataDisks
}
if _, ok := d.GetOk("tags"); ok {
if tags, err := ConvertCsTags(d); err == nil {
args.Tags = tags
}
d.SetPartial("tags")
}
if d.HasChange("taints") && !d.IsNewResource() {
args.Taints = expandKubernetesTaintsConfig(d.Get("taints").([]interface{}))
}
if d.HasChange("runtime") && !d.IsNewResource() {
args.Runtime = expandKubernetesRuntimeConfig(d.Get("runtime").(map[string]interface{}))
}
if d.HasChange("rds_instances") && !d.IsNewResource() {
args.RdsInstances = expandStringList(d.Get("rds_instances").([]interface{}))
}
if d.HasChange("cpu_policy") && !d.IsNewResource() {
args.CpuPolicy = d.Get("cpu_policy").(string)
}
if d.HasChange("install_cloud_monitor") && !d.IsNewResource() {
args.CloudMonitorFlags = d.Get("install_cloud_monitor").(bool)
}
if d.HasChange("image_id") && !d.IsNewResource() {
args.ImageId = d.Get("image_id").(string)
}
var resoponse interface{}
if err := invoker.Run(func() error {
var err error
resoponse, err = client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
resp, err := csClient.ScaleOutKubernetesCluster(d.Id(), args)
return resp, err
})
return err
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "ResizeKubernetesCluster", DenverdinoAliyungo)
}
if debugOn() {
resizeRequestMap := make(map[string]interface{})
resizeRequestMap["ClusterId"] = d.Id()
resizeRequestMap["Args"] = args
addDebug("ResizeKubernetesCluster", resoponse, resizeRequestMap)
}
stateConf := BuildStateConf([]string{"scaling"}, []string{"running"}, d.Timeout(schema.TimeoutUpdate), 10*time.Second, csService.CsKubernetesInstanceStateRefreshFunc(d.Id(), []string{"deleting", "failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("worker_number")
d.SetPartial("worker_data_disks")
d.SetPartial("worker_disk_category")
d.SetPartial("worker_disk_size")
d.SetPartial("worker_disk_snapshot_policy_id")
d.SetPartial("worker_disk_performance_level")
}
// remove cluster nodes.
if newValue < oldValue {
nodes, err := removeKubernetesNodes(d, meta)
if err != nil {
return WrapErrorf(fmt.Errorf("node removed failed"), "node:%++v, err:%++v", nodes, err)
}
}
}
// modify cluster name
if !d.IsNewResource() && (d.HasChange("name") || d.HasChange("name_prefix")) {
var clusterName string
if v, ok := d.GetOk("name"); ok {
clusterName = v.(string)
} else {
clusterName = resource.PrefixedUniqueId(d.Get("name_prefix").(string))
}
var requestInfo *cs.Client
var response interface{}
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
return nil, csClient.ModifyClusterName(d.Id(), clusterName)
})
response = raw
return err
}); err != nil && !IsExpectedErrors(err, []string{"ErrorClusterNameAlreadyExist"}) {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "ModifyClusterName", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["ClusterId"] = d.Id()
requestMap["ClusterName"] = clusterName
addDebug("ModifyClusterName", response, requestInfo, requestMap)
}
d.SetPartial("name")
d.SetPartial("name_prefix")
}
// modify cluster deletion protection
if !d.IsNewResource() && d.HasChange("deletion_protection") {
var requestInfo cs.ModifyClusterArgs
if v, ok := d.GetOk("deletion_protection"); ok {
requestInfo.DeletionProtection = v.(bool)
}
var response interface{}
if err := invoker.Run(func() error {
_, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
return nil, csClient.ModifyCluster(d.Id(), &requestInfo)
})
return err
}); err != nil && !IsExpectedErrors(err, []string{"ErrorModifyDeletionProtectionFailed"}) {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "ModifyCluster", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["ClusterId"] = d.Id()
requestMap["deletion_protection"] = requestInfo.DeletionProtection
addDebug("ModifyCluster", response, requestInfo, requestMap)
}
d.SetPartial("deletion_protection")
}
// modify cluster maintenance window
if !d.IsNewResource() && d.HasChange("maintenance_window") {
var mw cs.MaintenanceWindow
if v := d.Get("maintenance_window").([]interface{}); len(v) > 0 {
mw = expandMaintenanceWindowConfig(v)
}
_ = modifyMaintenanceWindow(d, meta, mw)
}
// modify cluster tag
if d.HasChange("tags") {
err := updateKubernetesClusterTag(d, meta)
if err != nil {
return WrapErrorf(err, ResponseCodeMsg, d.Id(), "ModifyClusterTags", AlibabaCloudSdkGoERROR)
}
}
// migrate cluster to pro form standard
if d.HasChange("cluster_spec") {
oldValue, newValue := d.GetChange("cluster_spec")
o, ok := oldValue.(string)
if ok != true {
return WrapErrorf(fmt.Errorf("cluster_spec old value can not be parsed"), "parseError %d", oldValue)
}
n, ok := newValue.(string)
if ok != true {
return WrapErrorf(fmt.Errorf("cluster_pec new value can not be parsed"), "parseError %d", newValue)
}
if o == "ack.standard" && strings.Contains(n, "pro") {
err := migrateAlicloudManagedKubernetesCluster(d, meta)
if err != nil {
return WrapErrorf(err, ResponseCodeMsg, d.Id(), "MigrateCluster", AlibabaCloudSdkGoERROR)
}
}
}
d.SetPartial("tags")
UpgradeAlicloudKubernetesCluster(d, meta)
d.Partial(false)
return resourceAlicloudCSKubernetesRead(d, meta)
}
func resourceAlicloudCSKubernetesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
csService := CsService{client}
invoker := NewInvoker()
object, err := csService.DescribeCsKubernetes(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", object.Name)
d.Set("vpc_id", object.VpcId)
d.Set("security_group_id", object.SecurityGroupId)
d.Set("version", object.CurrentVersion)
d.Set("worker_ram_role_name", object.WorkerRamRoleName)
d.Set("resource_group_id", object.ResourceGroupId)
d.Set("cluster_spec", object.ClusterSpec)
d.Set("deletion_protection", object.DeletionProtection)
if err := d.Set("tags", flattenTagsConfig(object.Tags)); err != nil {
return WrapError(err)
}
if d.Get("os_type") == "" {
d.Set("os_type", "Linux")
}
if d.Get("platform") == "" {
d.Set("platform", "CentOS")
}
if d.Get("node_port_range") == "" {
d.Set("node_port_range", "30000-32767")
}
if d.Get("cluster_domain") == "" {
d.Set("cluster_domain", "cluster.local")
}
if d.Get("load_balancer_spec") == "" {
d.Set("load_balancer_spec", "slb.s1.small")
}
// d.Set("os_type", object.OSType)
// d.Set("platform", object.Platform)
// d.Set("timezone", object.TimeZone)
// d.Set("cluster_domain", object.ClusterDomin)
// d.Set("custom_san",object.CustomSAN)
// d.Set("runtime", object.Runtime)
// d.Set("taints", object.Taits)
// d.Set("rds_instances", object.RdsInstances)
// d.Set("node_port_range", object.NodePortRange)
d.Set("maintenance_window", flattenMaintenanceWindowConfig(&object.MaintenanceWindow))
var masterNodes []map[string]interface{}
var workerNodes []map[string]interface{}
var defaultNodePoolId string
var nodePoolDetails interface{}
// get the default nodepool id
if err := invoker.Run(func() error {
var err error
nodePoolDetails, err = client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
nodePools, err := csClient.DescribeClusterNodePools(d.Id())
return *nodePools, err
})
return err
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DescribeClusterNodePools", DenverdinoAliyungo)
}
for _, v := range nodePoolDetails.([]cs.NodePoolDetail) {
if v.BasicNodePool.NodePoolInfo.Name == "default-nodepool" {
defaultNodePoolId = v.BasicNodePool.NodePoolInfo.NodePoolId
}
}
pageNumber := 1
for {
if defaultNodePoolId == "" {
break
}
var result []cs.KubernetesNodeType
var pagination *cs.PaginationResult
var requestInfo *cs.Client
var response interface{}
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
nodes, paginationResult, err := csClient.GetKubernetesClusterNodes(d.Id(), common.Pagination{PageNumber: pageNumber, PageSize: PageSizeLarge}, defaultNodePoolId)
return []interface{}{nodes, paginationResult}, err
})
response = raw
return err
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "GetKubernetesClusterNodes", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["ClusterId"] = d.Id()
requestMap["Pagination"] = common.Pagination{PageNumber: pageNumber, PageSize: PageSizeLarge}
addDebug("GetKubernetesClusterNodes", response, requestInfo, requestMap)
}
result, _ = response.([]interface{})[0].([]cs.KubernetesNodeType)
pagination, _ = response.([]interface{})[1].(*cs.PaginationResult)
if pageNumber == 1 && (len(result) == 0 || result[0].InstanceId == "") {
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
nodes, _, err := csClient.GetKubernetesClusterNodes(d.Id(), common.Pagination{PageNumber: pageNumber, PageSize: PageSizeLarge}, defaultNodePoolId)
return nodes, err
})
response = raw
return err
}); err != nil {
return resource.NonRetryableError(err)
}
tmp, _ := response.([]cs.KubernetesNodeType)
if len(tmp) > 0 && tmp[0].InstanceId != "" {
result = tmp
}
for _, stableState := range cs.NodeStableClusterState {
// If cluster is in NodeStableClusteState, node list will not change
if object.State == string(stableState) {
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["ClusterId"] = d.Id()
requestMap["Pagination"] = common.Pagination{PageNumber: pageNumber, PageSize: PageSizeLarge}
addDebug("GetKubernetesClusterNodes", response, requestInfo, requestMap)
}
return nil
}
}
time.Sleep(5 * time.Second)
return resource.RetryableError(Error("[ERROR] There is no any nodes in kubernetes cluster %s.", d.Id()))
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "GetKubernetesClusterNodes", DenverdinoAliyungo)
}
}
if d.Get("exclude_autoscaler_nodes") != nil && d.Get("exclude_autoscaler_nodes").(bool) {
result, err = knockOffAutoScalerNodes(result, meta)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "GetKubernetesClusterNodes", AlibabaCloudSdkGoERROR)
}
}
for _, node := range result {
mapping := map[string]interface{}{
"id": node.InstanceId,
"name": node.InstanceName,
"private_ip": node.IpAddress[0],
}
if node.InstanceRole == "Master" {
masterNodes = append(masterNodes, mapping)
} else {
workerNodes = append(workerNodes, mapping)
}
}
if len(result) < pagination.PageSize {
break
}
pageNumber += 1
}
d.Set("master_nodes", masterNodes)
d.Set("worker_nodes", workerNodes)
d.Set("worker_number", int64(len(workerNodes)))
// Get slb information and set connect
connection := make(map[string]string)
masterURL := object.MasterURL
endPoint := make(map[string]string)
_ = json.Unmarshal([]byte(masterURL), &endPoint)
connection["api_server_internet"] = endPoint["api_server_endpoint"]
connection["api_server_intranet"] = endPoint["intranet_api_server_endpoint"]
if endPoint["api_server_endpoint"] != "" {
connection["master_public_ip"] = strings.Split(strings.Split(endPoint["api_server_endpoint"], ":")[1], "/")[2]
}
if object.Profile != EdgeProfile {
connection["service_domain"] = fmt.Sprintf("*.%s.%s.alicontainer.com", d.Id(), object.RegionId)
}
d.Set("connections", connection)
d.Set("slb_internet", connection["master_public_ip"])
if endPoint["intranet_api_server_endpoint"] != "" {
d.Set("slb_intranet", strings.Split(strings.Split(endPoint["intranet_api_server_endpoint"], ":")[1], "/")[2])
}
// set nat gateway
natRequest := vpc.CreateDescribeNatGatewaysRequest()
natRequest.VpcId = object.VpcId
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeNatGateways(natRequest)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), natRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(natRequest.GetActionName(), raw, natRequest.RpcRequest, natRequest)
nat, _ := raw.(*vpc.DescribeNatGatewaysResponse)
if nat != nil && len(nat.NatGateways.NatGateway) > 0 {
d.Set("nat_gateway_id", nat.NatGateways.NatGateway[0].NatGatewayId)
}
// get cluster conn certs
// If the cluster is failed, there is no need to get cluster certs
if object.State == "failed" {
return nil
}
var requestInfo *cs.Client
var response interface{}
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
return csClient.GetClusterCerts(d.Id())
})
response = raw
return err
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "GetClusterCerts", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["Id"] = d.Id()
addDebug("GetClusterCerts", response, requestInfo, requestMap)
}
cert, _ := response.(cs.ClusterCerts)
// write cluster conn authority to local file
if ce, ok := d.GetOk("client_cert"); ok && ce.(string) != "" {
if err := writeToFile(ce.(string), cert.Cert); err != nil {
return WrapError(err)
}
}
if key, ok := d.GetOk("client_key"); ok && key.(string) != "" {
if err := writeToFile(key.(string), cert.Key); err != nil {
return WrapError(err)
}
}
if ca, ok := d.GetOk("cluster_ca_cert"); ok && ca.(string) != "" {
if err := writeToFile(ca.(string), cert.CA); err != nil {
return WrapError(err)
}
}
var config *cs.ClusterConfig
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
return csClient.DescribeClusterUserConfig(d.Id(), false)
})
response = raw
return err
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "GetClusterConfig", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["Id"] = d.Id()
addDebug("GetClusterConfig", response, requestInfo, requestMap)
}
config, _ = response.(*cs.ClusterConfig)
if file, ok := d.GetOk("kube_config"); ok && file.(string) != "" {
if err := writeToFile(file.(string), config.Config); err != nil {
return WrapError(err)
}
}
// write cluster conn authority to tf state
if err := d.Set("certificate_authority", flattenAlicloudCSCertificate(config)); err != nil {
return fmt.Errorf("error setting certificate_authority: %s", err)
}
return nil
}
func resourceAlicloudCSKubernetesDelete(d *schema.ResourceData, meta interface{}) error {
csService := CsService{meta.(*connectivity.AliyunClient)}
client, err := meta.(*connectivity.AliyunClient).NewRoaCsClient()
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceName, "InitializeClient", err)
}
args := &roacs.DeleteClusterRequest{}
if v := d.Get("retain_resources"); len(v.([]interface{})) > 0 {
args.RetainResources = tea.StringSlice(expandStringList(v.([]interface{})))
}
_, err = client.DeleteCluster(tea.String(d.Id()), args)
if err != nil {
if IsExpectedErrors(err, []string{"ErrorClusterNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, ResourceName, "DeleteCluster", AliyunTablestoreGoSdk)
}
stateConf := BuildStateConf([]string{"running", "deleting"}, []string{}, d.Timeout(schema.TimeoutDelete), 10*time.Second, csService.CsKubernetesInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
func buildKubernetesArgs(d *schema.ResourceData, meta interface{}) (*cs.DelicatedKubernetesClusterCreationRequest, error) {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var vswitchID string
if list := expandStringList(d.Get("worker_vswitch_ids").([]interface{})); len(list) > 0 {
vswitchID = list[0]
} else {
vswitchID = ""
}
var vpcId string
if vswitchID != "" {
vsw, err := vpcService.DescribeVSwitch(vswitchID)
if err != nil {
return nil, err
}
vpcId = vsw.VpcId
}
var clusterName string
if v, ok := d.GetOk("name"); ok {
clusterName = v.(string)
} else {
clusterName = resource.PrefixedUniqueId(d.Get("name_prefix").(string))
}
addons := make([]cs.Addon, 0)
if v, ok := d.GetOk("addons"); ok {
all, ok := v.([]interface{})
if ok {
for _, a := range all {
addon, ok := a.(map[string]interface{})
if ok {
addons = append(addons, cs.Addon{
Name: addon["name"].(string),
Config: addon["config"].(string),
Disabled: addon["disabled"].(bool),
})
}
}
}
}
var apiAudiences string
if d.Get("api_audiences") != nil {
if list := expandStringList(d.Get("api_audiences").([]interface{})); len(list) > 0 {
apiAudiences = strings.Join(list, ",")
}
}
creationArgs := &cs.DelicatedKubernetesClusterCreationRequest{
ClusterArgs: cs.ClusterArgs{
DisableRollback: true,
Name: clusterName,
DeletionProtection: d.Get("deletion_protection").(bool),
VpcId: vpcId,
// the params below is ok to be empty
KubernetesVersion: d.Get("version").(string),
NodeCidrMask: strconv.Itoa(d.Get("node_cidr_mask").(int)),
KeyPair: d.Get("key_name").(string),
ServiceCidr: d.Get("service_cidr").(string),
CloudMonitorFlags: d.Get("install_cloud_monitor").(bool),
SecurityGroupId: d.Get("security_group_id").(string),
IsEnterpriseSecurityGroup: d.Get("is_enterprise_security_group").(bool),
EndpointPublicAccess: d.Get("slb_internet_enabled").(bool),
SnatEntry: d.Get("new_nat_gateway").(bool),
Addons: addons,
ApiAudiences: apiAudiences,
},
}
if lbSpec, ok := d.GetOk("load_balancer_spec"); ok {
creationArgs.LoadBalancerSpec = lbSpec.(string)
}
if osType, ok := d.GetOk("os_type"); ok {
creationArgs.OsType = osType.(string)
}
if platform, ok := d.GetOk("platform"); ok {
creationArgs.Platform = platform.(string)
}
if timezone, ok := d.GetOk("timezone"); ok {
creationArgs.Timezone = timezone.(string)
}
if clusterDomain, ok := d.GetOk("cluster_domain"); ok {
creationArgs.ClusterDomain = clusterDomain.(string)
}
if customSan, ok := d.GetOk("custom_san"); ok {
creationArgs.CustomSAN = customSan.(string)
}
if imageId, ok := d.GetOk("image_id"); ok {
creationArgs.ClusterArgs.ImageId = imageId.(string)
}
if nodeNameMode, ok := d.GetOk("node_name_mode"); ok {
creationArgs.ClusterArgs.NodeNameMode = nodeNameMode.(string)
}
if saIssuer, ok := d.GetOk("service_account_issuer"); ok {
creationArgs.ClusterArgs.ServiceAccountIssuer = saIssuer.(string)
}
if resourceGroupId, ok := d.GetOk("resource_group_id"); ok {
creationArgs.ClusterArgs.ResourceGroupId = resourceGroupId.(string)
}
if v := d.Get("user_data").(string); v != "" {
_, base64DecodeError := base64.StdEncoding.DecodeString(v)
if base64DecodeError == nil {
creationArgs.UserData = v
} else {
creationArgs.UserData = base64.StdEncoding.EncodeToString([]byte(v))
}
}
if _, ok := d.GetOk("pod_vswitch_ids"); ok {
creationArgs.PodVswitchIds = expandStringList(d.Get("pod_vswitch_ids").([]interface{}))
} else {
creationArgs.ContainerCidr = d.Get("pod_cidr").(string)
}
if password := d.Get("password").(string); password == "" {
if v, ok := d.GetOk("kms_encrypted_password"); ok && v != "" {
kmsService := KmsService{client}
decryptResp, err := kmsService.Decrypt(v.(string), d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return nil, WrapError(err)
}
password = decryptResp
}
creationArgs.LoginPassword = password
} else {
creationArgs.LoginPassword = password
}
if tags, err := ConvertCsTags(d); err == nil {
creationArgs.Tags = tags
}
// CA default is empty
if userCa, ok := d.GetOk("user_ca"); ok {
userCaContent, err := loadFileContent(userCa.(string))
if err != nil {
return nil, fmt.Errorf("reading user_ca file failed %s", err)
}
creationArgs.UserCa = string(userCaContent)
}
// set proxy mode and default is ipvs
if proxyMode := d.Get("proxy_mode").(string); proxyMode != "" {
creationArgs.ProxyMode = cs.ProxyMode(proxyMode)
} else {
creationArgs.ProxyMode = cs.ProxyMode(cs.IPVS)
}
// dedicated kubernetes must provide master_vswitch_ids
if _, ok := d.GetOk("master_vswitch_ids"); ok {
creationArgs.MasterArgs = cs.MasterArgs{
MasterCount: len(d.Get("master_vswitch_ids").([]interface{})),
MasterVSwitchIds: expandStringList(d.Get("master_vswitch_ids").([]interface{})),
MasterInstanceTypes: expandStringList(d.Get("master_instance_types").([]interface{})),
MasterSystemDiskCategory: aliyungoecs.DiskCategory(d.Get("master_disk_category").(string)),
MasterSystemDiskSize: int64(d.Get("master_disk_size").(int)),
// TODO support other params
}
}
if v, ok := d.GetOk("master_disk_snapshot_policy_id"); ok && v != "" {
creationArgs.MasterArgs.MasterSnapshotPolicyId = v.(string)
}
if v, ok := d.GetOk("master_disk_performance_level"); ok && v != "" {
creationArgs.MasterArgs.MasterSystemDiskPerformanceLevel = v.(string)
}
if v, ok := d.GetOk("master_instance_charge_type"); ok {
creationArgs.MasterInstanceChargeType = v.(string)
if creationArgs.MasterInstanceChargeType == string(PrePaid) {
creationArgs.MasterAutoRenew = d.Get("master_auto_renew").(bool)
creationArgs.MasterAutoRenewPeriod = d.Get("master_auto_renew_period").(int)
creationArgs.MasterPeriod = d.Get("master_period").(int)
creationArgs.MasterPeriodUnit = d.Get("master_period_unit").(string)
}
}
var workerDiskSize int64
if d.Get("worker_disk_size") != nil {
workerDiskSize = int64(d.Get("worker_disk_size").(int))
}
if v, ok := d.GetOk("worker_vswitch_ids"); ok {
creationArgs.WorkerArgs.WorkerVSwitchIds = expandStringList(v.([]interface{}))
}
if v, ok := d.GetOk("worker_instance_types"); ok {
creationArgs.WorkerArgs.WorkerInstanceTypes = expandStringList(v.([]interface{}))
}
if v, ok := d.GetOk("worker_number"); ok {
creationArgs.WorkerArgs.NumOfNodes = int64(v.(int))
}
if v, ok := d.GetOk("worker_disk_category"); ok {
creationArgs.WorkerArgs.WorkerSystemDiskCategory = aliyungoecs.DiskCategory(v.(string))
}
if v, ok := d.GetOk("worker_disk_snapshot_policy_id"); ok && v != "" {
creationArgs.WorkerArgs.WorkerSnapshotPolicyId = v.(string)
}
if v, ok := d.GetOk("worker_disk_performance_level"); ok && v != "" {
creationArgs.WorkerArgs.WorkerSystemDiskPerformanceLevel = v.(string)
}
if dds, ok := d.GetOk("worker_data_disks"); ok {
disks := dds.([]interface{})
createDataDisks := make([]cs.DataDisk, 0, len(disks))
for _, e := range disks {
pack := e.(map[string]interface{})
dataDisk := cs.DataDisk{
Size: pack["size"].(string),
DiskName: pack["name"].(string),
Category: pack["category"].(string),
Device: pack["device"].(string),
AutoSnapshotPolicyId: pack["auto_snapshot_policy_id"].(string),
KMSKeyId: pack["kms_key_id"].(string),
Encrypted: pack["encrypted"].(string),
PerformanceLevel: pack["performance_level"].(string),
}
createDataDisks = append(createDataDisks, dataDisk)
}
creationArgs.WorkerDataDisks = createDataDisks
}
if workerDiskSize != 0 {
creationArgs.WorkerArgs.WorkerSystemDiskSize = workerDiskSize
}
if v, ok := d.GetOk("worker_instance_charge_type"); ok {
creationArgs.WorkerInstanceChargeType = v.(string)
if creationArgs.WorkerInstanceChargeType == string(PrePaid) {
creationArgs.WorkerAutoRenew = d.Get("worker_auto_renew").(bool)
creationArgs.WorkerAutoRenewPeriod = d.Get("worker_auto_renew_period").(int)
creationArgs.WorkerPeriod = d.Get("worker_period").(int)
creationArgs.WorkerPeriodUnit = d.Get("worker_period_unit").(string)
}
}
if v, ok := d.GetOk("cluster_spec"); ok {
creationArgs.ClusterSpec = v.(string)
}
if encryptionProviderKey, ok := d.GetOk("encryption_provider_key"); ok {
creationArgs.EncryptionProviderKey = encryptionProviderKey.(string)
}
if rdsInstances, ok := d.GetOk("rds_instances"); ok {
creationArgs.RdsInstances = expandStringList(rdsInstances.([]interface{}))
}
if nodePortRange, ok := d.GetOk("node_port_range"); ok {
creationArgs.NodePortRange = nodePortRange.(string)
}
if runtime, ok := d.GetOk("runtime"); ok {
if v := runtime.(map[string]interface{}); len(v) > 0 {
creationArgs.Runtime = expandKubernetesRuntimeConfig(v)
}
}
if taints, ok := d.GetOk("taints"); ok {
if v := taints.([]interface{}); len(v) > 0 {
creationArgs.Taints = expandKubernetesTaintsConfig(v)
}
}
// Cluster maintenance window. Effective only in the professional managed cluster
if v, ok := d.GetOk("maintenance_window"); ok {
creationArgs.MaintenanceWindow = expandMaintenanceWindowConfig(v.([]interface{}))
}
// Configure control plane log. Effective only in the professional managed cluster
if v, ok := d.GetOk("control_plane_log_components"); ok {
creationArgs.ControlplaneComponents = expandStringList(v.([]interface{}))
// ttl default is 30 days
creationArgs.ControlplaneLogTTL = "30"
}
if v, ok := d.GetOk("control_plane_log_ttl"); ok {
creationArgs.ControlplaneLogTTL = v.(string)
}
if v, ok := d.GetOk("control_plane_log_project"); ok {
creationArgs.ControlplaneLogProject = v.(string)
}
return creationArgs, nil
}
func knockOffAutoScalerNodes(nodes []cs.KubernetesNodeType, meta interface{}) ([]cs.KubernetesNodeType, error) {
log.Printf("[DEBUG] start to knock off auto scaler nodes %++v\n", nodes)
client := meta.(*connectivity.AliyunClient)
realNodesMap := make(map[string]ecs.Instance)
result := make([]cs.KubernetesNodeType, 0)
instanceIds := make([]interface{}, 0)
if len(nodes) == 0 {
return result, nil
}
for _, node := range nodes {
instanceIds = append(instanceIds, node.InstanceId)
}
request := ecs.CreateDescribeInstancesRequest()
request.RegionId = client.RegionId
request.PageSize = requests.NewInteger(len(nodes))
request.InstanceIds = convertListToJsonString(instanceIds)
// get all the nodes in use
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeInstances(request)
})
if err != nil {
return result, WrapErrorf(err, DataDefaultErrorMsg, "alicloud_instances", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ecs.DescribeInstancesResponse)
// filter out all autoscaler nodes
for _, instance := range response.Instances.Instance {
flags := false
for _, v := range instance.Tags.Tag {
if v.TagKey == defaultScalingGroupTag && v.TagValue == "true" {
flags = true
}
}
if flags != true {
realNodesMap[instance.InstanceId] = instance
}
}
// get the target node list
for _, node := range nodes {
if _, ok := realNodesMap[node.InstanceId]; ok {
result = append(result, node)
}
}
return result, nil
}
func expandKubernetesTaintsConfig(l []interface{}) []cs.Taint {
config := []cs.Taint{}
for _, v := range l {
if m, ok := v.(map[string]interface{}); ok {
config = append(config, cs.Taint{
Key: m["key"].(string),
Value: m["value"].(string),
Effect: cs.Effect(m["effect"].(string)),
})
}
}
return config
}
func expandKubernetesRuntimeConfig(l map[string]interface{}) cs.Runtime {
config := cs.Runtime{}
if v, ok := l["name"]; ok && v != "" {
config.Name = v.(string)
}
if v, ok := l["version"]; ok && v != "" {
config.Version = v.(string)
}
return config
}
func removeKubernetesNodes(d *schema.ResourceData, meta interface{}) ([]string, error) {
client := meta.(*connectivity.AliyunClient)
csService := CsService{client}
invoker := NewInvoker()
// remove nodes count
o, n := d.GetChange("worker_number")
count := o.(int) - n.(int)
var result []cs.KubernetesNodeType
var response interface{}
var defaultNodePoolId string
// get the default nodepool id
if err := invoker.Run(func() error {
var err error
response, err = client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
nodePools, err := csClient.DescribeClusterNodePools(d.Id())
return *nodePools, err
})
return err
}); err != nil {
return nil, WrapErrorf(err, DefaultErrorMsg, d.Id(), "GetKubernetesClusterNodes", DenverdinoAliyungo)
}
for _, v := range response.([]cs.NodePoolDetail) {
if v.BasicNodePool.NodePoolInfo.Name == "default-nodepool" {
defaultNodePoolId = v.BasicNodePool.NodePoolInfo.NodePoolId
}
}
// list all nodes of default nodepool
if err := invoker.Run(func() error {
var err error
response, err = client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
nodes, _, err := csClient.GetKubernetesClusterNodes(d.Id(), common.Pagination{PageNumber: 1, PageSize: PageSizeLarge}, defaultNodePoolId)
return nodes, err
})
return err
}); err != nil {
return nil, WrapErrorf(err, DefaultErrorMsg, d.Id(), "GetKubernetesClusterNodes", DenverdinoAliyungo)
}
ret := response.([]cs.KubernetesNodeType)
// filter out autoscaler nodes
var err error
result, err = knockOffAutoScalerNodes(ret, meta)
if err != nil {
return nil, WrapErrorf(err, DefaultErrorMsg, d.Id(), "GetKubernetesClusterNodes", AlibabaCloudSdkGoERROR)
}
// filter out Master nodes
var allNodeName []string
var allHostName []string
for _, value := range result {
if value.InstanceRole == "Worker" {
allNodeName = append(allNodeName, value.NodeName)
allHostName = append(allHostName, value.InstanceId)
}
}
// remove nodes
removeNodesName := allNodeName[:count]
removeNodesArgs := &cs.DeleteKubernetesClusterNodesRequest{
Nodes: removeNodesName,
ReleaseNode: true,
DrainNode: false,
}
if err := invoker.Run(func() error {
var err error
response, err = client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
resp, err := csClient.DeleteKubernetesClusterNodes(d.Id(), removeNodesArgs)
return resp, err
})
return err
}); err != nil {
return nil, WrapErrorf(err, DefaultErrorMsg, d.Id(), "RemoveClusterNodes", DenverdinoAliyungo)
}
stateConf := BuildStateConf([]string{"removing"}, []string{"running"}, d.Timeout(schema.TimeoutUpdate), 20*time.Second, csService.CsKubernetesInstanceStateRefreshFunc(d.Id(), []string{"deleting", "failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return nil, WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("worker_number")
return allHostName[len(allHostName)-count:], nil
}
func flattenAlicloudCSCertificate(certificate *cs.ClusterConfig) map[string]string {
if certificate == nil {
return map[string]string{}
}
kubeConfig := make(map[string]interface{})
_ = yaml.Unmarshal([]byte(certificate.Config), &kubeConfig)
m := make(map[string]string)
m["cluster_cert"] = kubeConfig["clusters"].([]interface{})[0].(map[interface{}]interface{})["cluster"].(map[interface{}]interface{})["certificate-authority-data"].(string)
m["client_cert"] = kubeConfig["users"].([]interface{})[0].(map[interface{}]interface{})["user"].(map[interface{}]interface{})["client-certificate-data"].(string)
m["client_key"] = kubeConfig["users"].([]interface{})[0].(map[interface{}]interface{})["user"].(map[interface{}]interface{})["client-key-data"].(string)
return m
}
// ACK pro maintenance window
func expandMaintenanceWindowConfig(l []interface{}) (config cs.MaintenanceWindow) {
if len(l) == 0 || l[0] == nil {
return
}
m := l[0].(map[string]interface{})
if v, ok := m["enable"]; ok {
config.Enable = v.(bool)
}
if v, ok := m["maintenance_time"]; ok && v != "" {
config.MaintenanceTime = cs.MaintenanceTime(v.(string))
}
if v, ok := m["duration"]; ok && v != "" {
config.Duration = v.(string)
}
if v, ok := m["weekly_period"]; ok && v != "" {
config.WeeklyPeriod = cs.WeeklyPeriod(v.(string))
}
return
}
func flattenMaintenanceWindowConfig(config *cs.MaintenanceWindow) (m []map[string]interface{}) {
if config == nil {
return []map[string]interface{}{}
}
m = append(m, map[string]interface{}{
"enable": config.Enable,
"maintenance_time": config.MaintenanceTime,
"duration": config.Duration,
"weekly_period": config.WeeklyPeriod,
})
return
}
func modifyMaintenanceWindow(d *schema.ResourceData, meta interface{}, mw cs.MaintenanceWindow) error {
client := meta.(*connectivity.AliyunClient)
invoker := NewInvoker()
var response interface{}
var requestInfo cs.ModifyClusterArgs
requestInfo.MaintenanceWindow = mw
if err := invoker.Run(func() error {
_, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
return nil, csClient.ModifyCluster(d.Id(), &requestInfo)
})
return err
}); err != nil && !IsExpectedErrors(err, []string{"ErrorModifyMaintenanceWindowFailed"}) {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "ModifyCluster", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["ClusterId"] = d.Id()
requestMap["maintenance_window"] = requestInfo.DeletionProtection
addDebug("ModifyCluster", response, requestInfo, requestMap)
}
d.SetPartial("maintenance_window")
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
const ResourceAlicloudCSKubernetesAddon = "resourceAlicloudCSKubernetesAddon"
func resourceAlicloudCSKubernetesAddon() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCSKubernetesAddonCreate,
Read: resourceAlicloudCSKubernetesAddonRead,
Update: resourceAlicloudCSKubernetesAddonUpdate,
Delete: resourceAlicloudCSKubernetesAddonDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"cluster_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"version": {
Type: schema.TypeString,
Required: true,
},
"next_version": {
Type: schema.TypeString,
Computed: true,
},
"can_upgrade": {
Type: schema.TypeBool,
Computed: true,
},
"required": {
Type: schema.TypeBool,
Computed: true,
},
},
}
}
func resourceAlicloudCSKubernetesAddonRead(d *schema.ResourceData, meta interface{}) error {
client, err := meta.(*connectivity.AliyunClient).NewRoaCsClient()
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceAlicloudCSKubernetesAddon, "InitializeClient", err)
}
csClient := CsClient{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
addon, err := csClient.DescribeCsKubernetesAddon(d.Id())
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceAlicloudCSKubernetesAddon, "DescribeCsKubernetesAddon", err)
}
d.Set("cluster_id", parts[0])
d.Set("name", addon.ComponentName)
d.Set("version", addon.Version)
d.Set("next_version", addon.NextVersion)
d.Set("can_upgrade", addon.CanUpgrade)
d.Set("required", addon.Required)
return nil
}
func resourceAlicloudCSKubernetesAddonCreate(d *schema.ResourceData, meta interface{}) error {
clusterId := d.Get("cluster_id").(string)
name := d.Get("name").(string)
version := d.Get("version").(string)
client, err := meta.(*connectivity.AliyunClient).NewRoaCsClient()
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceAlicloudCSKubernetesAddon, "InitializeClient", err)
}
csClient := CsClient{client}
status, err := csClient.DescribeCsKubernetesAddonStatus(clusterId, name)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceAlicloudCSKubernetesAddon, "DescribeCsKubernetesAddonStatus", err)
}
changed := false
if status.Version == "" {
// Addon not installed
changed = true
err := csClient.installAddon(d)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceAlicloudCSKubernetesAddon, "installAddon", err)
}
} else if status.Version != "" && status.Version != version {
// Addon has been installed
changed = true
err := csClient.upgradeAddon(d)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceAlicloudCSKubernetesAddon, "upgradeAddon", err)
}
}
d.SetId(fmt.Sprintf("%s%s%s", clusterId, COLON_SEPARATED, name))
stateConf := BuildStateConf([]string{"running", "Upgrading", "Pause"}, []string{"Success"}, d.Timeout(schema.TimeoutCreate), 10*time.Second, csClient.CsKubernetesAddonStateRefreshFunc(clusterId, name, []string{"Failed", "Canceled"}))
if changed {
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceAlicloudCSKubernetesAddon, "WaitForSuccessAfterCreate", d.Id())
}
}
return resourceAlicloudCSKubernetesAddonRead(d, meta)
}
func resourceAlicloudCSKubernetesAddonUpdate(d *schema.ResourceData, meta interface{}) error {
client, err := meta.(*connectivity.AliyunClient).NewRoaCsClient()
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceAlicloudCSKubernetesAddon, "InitializeClient", err)
}
csClient := CsClient{client}
if d.HasChange("version") {
clusterId := d.Get("cluster_id").(string)
name := d.Get("name").(string)
err := csClient.upgradeAddon(d)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceAlicloudCSKubernetesAddon, "upgradeAddon", err)
}
stateConf := BuildStateConf([]string{"running", "Upgrading", "Pause"}, []string{"Success"}, d.Timeout(schema.TimeoutUpdate), 10*time.Second, csClient.CsKubernetesAddonStateRefreshFunc(clusterId, name, []string{"Failed", "Canceled"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceAlicloudCSKubernetesAddon, "WaitForSuccessAfterUpdate", d.Id())
}
}
return resourceAlicloudCSKubernetesAddonRead(d, meta)
}
func resourceAlicloudCSKubernetesAddonDelete(d *schema.ResourceData, meta interface{}) error {
clusterId := d.Get("cluster_id").(string)
name := d.Get("name").(string)
client, err := meta.(*connectivity.AliyunClient).NewRoaCsClient()
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceAlicloudCSKubernetesAddon, "InitializeClient", err)
}
csClient := CsClient{client}
err = csClient.uninstallAddon(d)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceAlicloudCSKubernetesAddon, "uninstallAddon", err)
}
stateConf := BuildStateConf([]string{"running", "Upgrading", "Pause"}, []string{"Success"}, d.Timeout(schema.TimeoutDelete), 10*time.Second, csClient.CsKubernetesAddonStateRefreshFunc(clusterId, name, []string{"Failed", "Canceled"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceAlicloudCSKubernetesAddon, "WaitForSuccessAfterDelete", d.Id())
}
return nil
}
package alicloud
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path"
"strings"
"time"
"golang.org/x/net/context"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cs"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ess"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
appsv1 "k8s.io/api/apps/v1"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
const (
clusterAutoscaler = "cluster-autoscaler"
clusterAutoscalerMeta = "autoscaler-meta"
defaultAutoscalerNamespace = "kube-system"
defaultScalingGroupTag = "k8s.aliyun.com"
defaultServiceAccountName = "admin"
defaultAutoscalerImage = "registry-vpc.%s.aliyuncs.com/acs/autoscaler:v1.3.1-7369cf1"
LabelPattern = "k8s.io/cluster-autoscaler/node-template/label/"
TaintPattern = "k8s.io/cluster-autoscaler/node-template/taint/"
)
// nodePool defines the struct of scaling group params
type nodePool map[string]string
// userKubeConf defines the struct of response of api
type userKubeConf struct {
Config string `json:"config"`
}
// autoscalerMeta define the struct of autoscaler meta configmap
type autoscalerMeta struct {
UnneededDuration string `json:"unneeded_duration"`
CoolDownDuration string `json:"cool_down_duration"`
UtilizationThreshold string `json:"utilization_threshold"`
GpuUtilizationThreshold string `json:"gpu_utilization_threshold"`
ScalingConfigurations map[string]scalingConfiguration `json:"scaling_configurations"`
}
// scalingConfiguration define the config of scaling group
type scalingConfiguration struct {
Id string `json:"id"`
Labels string `json:"labels"`
Taints string `json:"taints"`
}
// autoscalerOptions define the options used by autoscaler creation
type autoscalerOptions struct {
Args []string
RegionId string
AccessKeyId string
AccessKeySecret string
Image string
UseEcsRamRoleToken bool
}
// resourceAlicloudCSKubernetesAutoscaler defines the schema of resource
func resourceAlicloudCSKubernetesAutoscaler() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCSKubernetesAutoscalerCreate,
Read: resourceAlicloudCSKubernetesAutoscalerRead,
Update: resourceAlicloudCSKubernetesAutoscalerUpdate,
Delete: resourceAlicloudCSKubernetesAutoscalerDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(90 * time.Minute),
Update: schema.DefaultTimeout(60 * time.Minute),
Delete: schema.DefaultTimeout(60 * time.Minute),
},
Schema: map[string]*schema.Schema{
"cluster_id": {
Type: schema.TypeString,
Required: true,
},
"nodepools": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Optional: true,
},
"taints": {
Type: schema.TypeString,
Optional: true,
},
"labels": {
Type: schema.TypeString,
Optional: true,
},
// TODO add min max support
//"min": {
// Type: schema.TypeInt,
// Optional: true,
//},
//"max": {
// Type: schema.TypeInt,
// Optional: true,
//},
},
},
MaxItems: 30,
MinItems: 1,
},
"utilization": {
Type: schema.TypeString,
Required: true,
},
"cool_down_duration": {
Type: schema.TypeString,
Required: true,
},
"defer_scale_in_duration": {
Type: schema.TypeString,
Required: true,
},
"use_ecs_ram_role_token": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
// resourceAlicloudCSKubernetesAutoscalerCreate define how to create autoscaler
func resourceAlicloudCSKubernetesAutoscalerCreate(d *schema.ResourceData, meta interface{}) error {
clusterId := d.Get("cluster_id").(string)
// set unique id of tf state
d.SetId(fmt.Sprintf("%s:%s", clusterId, clusterAutoscaler))
return resourceAlicloudCSKubernetesAutoscalerUpdate(d, meta)
}
// resourceAlicloudCSKubernetesAutoscalerRead no need to implement
func resourceAlicloudCSKubernetesAutoscalerRead(d *schema.ResourceData, meta interface{}) error {
return nil
}
// resourceAlicloudCSKubernetesAutoscalerUpdate define how to update autoscaler configuration
func resourceAlicloudCSKubernetesAutoscalerUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
csService := CsService{client}
// any changes need to ready autoscaler.
if d.HasChange("nodepools") || d.HasChange("utilization") || d.HasChange("cool_down_duration") || d.HasChange("defer_scale_in_duration") || d.HasChange("use_ecs_ram_role_token") {
regionId := client.RegionId
clusterId := d.Get("cluster_id").(string)
utilization := d.Get("utilization").(string)
coolDownDuration := d.Get("cool_down_duration").(string)
deferScaleInDuration := d.Get("defer_scale_in_duration").(string)
useEcsRamroleToken := d.Get("use_ecs_ram_role_token").(bool)
// parse nodepools
nodePoolsParams := d.Get("nodepools").(*schema.Set)
nodePools := nodePoolsParams.List()
// args creation
args := make([]string, 0)
args = applyDefaultArgs(args)
configmapMeta := autoscalerMeta{
UnneededDuration: deferScaleInDuration,
CoolDownDuration: coolDownDuration,
UtilizationThreshold: utilization,
GpuUtilizationThreshold: utilization,
ScalingConfigurations: make(map[string]scalingConfiguration),
}
for _, pool := range nodePools {
poolBytes, err := json.Marshal(pool)
if err != nil {
return WrapError(fmt.Errorf("failed to marshal pool,because of %v", err))
}
pool := make(nodePool)
err = json.Unmarshal(poolBytes, &pool)
if err != nil {
return WrapError(fmt.Errorf("failed to unmarshal pool,because of %v", err))
}
// get params of node pool
id := pool["id"]
labels := pool["labels"]
taints := pool["taints"]
// get userData from cluster openapi
userData, err := csService.GetUserData(clusterId, labels, taints)
if err != nil {
return WrapError(fmt.Errorf("failed to get permanent token,because of %v", err))
}
err = UpdateScalingGroupConfiguration(client, id, userData, labels, taints)
if err != nil {
return WrapError(fmt.Errorf("failed to update scaling group status,because of %v", err))
}
// get min max of scaling group
min, max, err := GetScalingGroupSizeRange(client, id)
if err != nil {
return WrapError(fmt.Errorf("failed to describe scaling group %s,because of %v", id, err))
}
nodeArgs := fmt.Sprintf("--nodes=%d:%d:%s", min, max, id)
args = append(args, nodeArgs)
configmapMeta.ScalingConfigurations[id] = scalingConfiguration{
Id: id,
Labels: labels,
Taints: taints,
}
}
if utilization != "" {
args = append(args, fmt.Sprintf("--scale-down-utilization-threshold=%s", utilization))
args = append(args, fmt.Sprintf("--scale-down-gpu-utilization-threshold=%s", utilization))
}
if coolDownDuration != "" {
args = append(args, fmt.Sprintf("--scale-down-delay-after-add=%s", coolDownDuration))
args = append(args, fmt.Sprintf("--scale-down-delay-after-failure=%s", coolDownDuration))
}
if deferScaleInDuration != "" {
args = append(args, fmt.Sprintf("--scale-down-unneeded-time=%s", deferScaleInDuration))
}
kubeConfPath, err := DownloadUserKubeConf(client, clusterId)
if err != nil {
return WrapError(fmt.Errorf("failed to download kubeconf from cluster,because of %v", err))
}
options := autoscalerOptions{
Args: args,
Image: fmt.Sprintf(defaultAutoscalerImage, regionId),
RegionId: regionId,
AccessKeyId: client.AccessKey,
AccessKeySecret: client.SecretKey,
UseEcsRamRoleToken: useEcsRamroleToken,
}
clientSet, err := getClientSetFromKubeconf(kubeConfPath)
if err != nil {
return WrapError(fmt.Errorf("failed to create kubernetes client,because of %v", err))
}
err = DeployAutoscaler(options, clientSet)
if err != nil {
return WrapError(fmt.Errorf("failed to deploy autoscaler,because of %v", err))
}
err = createOrUpdateAutoscalerMeta(clientSet, configmapMeta)
if err != nil {
return WrapError(fmt.Errorf("failed to update autoscaler meta configmap,because of %v", err))
}
}
return nil
}
// delete autoscaler deployment
func resourceAlicloudCSKubernetesAutoscalerDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
regionId := client.RegionId
clusterId := d.Get("cluster_id").(string)
if clusterId == "" {
return WrapError(fmt.Errorf("please provide the cluster_id in region %s", regionId))
}
kubeConfPath, err := DownloadUserKubeConf(client, clusterId)
if err != nil {
return WrapError(fmt.Errorf("failed to download kubeconf from cluster,because of %v", err))
}
return DeleteAutoscaler(kubeConfPath)
}
// update scaling group config
func UpdateScalingGroupConfiguration(client *connectivity.AliyunClient, groupId, userData string, labels string, taints string) (err error) {
describeScalingConfigurationsRequest := ess.CreateDescribeScalingConfigurationsRequest()
describeScalingConfigurationsResponse, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
describeScalingConfigurationsRequest.RegionId = client.RegionId
describeScalingConfigurationsRequest.ScalingGroupId = groupId
return essClient.DescribeScalingConfigurations(describeScalingConfigurationsRequest)
})
configurations, ok := describeScalingConfigurationsResponse.(*ess.DescribeScalingConfigurationsResponse)
if ok != true {
return WrapError(fmt.Errorf("failed to parse DescribeScalingConfigurationsResponse of %s", groupId))
}
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, groupId, describeScalingConfigurationsRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug("DescribeScalingConfigurations", configurations, describeScalingConfigurationsRequest)
if len(configurations.ScalingConfigurations.ScalingConfiguration) == 0 {
//todo create configuration
return WrapError(fmt.Errorf("please create the default scaling configuration of group %s", groupId))
} else {
defaultConfiguration := configurations.ScalingConfigurations.ScalingConfiguration[0]
// modify the default one
modifyScalingConfigurationRequest := ess.CreateModifyScalingConfigurationRequest()
modifyScalingConfigurationResponse, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
modifyScalingConfigurationRequest.RegionId = client.RegionId
modifyScalingConfigurationRequest.UserData = userData
modifyScalingConfigurationRequest.Tags = createScalingGroupTags(labels, taints)
modifyScalingConfigurationRequest.ScalingConfigurationId = defaultConfiguration.ScalingConfigurationId
return essClient.ModifyScalingConfiguration(modifyScalingConfigurationRequest)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, groupId, modifyScalingConfigurationRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug("ModifyScalingConfiguration", modifyScalingConfigurationResponse, modifyScalingConfigurationRequest)
}
return nil
}
func GetScalingGroupSizeRange(client *connectivity.AliyunClient, groupId string) (min, max int, err error) {
describeScalingGroupRequest := ess.CreateDescribeScalingGroupsRequest()
describeScalingGroupRequest.RegionId = client.RegionId
describeScalingGroupRequest.ScalingGroupId = &[]string{groupId}
describeScalingGroupResponse, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DescribeScalingGroups(describeScalingGroupRequest)
})
if err != nil {
return 0, 0, WrapErrorf(err, DefaultErrorMsg, groupId, describeScalingGroupRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug("DescribeScalingGroups", describeScalingGroupResponse, describeScalingGroupRequest)
resp, ok := describeScalingGroupResponse.(*ess.DescribeScalingGroupsResponse)
if ok != true {
return 0, 0, WrapError(fmt.Errorf("failed to parse DescribeScalingGroupsResponse of scaling group %s", groupId))
}
if resp.ScalingGroups.ScalingGroup == nil || len(resp.ScalingGroups.ScalingGroup) == 0 {
return 0, 0, WrapError(fmt.Errorf("the scaling group %s you specific is not found", groupId))
}
scalingGroup := resp.ScalingGroups.ScalingGroup[0]
if &scalingGroup == nil {
return 0, 0, WrapError(fmt.Errorf("the scaling group %s you specific is not found", groupId))
}
return scalingGroup.MinSize, scalingGroup.MaxSize, nil
}
// prepare kubeconf of kubernetes clsuter
func DownloadUserKubeConf(client *connectivity.AliyunClient, clusterId string) (string, error) {
describeClusterUserKubeconfigRequest := cs.CreateDescribeClusterUserKubeconfigRequest()
describeClusterUserKubeconfigResponse, err := client.WithOfficalCSClient(func(csClient *cs.Client) (interface{}, error) {
describeClusterUserKubeconfigRequest.RegionId = client.RegionId
describeClusterUserKubeconfigRequest.ClusterId = clusterId
return csClient.DescribeClusterUserKubeconfig(describeClusterUserKubeconfigRequest)
})
if err != nil {
return "", WrapErrorf(err, DefaultErrorMsg, clusterId, describeClusterUserKubeconfigRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
kubeConfResponse, ok := describeClusterUserKubeconfigResponse.(*cs.DescribeClusterUserKubeconfigResponse)
if ok != true {
return "", WrapError(fmt.Errorf("failed to parse DescribeClusterUserKubeconfigResponse of %s", clusterId))
}
addDebug("DescribeClusterUserKubeconfig", describeClusterUserKubeconfigResponse, describeClusterUserKubeconfigRequest)
// get response bytes
kubeconfBytes := kubeConfResponse.GetHttpContentBytes()
ukc := &userKubeConf{}
err = json.Unmarshal(kubeconfBytes, ukc)
if err != nil {
return "", WrapError(fmt.Errorf("failed to parse DescribeClusterUserKubeconfigResponse,because of %v", err))
}
content := ukc.Config
wd, err := os.Getwd()
if err != nil {
return "", WrapError(fmt.Errorf("failed to get current working dir,because of %v", err))
}
kubeConfPath := path.Join(wd, fmt.Sprintf("%s-kubeconf", clusterId))
err = ioutil.WriteFile(kubeConfPath, []byte(content), 0755)
if err != nil {
return "", WrapError(fmt.Errorf("failed to create kubeconf in working dir because of %v", err))
}
return kubeConfPath, nil
}
// delete autoscaler component
func DeleteAutoscaler(kubeconf string) error {
ctx := context.Background()
config, err := clientcmd.BuildConfigFromFlags("", kubeconf)
if err != nil {
return WrapError(fmt.Errorf("failed to build kubeconf from local path %s,because of %v", kubeconf, err))
}
clientSet, err := kubernetes.NewForConfig(config)
if err != nil {
return WrapError(fmt.Errorf("failed to create client-go clientSet,because of %v", err))
}
err = clientSet.AppsV1().Deployments(defaultAutoscalerNamespace).Delete(ctx, clusterAutoscaler, metav1.DeleteOptions{})
if errors.IsNotFound(err) == true {
return nil
}
return WrapError(err)
}
// deploy cluster-autoscaler to kubernetes cluster
func DeployAutoscaler(options autoscalerOptions, clientSet *kubernetes.Clientset) error {
ctx := context.Background()
deploy, err := clientSet.AppsV1().Deployments(defaultAutoscalerNamespace).Get(ctx, clusterAutoscaler, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
ak := options.AccessKeyId
sk := options.AccessKeySecret
if options.UseEcsRamRoleToken {
ak = ""
sk = ""
}
// create a new deploy
deployObject := &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: clusterAutoscaler,
Labels: map[string]string{
"app": clusterAutoscaler,
},
},
Spec: appsv1.DeploymentSpec{
Replicas: int32Ptr(1),
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"app": clusterAutoscaler,
},
},
Template: v1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
"app": clusterAutoscaler,
},
},
Spec: v1.PodSpec{
ServiceAccountName: defaultServiceAccountName,
Affinity: &v1.Affinity{
NodeAffinity: &v1.NodeAffinity{
RequiredDuringSchedulingIgnoredDuringExecution: &v1.NodeSelector{
NodeSelectorTerms: []v1.NodeSelectorTerm{
{
MatchExpressions: []v1.NodeSelectorRequirement{
{
Key: defaultScalingGroupTag,
Operator: v1.NodeSelectorOpNotIn,
Values: []string{
"true",
},
},
},
},
},
},
},
},
Containers: []v1.Container{
{
Name: clusterAutoscaler,
Image: options.Image,
Command: options.Args,
Env: []v1.EnvVar{
v1.EnvVar{
Name: "REGION_ID",
Value: options.RegionId,
},
v1.EnvVar{
Name: "ACCESS_KEY_ID",
Value: ak,
},
v1.EnvVar{
Name: "ACCESS_KEY_SECRET",
Value: sk,
},
},
},
},
},
},
},
}
_, err := clientSet.AppsV1().Deployments(defaultAutoscalerNamespace).Create(ctx, deployObject, metav1.CreateOptions{})
if err != nil {
return WrapError(fmt.Errorf("failed to create %s deployment,because of %v", clusterAutoscaler, err))
}
} else {
return WrapError(fmt.Errorf("failed to describe %s deployment,because of %v", clusterAutoscaler, err))
}
} else {
// update deployment
deploy.Spec.Template.Spec.Containers[0].Command = options.Args
_, err := clientSet.AppsV1().Deployments(defaultAutoscalerNamespace).Update(ctx, deploy, metav1.UpdateOptions{})
if err != nil {
return WrapError(fmt.Errorf("failed to update %s deployment,because of %v", clusterAutoscaler, err))
}
}
return nil
}
// set replicas
func int32Ptr(i int32) *int32 { return &i }
// apply default params of autoscaler command
func applyDefaultArgs(args []string) []string {
args = append(args, "./cluster-autoscaler")
args = append(args, "--v=5")
args = append(args, "--stderrthreshold=info")
args = append(args, "--cloud-provider=alicloud")
args = append(args, "--scan-interval=30s")
args = append(args, "--ok-total-unready-count=1000")
args = append(args, "--max-empty-bulk-delete=50")
args = append(args, "--expander=least-waste")
args = append(args, "--leader-elect=false")
args = append(args, "--skip-nodes-with-local-storage=false")
return args
}
// convert labels and taints to scaling group tags
func createScalingGroupTags(labels string, taints string) string {
tags := make(map[string]string)
tags[defaultScalingGroupTag] = "true"
labelArr := strings.Split(labels, ",")
for _, label := range labelArr {
labelKeyValue := strings.Split(label, "=")
if len(labelKeyValue) == 2 {
tags[fmt.Sprintf("%s%s", LabelPattern, labelKeyValue[0])] = labelKeyValue[1]
}
}
taintsArr := strings.Split(taints, ",")
for _, taint := range taintsArr {
taintKeyValue := strings.Split(taint, "=")
if len(taintKeyValue) == 2 {
tags[fmt.Sprintf("%s%s", TaintPattern, taintKeyValue[0])] = taintKeyValue[1]
}
}
tagsBytes, err := json.Marshal(tags)
if err != nil {
return ""
}
return string(tagsBytes)
}
// getClientSetFromKubeconf return the clientSet from kubeconf
func getClientSetFromKubeconf(kubeconf string) (*kubernetes.Clientset, error) {
config, err := clientcmd.BuildConfigFromFlags("", kubeconf)
if err != nil {
return nil, WrapError(fmt.Errorf("failed to build kubeconf from local path %s,because of %v", kubeconf, err))
}
clientSet, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, WrapError(fmt.Errorf("failed to create client-go clientSet,because of %v", err))
}
return clientSet, nil
}
// update autoscaler meta configmap
func createOrUpdateAutoscalerMeta(clientSet *kubernetes.Clientset, meta autoscalerMeta) error {
ctx := context.Background()
meta_bytes, err := json.Marshal(meta)
if err != nil {
return WrapError(fmt.Errorf("failed to marshal autoscaler meta,because of %v", err))
}
meta_map := make(map[string]string)
meta_map[clusterAutoscalerMeta] = string(meta_bytes)
cm := &v1.ConfigMap{
Data: meta_map,
}
cm.Name = clusterAutoscalerMeta
configmap, err := clientSet.CoreV1().ConfigMaps(defaultAutoscalerNamespace).Get(ctx, clusterAutoscalerMeta, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
_, err = clientSet.CoreV1().ConfigMaps(defaultAutoscalerNamespace).Create(ctx, cm, metav1.CreateOptions{})
if err != nil {
return WrapError(fmt.Errorf("failed to create configmap of autoscaler meta,because of %v", err))
}
return nil
} else {
// return errror
return WrapError(fmt.Errorf("failed to describe configmap autoscaler meta,because of %v", err))
}
}
configmap.Data = meta_map
// update configmapa
_, err = clientSet.CoreV1().ConfigMaps(defaultAutoscalerNamespace).Update(ctx, configmap, metav1.UpdateOptions{})
if err != nil {
return WrapError(fmt.Errorf("failed to update configmap autoscaler meta,because of %v", err))
}
return nil
}
package alicloud
import (
"encoding/base64"
"fmt"
"log"
"regexp"
"time"
"github.com/alibabacloud-go/tea/tea"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
roacs "github.com/alibabacloud-go/cs-20151215/v2/client"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/denverdino/aliyungo/common"
"github.com/denverdino/aliyungo/cs"
aliyungoecs "github.com/denverdino/aliyungo/ecs"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCSKubernetesNodePool() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCSKubernetesNodePoolCreate,
Read: resourceAlicloudCSNodePoolRead,
Update: resourceAlicloudCSNodePoolUpdate,
Delete: resourceAlicloudCSNodePoolDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(90 * time.Minute),
Update: schema.DefaultTimeout(60 * time.Minute),
Delete: schema.DefaultTimeout(60 * time.Minute),
},
Schema: map[string]*schema.Schema{
"cluster_id": {
Type: schema.TypeString,
Required: true,
},
"name": {
Type: schema.TypeString,
Required: true,
},
"node_count": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ConflictsWith: []string{"instances"},
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_ids": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
MinItems: 1,
},
"instance_types": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
MinItems: 1,
MaxItems: 10,
},
"password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
ConflictsWith: []string{"key_name", "kms_encrypted_password"},
},
"key_name": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"password", "kms_encrypted_password"},
},
"kms_encrypted_password": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"password", "key_name"},
},
"security_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Field 'security_group_id' has been deprecated from provider version 1.145.0. New field 'security_group_ids' instead",
},
"system_disk_category": {
Type: schema.TypeString,
Optional: true,
Default: DiskCloudEfficiency,
},
"system_disk_size": {
Type: schema.TypeInt,
Optional: true,
Default: 40,
ValidateFunc: validation.IntBetween(20, 32768),
},
"system_disk_performance_level": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"PL0", "PL1", "PL2", "PL3"}, false),
DiffSuppressFunc: csNodepoolDiskPerformanceLevelDiffSuppressFunc,
},
"platform": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"AliyunLinux", "Windows", "CentOS", "WindowsCore"}, false),
Deprecated: "Field 'platform' has been deprecated from provider version 1.145.0. New field 'image_type' instead",
},
"image_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"instance_charge_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: PostPaid,
ValidateFunc: validation.StringInSlice([]string{string(common.PrePaid), string(common.PostPaid)}, false),
},
"period": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 6, 12, 24, 36, 48, 60}),
DiffSuppressFunc: csNodepoolInstancePostPaidDiffSuppressFunc,
},
"period_unit": {
Type: schema.TypeString,
Optional: true,
Default: Month,
ValidateFunc: validation.StringInSlice([]string{"Month"}, false),
DiffSuppressFunc: csNodepoolInstancePostPaidDiffSuppressFunc,
},
"auto_renew": {
Type: schema.TypeBool,
Default: false,
Optional: true,
DiffSuppressFunc: csNodepoolInstancePostPaidDiffSuppressFunc,
},
"auto_renew_period": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 6, 12}),
DiffSuppressFunc: csNodepoolInstancePostPaidDiffSuppressFunc,
},
"install_cloud_monitor": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"unschedulable": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"data_disks": {
Optional: true,
Type: schema.TypeList,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"size": {
Type: schema.TypeInt,
Optional: true,
},
"category": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"all", "cloud", "ephemeral_ssd", "cloud_essd", "cloud_efficiency", "cloud_ssd", "local_disk"}, false),
},
"snapshot_id": {
Type: schema.TypeString,
Optional: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
},
"device": {
Type: schema.TypeString,
Optional: true,
},
"kms_key_id": {
Type: schema.TypeString,
Optional: true,
},
"encrypted": {
Type: schema.TypeString,
Optional: true,
},
"auto_snapshot_policy_id": {
Type: schema.TypeString,
Optional: true,
},
"performance_level": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"tags": {
Type: schema.TypeMap,
Optional: true,
},
"labels": {
Optional: true,
Type: schema.TypeList,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Required: true,
},
"value": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"taints": {
Optional: true,
Type: schema.TypeList,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Required: true,
},
"value": {
Type: schema.TypeString,
Optional: true,
},
"effect": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"node_name_mode": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^customized,[a-z0-9]([-a-z0-9\.])*,([5-9]|[1][0-2]),([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`), "Each node name consists of a prefix, an IP substring, and a suffix. For example, if the node IP address is 192.168.0.55, the prefix is aliyun.com, IP substring length is 5, and the suffix is test, the node name will be aliyun.com00055test."),
},
"user_data": {
Type: schema.TypeString,
Optional: true,
},
"scaling_group_id": {
Type: schema.TypeString,
Computed: true,
},
"management": {
Type: schema.TypeList,
Optional: true,
Computed: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"auto_repair": {
Type: schema.TypeBool,
Optional: true,
},
"auto_upgrade": {
Type: schema.TypeBool,
Optional: true,
},
"surge": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(0, 1000),
},
"surge_percentage": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(0, 100),
},
"max_unavailable": {
Type: schema.TypeInt,
Required: true,
},
},
},
},
"scaling_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"min_size": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(0, 1000),
},
"max_size": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(0, 1000),
},
"type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"cpu", "gpu", "gpushare", "spot"}, false),
},
"is_bond_eip": {
Type: schema.TypeBool,
Optional: true,
ConflictsWith: []string{"internet_charge_type"},
},
"eip_internet_charge_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"PayByBandwidth", "PayByTraffic"}, false),
ConflictsWith: []string{"internet_charge_type"},
},
"eip_bandwidth": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(1, 500),
ConflictsWith: []string{"internet_charge_type"},
},
},
},
ConflictsWith: []string{"instances"},
},
"scaling_policy": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"release", "recycle"}, false),
DiffSuppressFunc: csNodepoolScalingPolicyDiffSuppressFunc,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"internet_charge_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"PayByTraffic", "PayByBandwidth"}, false),
},
"internet_max_bandwidth_out": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"spot_strategy": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"SpotWithPriceLimit"}, false),
},
"spot_price_limit": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"instance_type": {
Type: schema.TypeString,
Optional: true,
},
"price_limit": {
Type: schema.TypeString,
Optional: true,
},
},
},
DiffSuppressFunc: csNodepoolSpotInstanceSettingDiffSuppressFunc,
},
"instances": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
MaxItems: 100,
ConflictsWith: []string{"node_count", "scaling_config"},
},
"keep_instance_name": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"format_disk": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"security_group_ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
MaxItems: 5,
Computed: true,
},
"image_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"AliyunLinux", "AliyunLinux3", "AliyunLinux3Arm64", "AliyunLinuxUEFI", "CentOS", "Windows", "WindowsCore", "AliyunLinux Qboot", "ContainerOS"}, false),
},
"runtime_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"runtime_version": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"deployment_set_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudCSKubernetesNodePoolCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
csService := CsService{client}
invoker := NewInvoker()
var requestInfo *cs.Client
var raw interface{}
clusterId := d.Get("cluster_id").(string)
// prepare args and set default value
args, err := buildNodePoolArgs(d, meta)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cs_kubernetes_node_pool", "PrepareKubernetesNodePoolArgs", err)
}
if err = invoker.Run(func() error {
raw, err = client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
return csClient.CreateNodePool(args, d.Get("cluster_id").(string))
})
return err
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cs_kubernetes_node_pool", "CreateKubernetesNodePool", raw)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["RegionId"] = common.Region(client.RegionId)
requestMap["Params"] = args
addDebug("CreateKubernetesNodePool", raw, requestInfo, requestMap)
}
nodePool, ok := raw.(*cs.CreateNodePoolResponse)
if ok != true {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cs_kubernetes_node_pool", "ParseKubernetesNodePoolResponse", raw)
}
d.SetId(fmt.Sprintf("%s%s%s", clusterId, COLON_SEPARATED, nodePool.NodePoolID))
// reset interval to 10s
stateConf := BuildStateConf([]string{"initial", "scaling"}, []string{"active"}, d.Timeout(schema.TimeoutCreate), 30*time.Second, csService.CsKubernetesNodePoolStateRefreshFunc(d.Id(), []string{"deleting", "failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, "ResourceID:%s , TaskID:%s ", d.Id(), nodePool.TaskID)
}
// attach existing node
if v, ok := d.GetOk("instances"); ok && v != nil {
attachExistingInstance(d, meta)
}
return resourceAlicloudCSNodePoolRead(d, meta)
}
func resourceAlicloudCSNodePoolUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
csService := CsService{client}
vpcService := VpcService{client}
d.Partial(true)
update := false
invoker := NewInvoker()
args := &cs.UpdateNodePoolRequest{
RegionId: common.Region(client.RegionId),
NodePoolInfo: cs.NodePoolInfo{},
ScalingGroup: cs.ScalingGroup{},
KubernetesConfig: cs.KubernetesConfig{},
AutoScaling: cs.AutoScaling{},
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
if d.HasChange("node_count") {
oldV, newV := d.GetChange("node_count")
oldValue, ok := oldV.(int)
if ok != true {
return WrapErrorf(fmt.Errorf("node_count old value can not be parsed"), "parseError %d", oldValue)
}
newValue, ok := newV.(int)
if ok != true {
return WrapErrorf(fmt.Errorf("node_count new value can not be parsed"), "parseError %d", newValue)
}
if newValue < oldValue {
removeNodePoolNodes(d, meta, parts, nil, nil)
// The removal of a node is logically independent.
// The removal of a node should not involve parameter changes.
return resourceAlicloudCSNodePoolRead(d, meta)
}
update = true
args.Count = int64(newValue) - int64(oldValue)
}
args.NodePoolInfo.Name = d.Get("name").(string)
if d.HasChange("name") {
update = true
args.NodePoolInfo.Name = d.Get("name").(string)
}
if d.HasChange("vswitch_ids") {
update = true
var vswitchID string
if list := expandStringList(d.Get("vswitch_ids").([]interface{})); len(list) > 0 {
vswitchID = list[0]
} else {
vswitchID = ""
}
var vpcId string
if vswitchID != "" {
vsw, err := vpcService.DescribeVSwitch(vswitchID)
if err != nil {
return err
}
vpcId = vsw.VpcId
}
args.ScalingGroup.VpcId = vpcId
args.ScalingGroup.VswitchIds = expandStringList(d.Get("vswitch_ids").([]interface{}))
}
if v, ok := d.GetOk("instance_charge_type"); ok {
args.InstanceChargeType = v.(string)
if args.InstanceChargeType == string(PrePaid) {
update = true
args.Period = d.Get("period").(int)
args.PeriodUnit = d.Get("period_unit").(string)
args.AutoRenew = d.Get("auto_renew").(bool)
args.AutoRenewPeriod = d.Get("auto_renew_period").(int)
}
}
if v, ok := d.GetOk("install_cloud_monitor"); ok && v != nil {
args.CmsEnabled = v.(bool)
}
if d.HasChange("install_cloud_monitor") {
update = true
args.CmsEnabled = d.Get("install_cloud_monitor").(bool)
}
if v, ok := d.GetOk("unschedulable"); ok {
args.Unschedulable = v.(bool)
}
if d.HasChange("instance_types") {
update = true
args.ScalingGroup.InstanceTypes = expandStringList(d.Get("instance_types").([]interface{}))
}
// password is required by update method
args.ScalingGroup.LoginPassword = d.Get("password").(string)
if d.HasChange("password") {
update = true
args.ScalingGroup.LoginPassword = d.Get("password").(string)
}
args.ScalingGroup.KeyPair = d.Get("key_name").(string)
if d.HasChange("key_name") {
update = true
args.ScalingGroup.KeyPair = d.Get("key_name").(string)
}
if d.HasChange("security_group_id") {
update = true
args.ScalingGroup.SecurityGroupId = d.Get("security_group_id").(string)
}
if d.HasChange("system_disk_category") {
update = true
args.ScalingGroup.SystemDiskCategory = aliyungoecs.DiskCategory(d.Get("system_disk_category").(string))
}
if d.HasChange("system_disk_size") {
update = true
args.ScalingGroup.SystemDiskSize = int64(d.Get("system_disk_size").(int))
}
if d.HasChange("system_disk_performance_level") {
update = true
args.SystemDiskPerformanceLevel = d.Get("system_disk_performance_level").(string)
}
if d.HasChange("image_id") {
update = true
args.ScalingGroup.ImageId = d.Get("image_id").(string)
}
if d.HasChange("data_disks") {
update = true
setNodePoolDataDisks(&args.ScalingGroup, d)
}
if d.HasChange("tags") {
update = true
setNodePoolTags(&args.ScalingGroup, d)
}
if d.HasChange("labels") {
update = true
setNodePoolLabels(&args.KubernetesConfig, d)
}
if d.HasChange("taints") {
update = true
setNodePoolTaints(&args.KubernetesConfig, d)
}
if d.HasChange("node_name_mode") {
update = true
args.KubernetesConfig.NodeNameMode = d.Get("node_name_mode").(string)
}
if v, ok := d.GetOk("user_data"); ok && v != nil {
_, base64DecodeError := base64.StdEncoding.DecodeString(v.(string))
if base64DecodeError == nil {
args.KubernetesConfig.UserData = v.(string)
} else {
args.KubernetesConfig.UserData = base64.StdEncoding.EncodeToString([]byte(v.(string)))
}
}
if d.HasChange("user_data") {
update = true
if v := d.Get("user_data").(string); v != "" {
_, base64DecodeError := base64.StdEncoding.DecodeString(v)
if base64DecodeError == nil {
args.KubernetesConfig.UserData = v
} else {
args.KubernetesConfig.UserData = base64.StdEncoding.EncodeToString([]byte(v))
}
}
}
if v, ok := d.GetOk("scaling_config"); ok && v != nil {
args.AutoScaling = setAutoScalingConfig(v.([]interface{}))
}
if d.HasChange("scaling_config") {
update = true
if v, ok := d.GetOk("scaling_config"); ok {
args.AutoScaling = setAutoScalingConfig(v.([]interface{}))
}
}
if v, ok := d.Get("management").([]interface{}); len(v) > 0 && ok {
update = true
args.Management = setManagedNodepoolConfig(v)
}
if v, ok := d.GetOk("internet_charge_type"); ok {
update = true
args.InternetChargeType = v.(string)
}
if v, ok := d.GetOk("internet_max_bandwidth_out"); ok {
update = true
args.InternetMaxBandwidthOut = v.(int)
}
if v, ok := d.GetOk("platform"); ok {
update = true
args.Platform = v.(string)
}
if d.HasChange("scaling_policy") {
update = true
args.ScalingPolicy = d.Get("scaling_policy").(string)
}
// spot
if d.HasChange("spot_strategy") {
update = true
args.SpotStrategy = d.Get("spot_strategy").(string)
}
if d.HasChange("spot_price_limit") {
update = true
args.SpotPriceLimit = setSpotPriceLimit(d.Get("spot_price_limit").([]interface{}))
}
if update {
var resoponse interface{}
if err := invoker.Run(func() error {
var err error
resoponse, err = client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
resp, err := csClient.UpdateNodePool(parts[0], parts[1], args)
return resp, err
})
return err
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "UpdateKubernetesNodePool", DenverdinoAliyungo)
}
if debugOn() {
resizeRequestMap := make(map[string]interface{})
resizeRequestMap["ClusterId"] = parts[0]
resizeRequestMap["NodePoolId"] = parts[1]
resizeRequestMap["Args"] = args
addDebug("UpdateKubernetesNodePool", resoponse, resizeRequestMap)
}
stateConf := BuildStateConf([]string{"scaling", "updating"}, []string{"active"}, d.Timeout(schema.TimeoutUpdate), 10*time.Second, csService.CsKubernetesNodePoolStateRefreshFunc(d.Id(), []string{"deleting", "failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
// attach or remove existing node
if d.HasChange("instances") {
rawOldValue, rawNewValue := d.GetChange("instances")
oldValue, ok := rawOldValue.([]interface{})
if ok != true {
return WrapErrorf(fmt.Errorf("instances old value can not be parsed"), "parseError %d", oldValue)
}
newValue, ok := rawNewValue.([]interface{})
if ok != true {
return WrapErrorf(fmt.Errorf("instances new value can not be parsed"), "parseError %d", oldValue)
}
if len(newValue) > len(oldValue) {
attachExistingInstance(d, meta)
} else {
removeNodePoolNodes(d, meta, parts, oldValue, newValue)
}
}
_ = resource.Retry(10*time.Minute, func() *resource.RetryError {
log.Printf("[DEBUG] Start retry fetch node pool info: %s", d.Id())
nodePoolDetail, err := csService.DescribeCsKubernetesNodePool(d.Id())
if err != nil {
return resource.NonRetryableError(err)
}
if nodePoolDetail.TotalNodes != d.Get("node_count").(int) {
time.Sleep(20 * time.Second)
return resource.RetryableError(Error("[ERROR] The number of nodes is inconsistent %s", d.Id()))
}
return resource.NonRetryableError(Error("[DEBUG] The number of nodes is the same"))
})
update = false
d.Partial(false)
return resourceAlicloudCSNodePoolRead(d, meta)
}
func resourceAlicloudCSNodePoolRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
csService := CsService{client}
object, err := csService.DescribeCsKubernetesNodePool(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("node_count", object.TotalNodes)
d.Set("name", object.Name)
d.Set("vpc_id", object.VpcId)
d.Set("vswitch_ids", object.VswitchIds)
d.Set("instance_types", object.InstanceTypes)
d.Set("key_name", object.KeyPair)
d.Set("security_group_id", object.SecurityGroupId)
d.Set("system_disk_category", object.SystemDiskCategory)
d.Set("system_disk_size", object.SystemDiskSize)
d.Set("system_disk_performance_level", object.SystemDiskPerformanceLevel)
d.Set("image_id", object.ImageId)
d.Set("platform", object.Platform)
d.Set("scaling_policy", object.ScalingPolicy)
d.Set("node_name_mode", object.NodeNameMode)
d.Set("user_data", object.UserData)
d.Set("scaling_group_id", object.ScalingGroupId)
d.Set("unschedulable", object.Unschedulable)
d.Set("instance_charge_type", object.InstanceChargeType)
d.Set("resource_group_id", object.ResourceGroupId)
d.Set("spot_strategy", object.SpotStrategy)
d.Set("internet_charge_type", object.InternetChargeType)
d.Set("internet_max_bandwidth_out", object.InternetMaxBandwidthOut)
d.Set("install_cloud_monitor", object.CmsEnabled)
d.Set("image_type", object.ScalingGroup.ImageType)
d.Set("security_group_ids", object.ScalingGroup.SecurityGroupIds)
d.Set("runtime_name", object.Runtime)
d.Set("runtime_version", object.RuntimeVersion)
d.Set("deployment_set_id", object.DeploymentSetId)
if object.InstanceChargeType == "PrePaid" {
d.Set("period", object.Period)
d.Set("period_unit", object.PeriodUnit)
d.Set("auto_renew", object.AutoRenew)
d.Set("auto_renew_period", object.AutoRenewPeriod)
}
if passwd, ok := d.GetOk("password"); ok && passwd.(string) != "" {
d.Set("password", passwd)
}
if parts, err := ParseResourceId(d.Id(), 2); err != nil {
return WrapError(err)
} else {
d.Set("cluster_id", string(parts[0]))
}
if err := d.Set("data_disks", flattenNodeDataDisksConfig(object.DataDisks)); err != nil {
return WrapError(err)
}
if err := d.Set("taints", flattenTaintsConfig(object.Taints)); err != nil {
return WrapError(err)
}
if err := d.Set("labels", flattenLabelsConfig(object.Labels)); err != nil {
return WrapError(err)
}
if err := d.Set("tags", flattenTagsConfig(object.Tags)); err != nil {
return WrapError(err)
}
if object.Management.Enable == true {
if err := d.Set("management", flattenManagementNodepoolConfig(&object.Management)); err != nil {
return WrapError(err)
}
}
if object.AutoScaling.Enable == true {
if err := d.Set("scaling_config", flattenAutoScalingConfig(&object.AutoScaling)); err != nil {
return WrapError(err)
}
}
if err := d.Set("spot_price_limit", flattenSpotPriceLimit(object.SpotPriceLimit)); err != nil {
return WrapError(err)
}
return nil
}
func resourceAlicloudCSNodePoolDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
csService := CsService{client}
invoker := NewInvoker()
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
// delete all nodes
removeNodePoolNodes(d, meta, parts, nil, nil)
var response interface{}
err = resource.Retry(30*time.Minute, func() *resource.RetryError {
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
return nil, csClient.DeleteNodePool(parts[0], parts[1])
})
response = raw
return err
}); err != nil {
return resource.RetryableError(err)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["ClusterId"] = parts[0]
requestMap["NodePoolId"] = parts[1]
addDebug("DeleteClusterNodePool", response, d.Id(), requestMap)
}
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ErrorClusterNodePoolNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DeleteClusterNodePool", DenverdinoAliyungo)
}
stateConf := BuildStateConf([]string{"active", "deleting"}, []string{}, d.Timeout(schema.TimeoutDelete), 30*time.Second, csService.CsKubernetesNodePoolStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
func buildNodePoolArgs(d *schema.ResourceData, meta interface{}) (*cs.CreateNodePoolRequest, error) {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var vswitchID string
if list := expandStringList(d.Get("vswitch_ids").([]interface{})); len(list) > 0 {
vswitchID = list[0]
} else {
vswitchID = ""
}
var vpcId string
if vswitchID != "" {
vsw, err := vpcService.DescribeVSwitch(vswitchID)
if err != nil {
return nil, err
}
vpcId = vsw.VpcId
}
password := d.Get("password").(string)
if password == "" {
if v := d.Get("kms_encrypted_password").(string); v != "" {
kmsService := KmsService{client}
decryptResp, err := kmsService.Decrypt(v, d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return nil, WrapError(err)
}
password = decryptResp
}
}
creationArgs := &cs.CreateNodePoolRequest{
RegionId: common.Region(client.RegionId),
Count: int64(d.Get("node_count").(int)),
NodePoolInfo: cs.NodePoolInfo{
Name: d.Get("name").(string),
NodePoolType: "ess", // hard code the type
},
ScalingGroup: cs.ScalingGroup{
VpcId: vpcId,
VswitchIds: expandStringList(d.Get("vswitch_ids").([]interface{})),
InstanceTypes: expandStringList(d.Get("instance_types").([]interface{})),
LoginPassword: password,
KeyPair: d.Get("key_name").(string),
SystemDiskCategory: aliyungoecs.DiskCategory(d.Get("system_disk_category").(string)),
SystemDiskSize: int64(d.Get("system_disk_size").(int)),
SecurityGroupId: d.Get("security_group_id").(string),
ImageId: d.Get("image_id").(string),
Platform: d.Get("platform").(string),
},
KubernetesConfig: cs.KubernetesConfig{
NodeNameMode: d.Get("node_name_mode").(string),
},
}
setNodePoolDataDisks(&creationArgs.ScalingGroup, d)
setNodePoolTags(&creationArgs.ScalingGroup, d)
setNodePoolTaints(&creationArgs.KubernetesConfig, d)
setNodePoolLabels(&creationArgs.KubernetesConfig, d)
if v, ok := d.GetOk("instance_charge_type"); ok {
creationArgs.InstanceChargeType = v.(string)
if creationArgs.InstanceChargeType == string(PrePaid) {
creationArgs.Period = d.Get("period").(int)
creationArgs.PeriodUnit = d.Get("period_unit").(string)
creationArgs.AutoRenew = d.Get("auto_renew").(bool)
creationArgs.AutoRenewPeriod = d.Get("auto_renew_period").(int)
}
}
if v, ok := d.GetOk("deployment_set_id"); ok {
creationArgs.DeploymentSetId = v.(string)
}
if v, ok := d.GetOk("install_cloud_monitor"); ok {
creationArgs.CmsEnabled = v.(bool)
}
if v, ok := d.GetOk("unschedulable"); ok {
creationArgs.Unschedulable = v.(bool)
}
if v, ok := d.GetOk("user_data"); ok && v != "" {
_, base64DecodeError := base64.StdEncoding.DecodeString(v.(string))
if base64DecodeError == nil {
creationArgs.KubernetesConfig.UserData = v.(string)
} else {
creationArgs.KubernetesConfig.UserData = base64.StdEncoding.EncodeToString([]byte(v.(string)))
}
}
// set auto scaling config
if v, ok := d.GetOk("scaling_policy"); ok {
creationArgs.ScalingPolicy = v.(string)
}
if v, ok := d.GetOk("scaling_config"); ok {
if sc, ok := v.([]interface{}); len(sc) > 0 && ok {
creationArgs.AutoScaling = setAutoScalingConfig(sc)
}
}
// set manage nodepool params
if v, ok := d.GetOk("management"); ok {
if management, ok := v.([]interface{}); len(management) > 0 && ok {
creationArgs.Management = setManagedNodepoolConfig(management)
}
}
if v, ok := d.GetOk("system_disk_performance_level"); ok {
creationArgs.SystemDiskPerformanceLevel = v.(string)
}
if v, ok := d.GetOk("resource_group_id"); ok {
creationArgs.ResourceGroupId = v.(string)
}
// setting spot instance
if v, ok := d.GetOk("spot_strategy"); ok {
creationArgs.SpotStrategy = v.(string)
}
if v, ok := d.GetOk("spot_price_limit"); ok {
creationArgs.SpotPriceLimit = setSpotPriceLimit(v.([]interface{}))
}
if v, ok := d.GetOk("internet_charge_type"); ok {
creationArgs.InternetChargeType = v.(string)
}
if v, ok := d.GetOk("internet_max_bandwidth_out"); ok {
creationArgs.InternetMaxBandwidthOut = v.(int)
}
if v, ok := d.GetOk("security_group_ids"); ok {
creationArgs.SecurityGroupIds = expandStringList(v.([]interface{}))
}
if v, ok := d.GetOk("image_type"); ok {
creationArgs.ImageType = v.(string)
}
if v, ok := d.GetOk("runtime_name"); ok {
creationArgs.Runtime = v.(string)
}
if v, ok := d.GetOk("runtime_version"); ok {
creationArgs.RuntimeVersion = v.(string)
}
return creationArgs, nil
}
func ConvertCsTags(d *schema.ResourceData) ([]cs.Tag, error) {
tags := make([]cs.Tag, 0)
tagsMap, ok := d.Get("tags").(map[string]interface{})
if ok {
for key, value := range tagsMap {
if value != nil {
if v, ok := value.(string); ok {
tags = append(tags, cs.Tag{
Key: key,
Value: v,
})
}
}
}
}
return tags, nil
}
func setNodePoolTags(scalingGroup *cs.ScalingGroup, d *schema.ResourceData) error {
if _, ok := d.GetOk("tags"); ok {
if tags, err := ConvertCsTags(d); err == nil {
scalingGroup.Tags = tags
}
}
return nil
}
func setNodePoolLabels(config *cs.KubernetesConfig, d *schema.ResourceData) error {
if v, ok := d.GetOk("labels"); ok && len(v.([]interface{})) > 0 {
vl := v.([]interface{})
labels := make([]cs.Label, 0)
for _, i := range vl {
if m, ok := i.(map[string]interface{}); ok {
labels = append(labels, cs.Label{
Key: m["key"].(string),
Value: m["value"].(string),
})
}
}
config.Labels = labels
}
return nil
}
func setNodePoolDataDisks(scalingGroup *cs.ScalingGroup, d *schema.ResourceData) error {
if dds, ok := d.GetOk("data_disks"); ok {
disks := dds.([]interface{})
createDataDisks := make([]cs.NodePoolDataDisk, 0, len(disks))
for _, e := range disks {
pack := e.(map[string]interface{})
dataDisk := cs.NodePoolDataDisk{
Size: pack["size"].(int),
DiskName: pack["name"].(string),
Category: pack["category"].(string),
Device: pack["device"].(string),
AutoSnapshotPolicyId: pack["auto_snapshot_policy_id"].(string),
KMSKeyId: pack["kms_key_id"].(string),
Encrypted: pack["encrypted"].(string),
PerformanceLevel: pack["performance_level"].(string),
}
createDataDisks = append(createDataDisks, dataDisk)
}
scalingGroup.DataDisks = createDataDisks
}
return nil
}
func setNodePoolTaints(config *cs.KubernetesConfig, d *schema.ResourceData) error {
if v, ok := d.GetOk("taints"); ok && len(v.([]interface{})) > 0 {
vl := v.([]interface{})
taints := make([]cs.Taint, 0)
for _, i := range vl {
if m, ok := i.(map[string]interface{}); ok {
taints = append(taints, cs.Taint{
Key: m["key"].(string),
Value: m["value"].(string),
Effect: cs.Effect(m["effect"].(string)),
})
}
}
config.Taints = taints
}
return nil
}
func setManagedNodepoolConfig(l []interface{}) (config cs.Management) {
if len(l) == 0 || l[0] == nil {
return config
}
m := l[0].(map[string]interface{})
// Once "management" is set, we think of it as creating a managed node pool
config.Enable = true
if v, ok := m["auto_repair"].(bool); ok {
config.AutoRepair = v
}
if v, ok := m["auto_upgrade"].(bool); ok {
config.UpgradeConf.AutoUpgrade = v
}
if v, ok := m["surge"].(int); ok {
config.UpgradeConf.Surge = int64(v)
}
if v, ok := m["surge_percentage"].(int); ok {
config.UpgradeConf.SurgePercentage = int64(v)
}
if v, ok := m["max_unavailable"].(int); ok {
config.UpgradeConf.MaxUnavailable = int64(v)
}
return config
}
func setAutoScalingConfig(l []interface{}) (config cs.AutoScaling) {
if len(l) == 0 || l[0] == nil {
return config
}
m := l[0].(map[string]interface{})
// Once "scaling_config" is set, we think of it as creating a auto scaling node pool
config.Enable = true
if v, ok := m["min_size"].(int); ok {
config.MinInstances = int64(v)
}
if v, ok := m["max_size"].(int); ok {
config.MaxInstances = int64(v)
}
if v, ok := m["type"].(string); ok {
config.Type = v
}
if v, ok := m["is_bond_eip"].(bool); ok {
config.IsBindEip = &v
}
if v, ok := m["eip_internet_charge_type"].(string); ok {
config.EipInternetChargeType = v
}
if v, ok := m["eip_bandwidth"].(int); ok {
config.EipBandWidth = int64(v)
}
return config
}
func setSpotPriceLimit(l []interface{}) (config []cs.SpotPrice) {
if len(l) == 0 || l[0] == nil {
return config
}
for _, v := range l {
if m, ok := v.(map[string]interface{}); ok {
config = append(config, cs.SpotPrice{
InstanceType: m["instance_type"].(string),
PriceLimit: m["price_limit"].(string),
})
}
}
return
}
func flattenSpotPriceLimit(config []cs.SpotPrice) (m []map[string]interface{}) {
if config == nil {
return []map[string]interface{}{}
}
for _, spotInfo := range config {
m = append(m, map[string]interface{}{
"instance_type": spotInfo.InstanceType,
"price_limit": spotInfo.PriceLimit,
})
}
return m
}
func flattenAutoScalingConfig(config *cs.AutoScaling) (m []map[string]interface{}) {
if config == nil {
return
}
m = append(m, map[string]interface{}{
"min_size": config.MinInstances,
"max_size": config.MaxInstances,
"type": config.Type,
"is_bond_eip": config.IsBindEip,
"eip_internet_charge_type": config.EipInternetChargeType,
"eip_bandwidth": config.EipBandWidth,
})
return
}
func flattenManagementNodepoolConfig(config *cs.Management) (m []map[string]interface{}) {
if config == nil {
return
}
m = append(m, map[string]interface{}{
"auto_repair": config.AutoRepair,
"auto_upgrade": config.UpgradeConf.AutoUpgrade,
"surge": config.UpgradeConf.Surge,
"surge_percentage": config.UpgradeConf.SurgePercentage,
"max_unavailable": config.UpgradeConf.MaxUnavailable,
})
return
}
func flattenNodeDataDisksConfig(config []cs.NodePoolDataDisk) (m []map[string]interface{}) {
if config == nil {
return []map[string]interface{}{}
}
for _, disks := range config {
m = append(m, map[string]interface{}{
"size": disks.Size,
"category": disks.Category,
"encrypted": disks.Encrypted,
"performance_level": disks.PerformanceLevel,
})
}
return m
}
func flattenTaintsConfig(config []cs.Taint) (m []map[string]interface{}) {
if config == nil {
return []map[string]interface{}{}
}
for _, taint := range config {
m = append(m, map[string]interface{}{
"key": taint.Key,
"value": taint.Value,
"effect": taint.Effect,
})
}
return m
}
func flattenLabelsConfig(config []cs.Label) (m []map[string]interface{}) {
if config == nil {
return []map[string]interface{}{}
}
for _, label := range config {
m = append(m, map[string]interface{}{
"key": label.Key,
"value": label.Value,
})
}
return m
}
func flattenTagsConfig(config []cs.Tag) map[string]string {
m := make(map[string]string, len(config))
if len(config) < 0 {
return m
}
for _, tag := range config {
if tag.Key != DefaultClusterTag {
m[tag.Key] = tag.Value
}
}
return m
}
func removeNodePoolNodes(d *schema.ResourceData, meta interface{}, parseId []string, oldNodes []interface{}, newNodes []interface{}) error {
client := meta.(*connectivity.AliyunClient)
csService := CsService{client}
invoker := NewInvoker()
var response interface{}
// list all nodes of the nodepool
if err := invoker.Run(func() error {
var err error
response, err = client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
nodes, _, err := csClient.GetKubernetesClusterNodes(parseId[0], common.Pagination{PageNumber: 1, PageSize: PageSizeLarge}, parseId[1])
return nodes, err
})
return err
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "GetKubernetesClusterNodes", DenverdinoAliyungo)
}
ret := response.([]cs.KubernetesNodeType)
// fetch the NodeName of all nodes
var allNodeName []string
for _, value := range ret {
allNodeName = append(allNodeName, value.NodeName)
}
removeNodesName := allNodeName
// remove automatically created nodes
if d.HasChange("node_count") {
o, n := d.GetChange("node_count")
count := o.(int) - n.(int)
removeNodesName = allNodeName[:count]
}
// remove manually added nodes
if d.HasChange("instances") {
var removeInstanceList []string
var attachNodeList []string
if oldNodes != nil && newNodes != nil {
attachNodeList = difference(expandStringList(oldNodes), expandStringList(newNodes))
}
if len(newNodes) == 0 {
attachNodeList = expandStringList(oldNodes)
}
for _, v := range ret {
for _, name := range attachNodeList {
if name == v.InstanceId {
removeInstanceList = append(removeInstanceList, v.NodeName)
}
}
}
removeNodesName = removeInstanceList
}
removeNodesArgs := &cs.DeleteKubernetesClusterNodesRequest{
Nodes: removeNodesName,
ReleaseNode: true,
DrainNode: false,
}
if err := invoker.Run(func() error {
var err error
response, err = client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
resp, err := csClient.DeleteKubernetesClusterNodes(parseId[0], removeNodesArgs)
return resp, err
})
return err
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DeleteKubernetesClusterNodes", DenverdinoAliyungo)
}
stateConf := BuildStateConf([]string{"removing"}, []string{"active"}, d.Timeout(schema.TimeoutUpdate), 30*time.Second, csService.CsKubernetesNodePoolStateRefreshFunc(d.Id(), []string{"deleting", "failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("node_count")
return nil
}
func attachExistingInstance(d *schema.ResourceData, meta interface{}) error {
csService := CsService{meta.(*connectivity.AliyunClient)}
client, err := meta.(*connectivity.AliyunClient).NewRoaCsClient()
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceName, "InitializeClient", err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
clusterId := parts[0]
nodePoolId := parts[1]
args := &roacs.AttachInstancesRequest{
NodepoolId: tea.String(nodePoolId),
FormatDisk: tea.Bool(false),
KeepInstanceName: tea.Bool(true),
}
if v, ok := d.GetOk("password"); ok {
args.Password = tea.String(v.(string))
}
if v, ok := d.GetOk("key_name"); ok {
args.KeyPair = tea.String(v.(string))
}
if v, ok := d.GetOk("format_disk"); ok {
args.FormatDisk = tea.Bool(v.(bool))
}
if v, ok := d.GetOk("keep_instance_name"); ok {
args.KeepInstanceName = tea.Bool(v.(bool))
}
if v, ok := d.GetOk("image_id"); ok {
args.ImageId = tea.String(v.(string))
}
if v, ok := d.GetOk("instances"); ok {
args.Instances = tea.StringSlice(expandStringList(v.([]interface{})))
}
_, err = client.AttachInstances(tea.String(clusterId), args)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceName, "AttachInstances", AliyunTablestoreGoSdk)
}
stateConf := BuildStateConf([]string{"scaling"}, []string{"active"}, d.Timeout(schema.TimeoutUpdate), 30*time.Second, csService.CsKubernetesNodePoolStateRefreshFunc(d.Id(), []string{"deleting", "failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
cs "github.com/alibabacloud-go/cs-20151215/v2/client"
"github.com/alibabacloud-go/tea/tea"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
const ResourceName = "resource_alicloud_cs_kubernetes_permissions"
func resourceAlicloudCSKubernetesPermissions() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCSKubernetesPermissionsCreate,
Read: resourceAlicloudCSKubernetesPermissionsRead,
Update: resourceAlicloudCSKubernetesPermissionsUpdate,
Delete: resourceAlicloudCSKubernetesPermissionsDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(90 * time.Minute),
Update: schema.DefaultTimeout(60 * time.Minute),
Delete: schema.DefaultTimeout(60 * time.Minute),
},
Schema: map[string]*schema.Schema{
"uid": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"permissions": {
Optional: true,
Type: schema.TypeSet,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"role_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"cluster", "namespace", "all-clusters"}, false),
},
"role_name": {
Type: schema.TypeString,
Required: true,
},
"cluster": {
Type: schema.TypeString,
Required: true,
},
"namespace": {
Type: schema.TypeString,
Optional: true,
},
"is_custom": {
Type: schema.TypeBool,
Optional: true,
},
"is_ram_role": {
Type: schema.TypeBool,
Optional: true,
},
},
},
},
},
}
}
func resourceAlicloudCSKubernetesPermissionsCreate(d *schema.ResourceData, meta interface{}) error {
client, err := meta.(*connectivity.AliyunClient).NewRoaCsClient()
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceName, "InitializeClient", err)
}
// Query existing permissions
uid := d.Get("uid").(string)
// Grant Permissions
// If other permissions with this right already exist, the existing permissions will be merged
grantPermissionsRequest := buildPermissionArgs(d)
err = resource.Retry(2*time.Minute, func() *resource.RetryError {
err := grantPermissionsForAddPerm(client, uid, grantPermissionsRequest)
if err == nil {
return resource.NonRetryableError(err)
}
time.Sleep(5 * time.Second)
return resource.RetryableError(Error("[ERROR] Grant user permission failed %s", d.Id()))
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceName, "GrantPermissions", AliyunTablestoreGoSdk)
}
addDebug("GrantPermissions", grantPermissionsRequest, err)
d.SetId(uid)
return resourceAlicloudCSKubernetesPermissionsRead(d, meta)
}
func resourceAlicloudCSKubernetesPermissionsRead(d *schema.ResourceData, meta interface{}) error {
d.Set("uid", d.Id())
return nil
}
func resourceAlicloudCSKubernetesPermissionsUpdate(d *schema.ResourceData, meta interface{}) error {
d.Partial(true)
client, err := meta.(*connectivity.AliyunClient).NewRoaCsClient()
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceName, "InitializeClient", err)
}
uid := d.Get("uid").(string)
// Update the permissions of the specified cluster.
// If other permissions of the cluster already exist, they will replace the existing permissions, and they will be added if they do not exist.
// Keep other existing cluster permissions.
if d.HasChange("permissions") {
oldValue, newValue := d.GetChange("permissions")
o := oldValue.(*schema.Set).List()
n := newValue.(*schema.Set).List()
// Remove all clusters permission
if len(n) == 0 {
err := grantPermissionsForDeleteSomeClusterPerms(client, uid, parseClusterIds(o))
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceName, "RemoveSomeClustersPermissions", err)
}
d.Partial(false)
return resourceAlicloudCSKubernetesPermissionsRead(d, meta)
}
// Remove some clusters permission
if len(n) > 0 && len(n) < len(o) {
// get difference cluster of permissions
clusters := difference(parseClusterIds(o), parseClusterIds(n))
err := grantPermissionsForDeleteSomeClusterPerms(client, uid, clusters)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceName, "RemoveSomeClustersPermissions", err)
}
d.Partial(false)
}
// update user permissions
updatePermissionsRequest := buildPermissionArgs(d)
err := grantPermissionsForUpdateSomeClusterPerms(client, uid, updatePermissionsRequest)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceName, "UpdateClusterPermissions", err)
}
d.Partial(false)
return resourceAlicloudCSKubernetesPermissionsRead(d, meta)
}
// Update all-clusters level permissions, if not exist, add new ones
// TODO
d.Partial(false)
return resourceAlicloudCSKubernetesPermissionsRead(d, meta)
}
func resourceAlicloudCSKubernetesPermissionsDelete(d *schema.ResourceData, meta interface{}) error {
client, err := meta.(*connectivity.AliyunClient).NewRoaCsClient()
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceName, "InitializeClient", err)
}
uid := d.Id()
// Remove up some clusters permissions owned by the user
if v, ok := d.GetOk("permissions"); ok {
if perms := v.(*schema.Set).List(); len(perms) > 0 {
err := grantPermissionsForDeleteSomeClusterPerms(client, uid, parseClusterIds(perms))
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceName, "RemoveSomeClustersPermissions", err)
}
}
}
return nil
}
func buildPermissionArgs(d *schema.ResourceData) []*cs.GrantPermissionsRequestBody {
var grantPermissionsRequest []*cs.GrantPermissionsRequestBody
if perms, ok := d.GetOk("permissions"); ok {
permissions := perms.(*schema.Set).List()
var perms *cs.GrantPermissionsRequestBody
for _, v := range permissions {
pack := v.(map[string]interface{})
perms = &cs.GrantPermissionsRequestBody{
Cluster: tea.String(pack["cluster"].(string)),
RoleName: tea.String(pack["role_name"].(string)),
RoleType: tea.String(pack["role_type"].(string)),
Namespace: tea.String(pack["namespace"].(string)),
IsCustom: tea.Bool(pack["is_custom"].(bool)),
IsRamRole: tea.Bool(pack["is_ram_role"].(bool)),
}
grantPermissionsRequest = append(grantPermissionsRequest, perms)
}
}
return grantPermissionsRequest
}
func convertDescribePermissionsToGrantPermissionsRequestBody(perms []*cs.DescribeUserPermissionResponseBody) []*cs.GrantPermissionsRequestBody {
var permReqs []*cs.GrantPermissionsRequestBody
for _, p := range perms {
p := p
req := &cs.GrantPermissionsRequestBody{
Cluster: nil,
IsCustom: nil,
RoleName: nil,
RoleType: tea.String("cluster"),
Namespace: nil,
IsRamRole: nil,
}
resourceId := ""
resourceType := tea.StringValue(p.ResourceType)
req.IsRamRole = tea.Bool(tea.Int64Value(p.IsRamRole) == 1)
if tea.StringValue(p.RoleType) == "custom" {
req.IsCustom = tea.Bool(true)
req.RoleName = tea.String(tea.StringValue(p.RoleName))
} else {
req.RoleName = tea.String(tea.StringValue(p.RoleType))
}
resourceId = tea.StringValue(p.ResourceId)
if strings.Contains(resourceId, "/") {
parts := strings.Split(resourceId, "/")
cluster := parts[0]
namespace := parts[1]
req.Cluster = tea.String(cluster)
req.Namespace = tea.String(namespace)
req.RoleType = tea.String("namespace")
} else if resourceType == "cluster" {
cluster := resourceId
req.Cluster = tea.String(cluster)
req.RoleType = tea.String("cluster")
}
if resourceType == "console" && resourceId == "all-clusters" {
req.RoleType = tea.String("all-clusters")
}
permReqs = append(permReqs, req)
}
return permReqs
}
func describeUserPermission(client *cs.Client, uid string) ([]*cs.DescribeUserPermissionResponseBody, error) {
resp, err := client.DescribeUserPermission(tea.String(uid))
if err != nil {
return nil, err
}
return resp.Body, nil
}
func grantPermissions(client *cs.Client, uid string, body []*cs.GrantPermissionsRequestBody) error {
if body == nil {
body = []*cs.GrantPermissionsRequestBody{}
}
req := &cs.GrantPermissionsRequest{
Body: body,
}
_, err := client.GrantPermissions(tea.String(uid), req)
if err != nil {
return err
}
return nil
}
func grantPermissionsForAddPerm(client *cs.Client, uid string, body []*cs.GrantPermissionsRequestBody) error {
existPerms, err := describeUserPermission(client, uid)
if err != nil {
return err
}
perms := convertDescribePermissionsToGrantPermissionsRequestBody(existPerms)
perms = append(perms, body...)
req := &cs.GrantPermissionsRequest{
Body: perms,
}
_, err = client.GrantPermissions(tea.String(uid), req)
if err != nil {
return err
}
return nil
}
func grantPermissionsForUpdateSomeClusterPerms(client *cs.Client, uid string, body []*cs.GrantPermissionsRequestBody) error {
describePerms, err := describeUserPermission(client, uid)
if err != nil {
return err
}
existPerms := convertDescribePermissionsToGrantPermissionsRequestBody(describePerms)
newPerms := []*cs.GrantPermissionsRequestBody{}
toUpdatePermMap := map[string][]*cs.GrantPermissionsRequestBody{}
for _, p := range body {
p := p
cluster := tea.StringValue(p.Cluster)
if _, ok := toUpdatePermMap[cluster]; !ok {
toUpdatePermMap[cluster] = []*cs.GrantPermissionsRequestBody{}
}
toUpdatePermMap[cluster] = append(toUpdatePermMap[cluster], p)
}
for _, p := range existPerms {
p := p
cluster := tea.StringValue(p.Cluster)
if v, ok := toUpdatePermMap[cluster]; ok {
newPerms = append(newPerms, v...)
delete(toUpdatePermMap, cluster)
} else {
newPerms = append(newPerms, p)
}
}
for _, p := range toUpdatePermMap {
newPerms = append(newPerms, p...)
}
req := &cs.GrantPermissionsRequest{
Body: newPerms,
}
_, err = client.GrantPermissions(tea.String(uid), req)
if err != nil {
return err
}
return nil
}
func grantPermissionsForDeleteSomeClusterPerms(client *cs.Client, uid string, clusters []string) error {
describePerms, err := describeUserPermission(client, uid)
if err != nil {
return err
}
existPerms := convertDescribePermissionsToGrantPermissionsRequestBody(describePerms)
var newPerms []*cs.GrantPermissionsRequestBody
toDeleteClusterMap := map[string]bool{}
for _, c := range clusters {
toDeleteClusterMap[c] = true
}
for _, p := range existPerms {
p := p
cluster := tea.StringValue(p.Cluster)
if !toDeleteClusterMap[cluster] {
newPerms = append(newPerms, p)
}
}
req := &cs.GrantPermissionsRequest{
Body: newPerms,
}
if len(clusters) > 0 && len(newPerms) == 0 {
req = &cs.GrantPermissionsRequest{Body: []*cs.GrantPermissionsRequestBody{}}
}
_, err = client.GrantPermissions(tea.String(uid), req)
if err != nil {
return err
}
return nil
}
func parseClusterIds(perms []interface{}) []string {
var clusters []string
for _, v := range perms {
m := v.(map[string]interface{})
clusters = append(clusters, m["cluster"].(string))
}
return clusters
}
func difference(slice1 []string, slice2 []string) []string {
var diff []string
for i := 0; i < 2; i++ {
for _, s1 := range slice1 {
found := false
for _, s2 := range slice2 {
if s1 == s2 {
found = true
break
}
}
if !found {
diff = append(diff, s1)
}
}
if i == 0 {
slice1, slice2 = slice2, slice1
}
}
return diff
}
package alicloud
import (
"fmt"
"regexp"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/denverdino/aliyungo/common"
"github.com/denverdino/aliyungo/cs"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCSManagedKubernetes() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCSManagedKubernetesCreate,
Read: resourceAlicloudCSKubernetesRead,
Update: resourceAlicloudCSKubernetesUpdate,
Delete: resourceAlicloudCSKubernetesDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(90 * time.Minute),
Update: schema.DefaultTimeout(60 * time.Minute),
Delete: schema.DefaultTimeout(60 * time.Minute),
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringLenBetween(1, 63),
ConflictsWith: []string{"name_prefix"},
},
"name_prefix": {
Type: schema.TypeString,
Optional: true,
Default: "Terraform-Creation",
ValidateFunc: validation.StringLenBetween(0, 37),
ConflictsWith: []string{"name"},
},
// worker configurations
"worker_vswitch_ids": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^vsw-[a-z0-9]*$`), "should start with 'vsw-'."),
},
MinItems: 1,
},
"worker_instance_types": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
MaxItems: 10,
},
"worker_number": {
Type: schema.TypeInt,
Optional: true,
},
"worker_disk_size": {
Type: schema.TypeInt,
Optional: true,
Default: 40,
ValidateFunc: validation.IntBetween(20, 32768),
},
"worker_disk_category": {
Type: schema.TypeString,
Optional: true,
Default: DiskCloudEfficiency,
},
"worker_disk_performance_level": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"PL0", "PL1", "PL2", "PL3"}, false),
DiffSuppressFunc: workerDiskPerformanceLevelDiffSuppressFunc,
},
"worker_disk_snapshot_policy_id": {
Type: schema.TypeString,
Optional: true,
},
"worker_data_disk_size": {
Type: schema.TypeInt,
Optional: true,
Default: 40,
ValidateFunc: validation.IntBetween(20, 32768),
DiffSuppressFunc: workerDataDiskSizeSuppressFunc,
},
"worker_data_disk_category": {
Type: schema.TypeString,
Optional: true,
},
"worker_instance_charge_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{string(common.PrePaid), string(common.PostPaid)}, false),
Default: PostPaid,
},
"worker_data_disks": {
Optional: true,
Type: schema.TypeList,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"size": {
Type: schema.TypeString,
Optional: true,
},
"category": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"all", "cloud", "ephemeral_ssd", "cloud_essd", "cloud_efficiency", "cloud_ssd", "local_disk"}, false),
},
"snapshot_id": {
Type: schema.TypeString,
Optional: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
},
"device": {
Type: schema.TypeString,
Optional: true,
},
"kms_key_id": {
Type: schema.TypeString,
Optional: true,
},
"encrypted": {
Type: schema.TypeString,
Optional: true,
},
"auto_snapshot_policy_id": {
Type: schema.TypeString,
Optional: true,
},
"performance_level": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"worker_period_unit": {
Type: schema.TypeString,
Optional: true,
Default: Month,
ValidateFunc: validation.StringInSlice([]string{"Week", "Month"}, false),
DiffSuppressFunc: csKubernetesWorkerPostPaidDiffSuppressFunc,
},
"worker_period": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
ValidateFunc: validation.Any(
validation.IntBetween(1, 9),
validation.IntInSlice([]int{12, 24, 36, 48, 60})),
DiffSuppressFunc: csKubernetesWorkerPostPaidDiffSuppressFunc,
},
"worker_auto_renew": {
Type: schema.TypeBool,
Default: false,
Optional: true,
DiffSuppressFunc: csKubernetesWorkerPostPaidDiffSuppressFunc,
},
"worker_auto_renew_period": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 6, 12}),
DiffSuppressFunc: csKubernetesWorkerPostPaidDiffSuppressFunc,
},
"exclude_autoscaler_nodes": {
Type: schema.TypeBool,
Default: false,
Optional: true,
},
// global configurations
"pod_vswitch_ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^vsw-[a-z0-9]*$`), "should start with 'vsw-'."),
},
MaxItems: 10,
},
"pod_cidr": {
Type: schema.TypeString,
Optional: true,
},
"service_cidr": {
Type: schema.TypeString,
Optional: true,
},
"node_cidr_mask": {
Type: schema.TypeInt,
Optional: true,
Default: KubernetesClusterNodeCIDRMasksByDefault,
ValidateFunc: validation.IntBetween(24, 28),
},
"enable_ssh": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"new_nat_gateway": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
ConflictsWith: []string{"key_name", "kms_encrypted_password"},
},
"key_name": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"password", "kms_encrypted_password"},
},
"kms_encrypted_password": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"password", "key_name"},
},
"kms_encryption_context": {
Type: schema.TypeMap,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("kms_encrypted_password").(string) == ""
},
Elem: schema.TypeString,
},
"user_ca": {
Type: schema.TypeString,
Optional: true,
},
"image_id": {
Type: schema.TypeString,
Optional: true,
},
"install_cloud_monitor": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"version": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
// cpu policy options of kubelet
"cpu_policy": {
Type: schema.TypeString,
Optional: true,
Default: "none",
ValidateFunc: validation.StringInSlice([]string{"none", "static"}, false),
},
"proxy_mode": {
Type: schema.TypeString,
Optional: true,
Default: "ipvs",
ValidateFunc: validation.StringInSlice([]string{"iptables", "ipvs"}, false),
},
"addons": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
},
"config": {
Type: schema.TypeString,
Optional: true,
},
"disabled": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
},
},
"slb_internet_enabled": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"load_balancer_spec": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"slb.s1.small", "slb.s2.small", "slb.s2.medium", "slb.s3.small", "slb.s3.medium", "slb.s3.large"}, false),
Default: "slb.s1.small",
},
"deletion_protection": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"timezone": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"os_type": {
Type: schema.TypeString,
Optional: true,
Default: "Linux",
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Windows", "Linux"}, false),
},
"platform": {
Type: schema.TypeString,
Optional: true,
Default: "CentOS",
ForceNew: true,
},
"node_port_range": {
Type: schema.TypeString,
Optional: true,
Default: "30000-32767",
ForceNew: true,
},
"cluster_domain": {
Type: schema.TypeString,
Optional: true,
Default: "cluster.local",
ForceNew: true,
Description: "cluster local domain ",
},
"runtime": {
Type: schema.TypeMap,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Default: "docker",
},
"version": {
Type: schema.TypeString,
Optional: true,
Default: "19.03.5",
},
},
},
},
"taints": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Optional: true,
},
"value": {
Type: schema.TypeString,
Optional: true,
},
"effect": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"NoSchedule", "NoExecute", "PreferNoSchedule"}, false),
},
},
},
},
"rds_instances": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"custom_san": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"encryption_provider_key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: "disk encryption key, only in ack-pro",
},
// computed parameters
"kube_config": {
Type: schema.TypeString,
Optional: true,
},
"client_cert": {
Type: schema.TypeString,
Optional: true,
},
"client_key": {
Type: schema.TypeString,
Optional: true,
},
"cluster_ca_cert": {
Type: schema.TypeString,
Optional: true,
},
"certificate_authority": {
Type: schema.TypeMap,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cluster_cert": {
Type: schema.TypeString,
Computed: true,
},
"client_cert": {
Type: schema.TypeString,
Computed: true,
},
"client_key": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"connections": {
Type: schema.TypeMap,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"api_server_internet": {
Type: schema.TypeString,
Computed: true,
},
"api_server_intranet": {
Type: schema.TypeString,
Computed: true,
},
"master_public_ip": {
Type: schema.TypeString,
Computed: true,
},
"service_domain": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"slb_id": {
Type: schema.TypeString,
Computed: true,
Deprecated: "Field 'slb_id' has been deprecated from provider version 1.9.2. New field 'slb_internet' replaces it.",
},
"slb_internet": {
Type: schema.TypeString,
Computed: true,
},
"slb_intranet": {
Type: schema.TypeString,
Computed: true,
},
"security_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"is_enterprise_security_group": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
ConflictsWith: []string{"security_group_id"},
},
"nat_gateway_id": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"worker_nodes": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"private_ip": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"availability_zone": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
// remove parameters below
// mix vswitch_ids between master and worker is not a good guidance to create cluster
"vswitch_ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^vsw-[a-z0-9]*$`), "should start with 'vsw-'."),
},
MinItems: 3,
MaxItems: 5,
Removed: "Field 'vswitch_ids' has been deprecated from provider version 1.75.0. New field 'master_vswitch_ids' and 'worker_vswitch_ids' replace it.",
},
// force update is a high risk operation
"force_update": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Removed: "Field 'force_update' has been removed from provider version 1.75.0.",
},
// worker_numbers in array is a hell of management
"worker_numbers": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeInt,
Default: 3,
},
MinItems: 1,
MaxItems: 3,
Removed: "Field 'worker_numbers' has been removed from provider version 1.75.0. New field 'worker_number' replaces it.",
},
"cluster_network_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{KubernetesClusterNetworkTypeFlannel, KubernetesClusterNetworkTypeTerway}, false),
Removed: "Field 'cluster_network_type' has been removed from provider version 1.75.0. New field 'addons' replaces it.",
},
// too hard to use this config
"log_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"type": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{KubernetesClusterLoggingTypeSLS}, false),
Required: true,
},
"project": {
Type: schema.TypeString,
Optional: true,
},
},
},
Removed: "Field 'log_config' has been removed from provider version 1.75.0. New field 'addons' replaces it.",
},
"worker_instance_type": {
Type: schema.TypeString,
Optional: true,
Removed: "Field 'worker_instance_type' has been removed from provider version 1.75.0. New field 'worker_instance_types' replaces it.",
},
"user_data": {
Type: schema.TypeString,
Optional: true,
},
"node_name_mode": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^customized,[a-z0-9]([-a-z0-9\.])*,([5-9]|[1][0-2]),([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`), "Each node name consists of a prefix, an IP substring, and a suffix. For example, if the node IP address is 192.168.0.55, the prefix is aliyun.com, IP substring length is 5, and the suffix is test, the node name will be aliyun.com00055test."),
},
"worker_ram_role_name": {
Type: schema.TypeString,
Computed: true,
},
"service_account_issuer": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"api_audiences": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
ForceNew: true,
},
"tags": {
Type: schema.TypeMap,
Optional: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"cluster_spec": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"ack.standard", "ack.pro.small"}, false),
},
"maintenance_window": {
Type: schema.TypeList,
Optional: true,
Computed: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeBool,
Required: true,
},
"maintenance_time": {
Type: schema.TypeString,
Required: true,
},
"duration": {
Type: schema.TypeString,
Required: true,
},
"weekly_period": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"control_plane_log_ttl": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"control_plane_log_project": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"control_plane_log_components": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
MinItems: 1,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"retain_resources": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
}
}
func resourceAlicloudCSManagedKubernetesCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
invoker := NewInvoker()
csService := CsService{client}
args, err := buildKubernetesArgs(d, meta)
if err != nil {
return WrapError(err)
}
var requestInfo *cs.Client
var response interface{}
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
args.RegionId = common.Region(client.RegionId)
args.ClusterType = cs.ManagedKubernetes
return csClient.CreateManagedKubernetesCluster(&cs.ManagedKubernetesClusterCreationRequest{
ClusterArgs: args.ClusterArgs,
WorkerArgs: args.WorkerArgs,
})
})
response = raw
return err
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cs_managed_kubernetes", "CreateKubernetesCluster", response)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["RegionId"] = common.Region(client.RegionId)
requestMap["Args"] = args
addDebug("CreateKubernetesCluster", response, requestInfo, requestMap)
}
cluster, _ := response.(*cs.ClusterCommonResponse)
d.SetId(cluster.ClusterID)
stateConf := BuildStateConf([]string{"initial"}, []string{"running"}, d.Timeout(schema.TimeoutCreate), 10*time.Second, csService.CsKubernetesInstanceStateRefreshFunc(d.Id(), []string{"deleting", "failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudCSKubernetesRead(d, meta)
}
func UpgradeAlicloudKubernetesCluster(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
if d.HasChange("version") {
nextVersion := d.Get("version").(string)
args := &cs.UpgradeClusterArgs{
Version: nextVersion,
}
csService := CsService{client}
err := csService.UpgradeCluster(d.Id(), args)
if err != nil {
return WrapError(err)
}
d.SetPartial("version")
}
return nil
}
func migrateAlicloudManagedKubernetesCluster(d *schema.ResourceData, meta interface{}) error {
action := "MigrateCluster"
client := meta.(*connectivity.AliyunClient)
csService := CsService{client}
migrateClusterRequest := map[string]string{
"type": "ManagedKubernetes",
"spec": d.Get("cluster_spec").(string),
}
conn, err := meta.(*connectivity.AliyunClient).NewTeaRoaCommonClient(connectivity.OpenAckService)
if err != nil {
return WrapError(err)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequestWithAction(StringPointer(action), StringPointer("2015-12-15"), nil, StringPointer("POST"), StringPointer("AK"), String(fmt.Sprintf("/clusters/%s/migrate", d.Id())), nil, nil, migrateClusterRequest, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"QPS Limit Exceeded"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
addDebug(action, response, nil)
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
stateConf := BuildStateConf([]string{"migrating"}, []string{"running"}, d.Timeout(schema.TimeoutUpdate), 20*time.Second, csService.CsKubernetesInstanceStateRefreshFunc(d.Id(), []string{"deleting", "failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return err
}
d.SetPartial("cluster_spec")
return nil
}
func updateKubernetesClusterTag(d *schema.ResourceData, meta interface{}) error {
action := "ModifyClusterTags"
client := meta.(*connectivity.AliyunClient)
csService := CsService{client}
var modifyClusterTagsRequest []cs.Tag
if tags, err := ConvertCsTags(d); err == nil {
modifyClusterTagsRequest = tags
}
d.SetPartial("tags")
conn, err := meta.(*connectivity.AliyunClient).NewTeaRoaCommonClient(connectivity.OpenAckService)
if err != nil {
return WrapError(err)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequestWithAction(StringPointer(action), StringPointer("2015-12-15"), nil, StringPointer("POST"), StringPointer("AK"), String(fmt.Sprintf("/clusters/%s/tags", d.Id())), nil, nil, modifyClusterTagsRequest, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"QPS Limit Exceeded"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
addDebug(action, response, nil)
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
stateConf := BuildStateConf([]string{"updating"}, []string{"running"}, d.Timeout(schema.TimeoutUpdate), 60*time.Second, csService.CsKubernetesInstanceStateRefreshFunc(d.Id(), []string{"deleting", "failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return err
}
if err != nil {
return err
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
roacs "github.com/alibabacloud-go/cs-20151215/v2/client"
"github.com/alibabacloud-go/tea/tea"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/denverdino/aliyungo/common"
"github.com/denverdino/aliyungo/cs"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCSServerlessKubernetes() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCSServerlessKubernetesCreate,
Read: resourceAlicloudCSServerlessKubernetesRead,
Update: resourceAlicloudCSServerlessKubernetesUpdate,
Delete: resourceAlicloudCSServerlessKubernetesDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(60 * time.Minute),
Delete: schema.DefaultTimeout(30 * time.Minute),
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringLenBetween(1, 63),
ConflictsWith: []string{"name_prefix"},
},
"name_prefix": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(0, 37),
ConflictsWith: []string{"name"},
},
"vpc_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Deprecated: "Field 'vswitch_id' has been deprecated from provider version 1.91.0. New field 'vswitch_ids' replace it.",
},
"vswitch_ids": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^vsw-[a-z0-9]*$`), "should start with 'vsw-'."),
},
MinItems: 1,
ConflictsWith: []string{"vswitch_id"},
},
"service_cidr": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"new_nat_gateway": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: true,
},
"deletion_protection": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"private_zone": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
ConflictsWith: []string{"service_discovery_types"},
Deprecated: "Field 'private_zone' has been deprecated from provider version 1.123.1. New field 'service_discovery_types' replace it.",
},
"service_discovery_types": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"CoreDNS", "PrivateZone"}, false),
},
ConflictsWith: []string{"private_zone"},
},
"zone_id": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
},
"endpoint_public_access_enabled": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: false,
},
"kube_config": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
},
"client_cert": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
},
"client_key": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
},
"cluster_ca_cert": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
},
"tags": {
Type: schema.TypeMap,
Optional: true,
},
"force_update": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: false,
},
"security_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"addons": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
},
"config": {
Type: schema.TypeString,
Optional: true,
},
"disabled": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
},
},
"version": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"load_balancer_spec": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"slb.s1.small", "slb.s2.small", "slb.s2.medium", "slb.s3.small", "slb.s3.medium", "slb.s3.large"}, false),
Default: "slb.s1.small",
},
"logging_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "SLS",
},
"sls_project_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"time_zone": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"retain_resources": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
}
}
func resourceAlicloudCSServerlessKubernetesCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
invoker := NewInvoker()
csService := CsService{client}
var clusterName string
if v, ok := d.GetOk("name"); ok {
clusterName = v.(string)
} else {
clusterName = resource.PrefixedUniqueId(d.Get("name_prefix").(string))
}
tags := make([]cs.Tag, 0)
tagsMap, ok := d.Get("tags").(map[string]interface{})
if ok {
for key, value := range tagsMap {
if value != nil {
if v, ok := value.(string); ok {
tags = append(tags, cs.Tag{
Key: key,
Value: v,
})
}
}
}
}
addons := make([]cs.Addon, 0)
if v, ok := d.GetOk("addons"); ok {
all, ok := v.([]interface{})
if ok {
for _, a := range all {
addon, ok := a.(map[string]interface{})
if ok {
addons = append(addons, cs.Addon{
Name: addon["name"].(string),
Config: addon["config"].(string),
Disabled: addon["disabled"].(bool),
})
}
}
}
}
args := &cs.ServerlessCreationArgs{
Name: clusterName,
ClusterType: cs.ClusterTypeServerlessKubernetes,
RegionId: client.RegionId,
VpcId: d.Get("vpc_id").(string),
EndpointPublicAccess: d.Get("endpoint_public_access_enabled").(bool),
NatGateway: d.Get("new_nat_gateway").(bool),
SecurityGroupId: d.Get("security_group_id").(string),
Addons: addons,
KubernetesVersion: d.Get("version").(string),
DeletionProtection: d.Get("deletion_protection").(bool),
ResourceGroupId: d.Get("resource_group_id").(string),
}
if v, ok := d.GetOk("time_zone"); ok {
args.TimeZone = v.(string)
}
if v, ok := d.GetOk("zone_id"); ok {
args.ZoneID = v.(string)
}
if v, ok := d.GetOk("service_cidr"); ok {
args.ServiceCIDR = v.(string)
}
if v, ok := d.GetOk("logging_type"); ok {
args.LoggingType = v.(string)
}
if v, ok := d.GetOk("sls_project_name"); ok {
args.SLSProjectName = v.(string)
}
if v, ok := d.GetOk("service_discovery_types"); ok {
args.ServiceDiscoveryTypes = expandStringList(v.([]interface{}))
}
if v, ok := d.GetOkExists("private_zone"); ok {
args.ServiceDiscoveryTypes = []string{}
if v.(bool) == true {
args.ServiceDiscoveryTypes = []string{"PrivateZone"}
}
}
if v := d.Get("vswitch_id").(string); v != "" {
args.VSwitchId = v
}
if v, ok := d.GetOk("vswitch_ids"); ok {
args.VswitchIds = expandStringList(v.([]interface{}))
}
if lbSpec, ok := d.GetOk("load_balancer_spec"); ok {
args.LoadBalancerSpec = lbSpec.(string)
}
//set tags
if len(tags) > 0 {
args.Tags = tags
}
var requestInfo *cs.Client
var response interface{}
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
return csClient.CreateServerlessKubernetesCluster(args)
})
response = raw
return err
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cs_serverless_kubernetes", "CreateServerlessKubernetesCluster", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["RegionId"] = common.Region(client.RegionId)
requestMap["Args"] = args
addDebug("CreateServerlessKubernetesCluster", response, requestInfo, requestMap)
}
cluster, _ := response.(*cs.ClusterCommonResponse)
d.SetId(cluster.ClusterID)
stateConf := BuildStateConf([]string{"initial"}, []string{"running"}, d.Timeout(schema.TimeoutCreate), 30*time.Second, csService.CsServerlessKubernetesInstanceStateRefreshFunc(d.Id(), []string{"deleting", "failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudCSServerlessKubernetesRead(d, meta)
}
func resourceAlicloudCSServerlessKubernetesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
csService := CsService{client}
invoker := NewInvoker()
rosClient, err := client.NewRoaCsClient()
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceName, "InitializeClient", err)
}
object, err := csService.DescribeCsServerlessKubernetes(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
vswitchIds := []string{}
resources, _ := rosClient.DescribeClusterResources(tea.String(d.Id()))
for _, resource := range resources.Body {
if tea.StringValue(resource.ResourceType) == "VSWITCH" {
vswitchIds = append(vswitchIds, tea.StringValue(resource.InstanceId))
}
}
d.Set("name", object.Name)
d.Set("vpc_id", object.VpcId)
d.Set("vswitch_id", object.VSwitchId)
d.Set("vswitch_ids", vswitchIds)
d.Set("security_group_id", object.SecurityGroupId)
d.Set("deletion_protection", object.DeletionProtection)
d.Set("version", object.CurrentVersion)
d.Set("resource_group_id", object.ResourceGroupId)
d.Set("cluster_spec", object.ClusterSpec)
if err := d.Set("tags", flattenTagsConfig(object.Tags)); err != nil {
return WrapError(err)
}
if d.Get("load_balancer_spec") == "" {
d.Set("load_balancer_spec", "slb.s1.small")
}
if d.Get("logging_type") == "" {
d.Set("logging_type", "SLS")
}
var requestInfo *cs.Client
var response interface{}
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
return csClient.GetClusterCerts(d.Id())
})
response = raw
return err
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "GetClusterCerts", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["ClusterId"] = d.Id()
addDebug("GetClusterCerts", response, requestInfo, requestMap)
}
cert, _ := response.(cs.ClusterCerts)
if ce, ok := d.GetOk("client_cert"); ok && ce.(string) != "" {
if err := writeToFile(ce.(string), cert.Cert); err != nil {
return WrapError(err)
}
}
if key, ok := d.GetOk("client_key"); ok && key.(string) != "" {
if err := writeToFile(key.(string), cert.Key); err != nil {
return WrapError(err)
}
}
if ca, ok := d.GetOk("cluster_ca_cert"); ok && ca.(string) != "" {
if err := writeToFile(ca.(string), cert.CA); err != nil {
return WrapError(err)
}
}
var config *cs.ClusterConfig
if file, ok := d.GetOk("kube_config"); ok && file.(string) != "" {
var requestInfo *cs.Client
if err := invoker.Run(func() error {
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
return csClient.DescribeClusterUserConfig(d.Id(), !d.Get("endpoint_public_access_enabled").(bool))
})
response = raw
return err
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "GetClusterConfig", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["ClusterId"] = d.Id()
addDebug("GetClusterConfig", response, requestInfo, requestMap)
}
config, _ = response.(*cs.ClusterConfig)
if err := writeToFile(file.(string), config.Config); err != nil {
return WrapError(err)
}
}
return nil
}
func resourceAlicloudCSServerlessKubernetesUpdate(d *schema.ResourceData, meta interface{}) error {
d.Partial(true)
// modify cluster tag
if d.HasChange("tags") {
err := updateKubernetesClusterTag(d, meta)
if err != nil {
return WrapErrorf(err, ResponseCodeMsg, d.Id(), "ModifyClusterTags", AlibabaCloudSdkGoERROR)
}
d.SetPartial("tags")
}
// upgrade cluster version
err := UpgradeAlicloudKubernetesCluster(d, meta)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "UpgradeClusterVersion", DenverdinoAliyungo)
}
if err := modifyKubernetesCluster(d, meta); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "ModifyCluster", DenverdinoAliyungo)
}
d.Partial(false)
return resourceAlicloudCSServerlessKubernetesRead(d, meta)
}
func resourceAlicloudCSServerlessKubernetesDelete(d *schema.ResourceData, meta interface{}) error {
csService := CsService{meta.(*connectivity.AliyunClient)}
client, err := meta.(*connectivity.AliyunClient).NewRoaCsClient()
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceName, "InitializeClient", err)
}
args := &roacs.DeleteClusterRequest{}
if v := d.Get("retain_resources"); len(v.([]interface{})) > 0 {
args.RetainResources = tea.StringSlice(expandStringList(v.([]interface{})))
}
_, err = client.DeleteCluster(tea.String(d.Id()), args)
if err != nil {
if IsExpectedErrors(err, []string{"ErrorClusterNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, ResourceName, "DeleteCluster", AliyunTablestoreGoSdk)
}
stateConf := BuildStateConf([]string{"running", "deleting"}, []string{}, d.Timeout(schema.TimeoutDelete), 30*time.Second, csService.CsServerlessKubernetesInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
func modifyKubernetesCluster(d *schema.ResourceData, meta interface{}) error {
var update bool
action := "ModifyCluster"
client := meta.(*connectivity.AliyunClient)
csService := CsService{client}
var modifyClusterRequest cs.ModifyClusterArgs
if d.HasChange("deletion_protection") {
update = true
modifyClusterRequest.DeletionProtection = d.Get("deletion_protection").(bool)
}
if update {
conn, err := meta.(*connectivity.AliyunClient).NewTeaRoaCommonClient(connectivity.OpenAckService)
if err != nil {
return WrapError(err)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequestWithAction(StringPointer(action), StringPointer("2015-12-15"), nil, StringPointer("PUT"), StringPointer("AK"), String(fmt.Sprintf("/api/v2/clusters/%s", d.Id())), nil, nil, modifyClusterRequest, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"QPS Limit Exceeded"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
addDebug(action, response, nil)
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
stateConf := BuildStateConf([]string{"updating"}, []string{"running"}, d.Timeout(schema.TimeoutUpdate), 10*time.Second, csService.CsKubernetesInstanceStateRefreshFunc(d.Id(), []string{"deleting", "failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return err
}
if err != nil {
return err
}
}
d.SetPartial("deletion_protection")
return nil
}
package alicloud
import (
"fmt"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
newsdk "github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/denverdino/aliyungo/common"
"github.com/denverdino/aliyungo/cs"
"github.com/denverdino/aliyungo/ecs"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudCSSwarm() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudCSSwarmCreate,
Read: resourceAlicloudCSSwarmRead,
Update: resourceAlicloudCSSwarmUpdate,
Delete: resourceAlicloudCSSwarmDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringLenBetween(1, 63),
ConflictsWith: []string{"name_prefix"},
},
"name_prefix": {
Type: schema.TypeString,
Optional: true,
Default: "Terraform-Creation",
ValidateFunc: validation.StringLenBetween(0, 37),
ConflictsWith: []string{"name"},
},
"size": {
Type: schema.TypeInt,
Optional: true,
Deprecated: "Field 'size' has been deprecated from provider version 1.9.1. New field 'node_number' replaces it.",
},
"node_number": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
ValidateFunc: validation.IntBetween(0, 50),
},
"cidr_block": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^ecs\..*`), "prefix must be 'ecs.'"),
},
"vswitch_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"password": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Sensitive: true,
},
"disk_size": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Default: 20,
ValidateFunc: validation.IntBetween(20, 32768),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("node_number").(int) == 0
},
},
"disk_category": {
Type: schema.TypeString,
Optional: true,
Default: ecs.DiskCategoryCloudEfficiency,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"all", "cloud", "ephemeral_ssd", "cloud_essd", "cloud_efficiency", "cloud_ssd", "local_disk"}, false),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("node_number").(int) == 0
},
},
"image_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"release_eip": {
Type: schema.TypeBool,
Optional: true,
Default: false,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return old != ""
},
},
"is_outdated": {
Type: schema.TypeBool,
Optional: true,
},
"need_slb": {
Type: schema.TypeBool,
Optional: true,
Default: true,
ForceNew: true,
},
"nodes": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"private_ip": {
Type: schema.TypeString,
Computed: true,
},
"eip": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"slb_id": {
Type: schema.TypeString,
Computed: true,
},
"security_group_id": {
Type: schema.TypeString,
Computed: true,
},
"agent_version": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudCSSwarmCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
vpcService := VpcService{client}
// Ensure instance_type is valid
//zoneId, validZones, _, err := ecsService.DescribeAvailableResources(d, meta, InstanceTypeResource)
//if err != nil {
// return err
//}
//if err := ecsService.InstanceTypeValidation(d.Get("instance_type").(string), zoneId, validZones); err != nil {
// return err
//}
var clusterName string
if v, ok := d.GetOk("name"); ok {
clusterName = v.(string)
} else {
clusterName = resource.PrefixedUniqueId(d.Get("name_prefix").(string))
}
args := &cs.ClusterCreationArgs{
Name: clusterName,
InstanceType: d.Get("instance_type").(string),
Password: d.Get("password").(string),
Size: int64(d.Get("node_number").(int)),
IOOptimized: ecs.IoOptimized("true"),
DataDiskCategory: ecs.DiskCategory(d.Get("disk_category").(string)),
DataDiskSize: int64(d.Get("disk_size").(int)),
NetworkMode: cs.VPCNetwork,
VSwitchID: d.Get("vswitch_id").(string),
SubnetCIDR: d.Get("cidr_block").(string),
ReleaseEipFlag: d.Get("release_eip").(bool),
NeedSLB: d.Get("need_slb").(bool),
}
vsw, err := vpcService.DescribeVSwitch(args.VSwitchID)
if err != nil {
return fmt.Errorf("Error DescribeVSwitches: %#v", err)
}
if vsw.CidrBlock == args.SubnetCIDR {
return fmt.Errorf("Container cluster's cidr_block only accepts 192.168.X.0/24 or 172.18.X.0/24 ~ 172.31.X.0/24. " +
"And it cannot be equal to vswitch's cidr_block and sub cidr block.")
}
args.VPCID = vsw.VpcId
if imageId, ok := d.GetOk("image_id"); ok {
if _, err := ecsService.DescribeImageById(imageId.(string)); err != nil {
return err
}
args.ECSImageID = imageId.(string)
}
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
return csClient.CreateCluster(common.Region(client.RegionId), args)
})
if err != nil {
return fmt.Errorf("Creating container Cluster got an error: %#v", err)
}
cluster, _ := raw.(cs.ClusterCommonResponse)
d.SetId(cluster.ClusterID)
_, err = client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
state := cs.Running
if args.Size == 0 {
state = cs.InActive
}
return nil, csClient.WaitForClusterAsyn(cluster.ClusterID, state, 500)
})
if err != nil {
return fmt.Errorf("Waitting for container Cluster %#v got an error: %#v", cs.Running, err)
}
return resourceAlicloudCSSwarmUpdate(d, meta)
}
func resourceAlicloudCSSwarmUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
d.Partial(true)
if d.HasChange("node_number") && !d.IsNewResource() {
o, n := d.GetChange("node_number")
oi := o.(int)
ni := n.(int)
if ni <= oi {
return fmt.Errorf("The node number must greater than the current. The cluster's current node number is %d.", oi)
}
d.SetPartial("node_number")
_, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
return nil, csClient.ResizeCluster(d.Id(), &cs.ClusterResizeArgs{
Size: int64(ni),
InstanceType: d.Get("instance_type").(string),
Password: d.Get("password").(string),
DataDiskCategory: ecs.DiskCategory(d.Get("disk_category").(string)),
DataDiskSize: int64(d.Get("disk_size").(int)),
ECSImageID: d.Get("image_id").(string),
IOOptimized: ecs.IoOptimized("true"),
})
})
if err != nil {
return fmt.Errorf("Resize Cluster got an error: %#v", err)
}
_, err = client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
state := cs.Running
if ni == 0 {
state = cs.InActive
}
return nil, csClient.WaitForClusterAsyn(d.Id(), state, 500)
})
if err != nil {
return fmt.Errorf("Waitting for container Cluster %#v got an error: %#v", cs.Running, err)
}
}
if !d.IsNewResource() && (d.HasChange("name") || d.HasChange("name_prefix")) {
var clusterName string
if v, ok := d.GetOk("name"); ok {
clusterName = v.(string)
} else {
clusterName = resource.PrefixedUniqueId(d.Get("name_prefix").(string))
}
_, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
return nil, csClient.ModifyClusterName(d.Id(), clusterName)
})
if err != nil && !IsExpectedErrors(err, []string{"ErrorClusterNameAlreadyExist"}) {
return fmt.Errorf("Modify Cluster Name got an error: %#v", err)
}
d.SetPartial("name")
d.SetPartial("name_prefix")
}
d.Partial(false)
return resourceAlicloudCSSwarmRead(d, meta)
}
func resourceAlicloudCSSwarmRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
csService := CsService{client}
ecsService := EcsService{client}
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
return csClient.DescribeCluster(d.Id())
})
if err != nil {
if IsExpectedErrors(err, []string{"ErrorClusterNotFound"}) {
d.SetId("")
return nil
}
return err
}
cluster, _ := raw.(cs.ClusterType)
d.Set("name", cluster.Name)
d.Set("node_number", cluster.Size)
d.Set("vpc_id", cluster.VPCID)
d.Set("vswitch_id", cluster.VSwitchID)
d.Set("security_group_id", cluster.SecurityGroupID)
d.Set("slb_id", cluster.ExternalLoadbalancerID)
d.Set("agent_version", cluster.AgentVersion)
pcluster, certs, err := csService.GetContainerClusterAndCertsByName(cluster.Name)
if err != nil {
return err
}
raw, err = client.WithCsProjectClient(pcluster.ClusterID, pcluster.MasterURL, *certs, func(csProjectClient *cs.ProjectClient) (interface{}, error) {
return csProjectClient.GetSwarmClusterNodes()
})
if err != nil {
return err
}
if cluster.Size > 0 {
resp, _ := raw.(cs.GetSwarmClusterNodesResponse)
var nodes []map[string]interface{}
var oneNode newsdk.Instance
for _, node := range resp {
mapping := map[string]interface{}{
"id": node.InstanceId,
"name": node.Name,
"private_ip": node.IP,
"status": node.Status,
}
inst, err := ecsService.DescribeInstance(node.InstanceId)
if err != nil {
return fmt.Errorf("[ERROR] QueryInstancesById %s: %#v.", node.InstanceId, err)
}
mapping["eip"] = inst.EipAddress.IpAddress
oneNode = inst
nodes = append(nodes, mapping)
}
d.Set("nodes", nodes)
d.Set("instance_type", oneNode.InstanceType)
disks, err := ecsService.DescribeDisksByType(oneNode.InstanceId, DiskTypeData)
if err != nil {
return fmt.Errorf("[ERROR] DescribeDisks By Id %s: %#v.", resp[0].InstanceId, err)
}
for _, disk := range disks {
d.Set("disk_size", disk.Size)
d.Set("disk_category", disk.Category)
}
} else {
d.Set("nodes", []map[string]interface{}{})
d.Set("disk_size", 0)
d.Set("disk_category", "")
}
return nil
}
func resourceAlicloudCSSwarmDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
return resource.Retry(3*time.Minute, func() *resource.RetryError {
_, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
return nil, csClient.DeleteCluster(d.Id())
})
if err != nil {
if IsExpectedErrors(err, []string{"ErrorClusterNotFound"}) {
return nil
}
return resource.RetryableError(fmt.Errorf("Deleting container cluster got an error: %#v", err))
}
raw, err := client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
return csClient.DescribeCluster(d.Id())
})
if err != nil {
if IsExpectedErrors(err, []string{"ErrorClusterNotFound"}) {
return nil
}
return resource.NonRetryableError(fmt.Errorf("Describe container cluster got an error: %#v", err))
}
resp, _ := raw.(cs.ClusterType)
if resp.ClusterID == "" {
return nil
}
return resource.RetryableError(fmt.Errorf("Deleting container cluster got an error: %#v", err))
})
}
package alicloud
import (
"fmt"
"log"
"path"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudDataWorksFolder() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDataWorksFolderCreate,
Read: resourceAlicloudDataWorksFolderRead,
Update: resourceAlicloudDataWorksFolderUpdate,
Delete: resourceAlicloudDataWorksFolderDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"folder_id": {
Type: schema.TypeString,
ForceNew: true,
Computed: true,
},
"folder_path": {
Type: schema.TypeString,
Required: true,
},
"project_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"project_identifier": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudDataWorksFolderCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateFolder"
request := make(map[string]interface{})
conn, err := client.NewDataworkspublicClient()
if err != nil {
return WrapError(err)
}
folderPath := ConvertDataWorksFrontEndFolderPathToBackEndFolderPath(d.Get("folder_path").(string))
request["FolderPath"] = folderPath
if v, ok := d.GetOk("project_id"); ok {
request["ProjectId"] = v
}
if v, ok := d.GetOk("project_identifier"); ok {
request["ProjectIdentifier"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-05-18"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_data_works_folder", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["Data"], ":", request["ProjectId"]))
return resourceAlicloudDataWorksFolderRead(d, meta)
}
func resourceAlicloudDataWorksFolderRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dataworksPublicService := DataworksPublicService{client}
object, err := dataworksPublicService.DescribeDataWorksFolder(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_data_works_folder dataworksPublicService.DescribeDataWorksFolder Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("folder_id", parts[0])
d.Set("project_id", parts[1])
d.Set("folder_path", object["FolderPath"].(string))
return nil
}
func resourceAlicloudDataWorksFolderUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"FolderId": parts[0],
"ProjectId": parts[1],
}
if d.HasChange("folder_path") {
folderPath := ConvertDataWorksFrontEndFolderPathToBackEndFolderPath(d.Get("folder_path").(string))
absolutePath := folderPath
_, lastDir := path.Split(absolutePath)
request["FolderName"] = lastDir
}
if v, ok := d.GetOk("project_identifier"); ok {
request["ProjectIdentifier"] = v
}
action := "UpdateFolder"
conn, err := client.NewDataworkspublicClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-05-18"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return resourceAlicloudDataWorksFolderRead(d, meta)
}
func resourceAlicloudDataWorksFolderDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteFolder"
var response map[string]interface{}
conn, err := client.NewDataworkspublicClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"FolderId": parts[0],
"ProjectId": parts[1],
}
if v, ok := d.GetOk("project_identifier"); ok {
request["ProjectIdentifier"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-05-18"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func getConvertMap() map[string]string {
convertMap := make(map[string]string)
convertMap["Business Flow"] = "业务流程"
convertMap["folderAlgm"] = "算法"
convertMap["folderCDH"] = "CDH"
convertMap["folderDi"] = "数据集成"
convertMap["folderFlink"] = "Flink"
convertMap["folderGeneral"] = "通用"
convertMap["folderHologres"] = "Hologres"
convertMap["folderMaxCompute"] = "MaxCompute"
convertMap["folderUserDefined"] = "自定义"
convertMap["folderEMR"] = "EMR"
convertMap["folderErd"] = "数据模型"
convertMap["folderADB"] = "AnalyticDB for PostgreSQL"
convertMap["folderJdbc"] = "数据库"
return convertMap
}
func ConvertDataWorksFrontEndFolderPathToBackEndFolderPath(source string) string {
result := source
convertMap := getConvertMap()
for convert := range convertMap {
result = strings.Replace(result, convert, convertMap[convert], 1)
}
return result
}
func ConvertDataWorksBackEndFolderPathToFrontEndFolderPath(source string) string {
result := source
convertMap := getConvertMap()
for convert := range convertMap {
result = strings.Replace(result, convertMap[convert], convert, 1)
}
return result
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudDatabaseGatewayGateway() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDatabaseGatewayGatewayCreate,
Read: resourceAlicloudDatabaseGatewayGatewayRead,
Update: resourceAlicloudDatabaseGatewayGatewayUpdate,
Delete: resourceAlicloudDatabaseGatewayGatewayDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"gateway_desc": {
Type: schema.TypeString,
Optional: true,
},
"gateway_name": {
Type: schema.TypeString,
Required: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudDatabaseGatewayGatewayCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateGateway"
request := make(map[string]interface{})
conn, err := client.NewDgClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("gateway_desc"); ok {
request["GatewayDesc"] = v
}
request["GatewayName"] = d.Get("gateway_name")
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-27"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_database_gateway_gateway", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetId(fmt.Sprint(response["Data"]))
return resourceAlicloudDatabaseGatewayGatewayRead(d, meta)
}
func resourceAlicloudDatabaseGatewayGatewayRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dgService := DgService{client}
object, err := dgService.DescribeDatabaseGatewayGateway(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_database_gateway_gateway dgService.DescribeDatabaseGatewayGateway Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("gateway_desc", object["gatewayDesc"])
d.Set("gateway_name", object["gatewayName"])
d.Set("status", object["status"])
return nil
}
func resourceAlicloudDatabaseGatewayGatewayUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"GatewayId": d.Id(),
}
if d.HasChange("gateway_desc") {
update = true
}
if v, ok := d.GetOk("gateway_desc"); ok {
request["GatewayDesc"] = v
}
if d.HasChange("gateway_name") {
update = true
}
request["GatewayName"] = d.Get("gateway_name")
if update {
action := "ModifyGateway"
conn, err := client.NewDgClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-27"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
}
return resourceAlicloudDatabaseGatewayGatewayRead(d, meta)
}
func resourceAlicloudDatabaseGatewayGatewayDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteGateway"
var response map[string]interface{}
conn, err := client.NewDgClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"GatewayId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-27"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
return nil
}
package alicloud
import (
"strconv"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/aliyun-datahub-sdk-go/datahub"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudDatahubProject() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunDatahubProjectCreate,
Read: resourceAliyunDatahubProjectRead,
Update: resourceAliyunDatahubProjectUpdate,
Delete: resourceAliyunDatahubProjectDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(3, 32),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return strings.ToLower(new) == strings.ToLower(old)
},
},
"comment": {
Type: schema.TypeString,
Optional: true,
Default: "project added by terraform",
ValidateFunc: validation.StringLenBetween(0, 255),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return strings.ToLower(new) == strings.ToLower(old)
},
},
"create_time": {
Type: schema.TypeString, //uint64 value from sdk
Computed: true,
},
"last_modify_time": {
Type: schema.TypeString, //uint64 value from sdk
Computed: true,
},
},
}
}
func resourceAliyunDatahubProjectCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
projectName := d.Get("name").(string)
projectComment := d.Get("comment").(string)
var requestInfo *datahub.DataHub
raw, err := client.WithDataHubClient(func(dataHubClient datahub.DataHubApi) (interface{}, error) {
requestInfo = dataHubClient.(*datahub.DataHub)
return dataHubClient.CreateProject(projectName, projectComment)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_datahub_project", "CreateProject", AliyunDatahubSdkGo)
}
if debugOn() {
requestMap := make(map[string]string)
requestMap["ProjectName"] = projectName
requestMap["ProjectComment"] = projectComment
addDebug("CreateProject", raw, requestInfo, requestMap)
}
d.SetId(strings.ToLower(projectName))
return resourceAliyunDatahubProjectRead(d, meta)
}
func resourceAliyunDatahubProjectRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
datahubService := DatahubService{client}
object, err := datahubService.DescribeDatahubProject(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.SetId(strings.ToLower(d.Id()))
d.Set("name", d.Id())
d.Set("comment", object.Comment)
d.Set("create_time", strconv.FormatInt(object.CreateTime, 10))
d.Set("last_modify_time", strconv.FormatInt(object.LastModifyTime, 10))
return nil
}
func resourceAliyunDatahubProjectUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
if d.HasChange("comment") {
projectName := d.Id()
projectComment := d.Get("comment").(string)
var requestInfo *datahub.DataHub
raw, err := client.WithDataHubClient(func(dataHubClient datahub.DataHubApi) (interface{}, error) {
requestInfo = dataHubClient.(*datahub.DataHub)
return dataHubClient.UpdateProject(projectName, projectComment)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "UpdateProject", AliyunDatahubSdkGo)
}
if debugOn() {
requestMap := make(map[string]string)
requestMap["ProjectName"] = projectName
requestMap["ProjectComment"] = projectComment
addDebug("UpdateProject", raw, requestInfo, requestMap)
}
}
return resourceAliyunDatahubProjectRead(d, meta)
}
func resourceAliyunDatahubProjectDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
datahubService := DatahubService{client}
projectName := d.Id()
var requestInfo *datahub.DataHub
err := resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := client.WithDataHubClient(func(dataHubClient datahub.DataHubApi) (interface{}, error) {
requestInfo = dataHubClient.(*datahub.DataHub)
return dataHubClient.DeleteProject(projectName)
})
if err != nil {
if isRetryableDatahubError(err) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if debugOn() {
requestMap := make(map[string]string)
requestMap["ProjectName"] = projectName
addDebug("DeleteProject", raw, requestInfo, requestMap)
}
return nil
})
if err != nil {
if isDatahubNotExistError(err) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DeleteProject", AliyunDatahubSdkGo)
}
return WrapError(datahubService.WaitForDatahubProject(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/aliyun-datahub-sdk-go/datahub"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudDatahubSubscription() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunDatahubSubscriptionCreate,
Read: resourceAliyunDatahubSubscriptionRead,
Update: resourceAliyunDatahubSubscriptionUpdate,
Delete: resourceAliyunDatahubSubscriptionDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"project_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(3, 32),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return strings.ToLower(new) == strings.ToLower(old)
},
},
"topic_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(1, 128),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return strings.ToLower(new) == strings.ToLower(old)
},
},
"comment": {
Type: schema.TypeString,
Optional: true,
Default: "subscription added by terraform",
ValidateFunc: validation.StringLenBetween(0, 255),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return strings.ToLower(new) == strings.ToLower(old)
},
},
"sub_id": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString, //uint64 value from sdk
Computed: true,
},
"last_modify_time": {
Type: schema.TypeString, //uint64 value from sdk
Computed: true,
},
},
}
}
func resourceAliyunDatahubSubscriptionCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
projectName := d.Get("project_name").(string)
topicName := d.Get("topic_name").(string)
subComment := d.Get("comment").(string)
var requestInfo *datahub.DataHub
raw, err := client.WithDataHubClient(func(dataHubClient datahub.DataHubApi) (interface{}, error) {
requestInfo = dataHubClient.(*datahub.DataHub)
return dataHubClient.CreateSubscription(projectName, topicName, subComment)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_datahub_subscription", "CreateSubscription", AliyunDatahubSdkGo)
}
subscriptionResult := raw.(*datahub.CreateSubscriptionResult)
if debugOn() {
requestMap := make(map[string]string)
requestMap["ProjectName"] = projectName
requestMap["TopicName"] = topicName
requestMap["SubComment"] = subComment
addDebug("CreateSubscription", raw, requestInfo, requestMap)
}
d.SetId(fmt.Sprintf("%s%s%s%s%s", strings.ToLower(projectName), COLON_SEPARATED, strings.ToLower(topicName), COLON_SEPARATED, subscriptionResult.SubId))
return resourceAliyunDatahubSubscriptionRead(d, meta)
}
func resourceAliyunDatahubSubscriptionRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
datahubService := DatahubService{client}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
projectName := parts[0]
object, err := datahubService.DescribeDatahubSubscription(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.SetId(fmt.Sprintf("%s%s%s%s%s", strings.ToLower(projectName), COLON_SEPARATED, strings.ToLower(object.TopicName), COLON_SEPARATED, object.SubId))
d.Set("project_name", projectName)
d.Set("topic_name", object.TopicName)
d.Set("sub_id", object.SubId)
d.Set("comment", object.Comment)
d.Set("create_time", strconv.FormatInt(object.CreateTime, 10))
d.Set("last_modify_time", strconv.FormatInt(object.LastModifyTime, 10))
return nil
}
func resourceAliyunDatahubSubscriptionUpdate(d *schema.ResourceData, meta interface{}) error {
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
projectName, topicName, subId := parts[0], parts[1], parts[2]
client := meta.(*connectivity.AliyunClient)
if d.HasChange("comment") {
subComment := d.Get("comment").(string)
var requestInfo *datahub.DataHub
raw, err := client.WithDataHubClient(func(dataHubClient datahub.DataHubApi) (interface{}, error) {
requestInfo = dataHubClient.(*datahub.DataHub)
return dataHubClient.UpdateSubscription(projectName, topicName, subId, subComment)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "UpdateSubscription", AliyunDatahubSdkGo)
}
if debugOn() {
requestMap := make(map[string]string)
requestMap["ProjectName"] = projectName
requestMap["TopicName"] = topicName
requestMap["SubId"] = subId
requestMap["SubComment"] = subComment
addDebug("UpdateSubscription", raw, requestInfo, requestMap)
}
}
return resourceAliyunDatahubSubscriptionRead(d, meta)
}
func resourceAliyunDatahubSubscriptionDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
datahubService := DatahubService{client}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
projectName, topicName, subId := parts[0], parts[1], parts[2]
var requestInfo *datahub.DataHub
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := client.WithDataHubClient(func(dataHubClient datahub.DataHubApi) (interface{}, error) {
requestInfo = dataHubClient.(*datahub.DataHub)
return dataHubClient.DeleteSubscription(projectName, topicName, subId)
})
if err != nil {
if isRetryableDatahubError(err) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if debugOn() {
requestMap := make(map[string]string)
requestMap["ProjectName"] = projectName
requestMap["TopicName"] = topicName
requestMap["SubId"] = subId
addDebug("DeleteSubscription", raw, requestInfo, requestMap)
}
return nil
})
if err != nil {
if isDatahubNotExistError(err) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DeleteSubscription", AliyunDatahubSdkGo)
}
return WrapError(datahubService.WaitForDatahubSubscription(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"strconv"
"strings"
"time"
"github.com/aliyun/aliyun-datahub-sdk-go/datahub"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudDatahubTopic() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunDatahubTopicCreate,
Read: resourceAliyunDatahubTopicRead,
Update: resourceAliyunDatahubTopicUpdate,
Delete: resourceAliyunDatahubTopicDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"project_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(3, 32),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return strings.ToLower(new) == strings.ToLower(old)
},
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(1, 128),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return strings.ToLower(new) == strings.ToLower(old)
},
},
"shard_count": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Default: 1,
ValidateFunc: validation.IntBetween(1, 10),
},
"life_cycle": {
Type: schema.TypeInt,
Optional: true,
Default: 3,
ValidateFunc: validation.IntBetween(1, 7),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return strings.ToLower(old) != "" && strings.ToLower(new) != strings.ToLower(old)
},
},
"comment": {
Type: schema.TypeString,
Optional: true,
Default: "topic added by terraform",
ValidateFunc: validation.StringLenBetween(0, 255),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return strings.ToLower(new) == strings.ToLower(old)
},
},
"record_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "TUPLE",
ValidateFunc: validation.StringInSlice([]string{"TUPLE", "BLOB"}, false),
},
"record_schema": {
Type: schema.TypeMap,
Elem: schema.TypeString,
Optional: true,
ForceNew: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("record_type") != string(datahub.TUPLE)
},
},
"create_time": {
Type: schema.TypeString, //converted from UTC(uint64) value
Computed: true,
},
"last_modify_time": {
Type: schema.TypeString, //converted from UTC(uint64) value
Computed: true,
},
},
}
}
func resourceAliyunDatahubTopicCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
t := &datahub.GetTopicResult{
ProjectName: d.Get("project_name").(string),
TopicName: d.Get("name").(string),
ShardCount: d.Get("shard_count").(int),
LifeCycle: d.Get("life_cycle").(int),
Comment: d.Get("comment").(string),
}
recordType := d.Get("record_type").(string)
if recordType == string(datahub.TUPLE) {
t.RecordType = datahub.TUPLE
recordSchema := d.Get("record_schema").(map[string]interface{})
if len(recordSchema) == 0 {
recordSchema = getDefaultRecordSchemainMap()
}
t.RecordSchema = getRecordSchema(recordSchema)
} else if recordType == string(datahub.BLOB) {
t.RecordType = datahub.BLOB
}
var requestInfo *datahub.DataHub
raw, err := client.WithDataHubClient(func(dataHubClient datahub.DataHubApi) (interface{}, error) {
requestInfo = dataHubClient.(*datahub.DataHub)
return dataHubClient.CreateTopicWithPara(t.ProjectName, t.TopicName, &datahub.CreateTopicParameter{
ShardCount: t.ShardCount,
LifeCycle: t.LifeCycle,
Comment: t.Comment,
RecordType: t.RecordType,
RecordSchema: t.RecordSchema,
ExpandMode: t.ExpandMode,
})
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_datahub_topic", "CreateTopic", AliyunDatahubSdkGo)
}
addDebug("CreateTopic", raw, requestInfo, t)
d.SetId(strings.ToLower(fmt.Sprintf("%s%s%s", t.ProjectName, COLON_SEPARATED, t.TopicName)))
return resourceAliyunDatahubTopicRead(d, meta)
}
func resourceAliyunDatahubTopicRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
datahubService := DatahubService{client}
object, err := datahubService.DescribeDatahubTopic(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", object.TopicName)
d.Set("project_name", object.ProjectName)
d.Set("shard_count", object.ShardCount)
d.Set("life_cycle", object.LifeCycle)
d.Set("comment", object.Comment)
d.Set("record_type", object.RecordType.String())
if object.RecordSchema != nil {
d.Set("record_schema", recordSchemaToMap(object.RecordSchema.Fields))
}
d.Set("create_time", strconv.FormatInt(object.CreateTime, 10))
d.Set("last_modify_time", strconv.FormatInt(object.LastModifyTime, 10))
return nil
}
func resourceAliyunDatahubTopicUpdate(d *schema.ResourceData, meta interface{}) error {
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
projectName, topicName := parts[0], parts[1]
client := meta.(*connectivity.AliyunClient)
// Currently, life_cycle can not be modified and it will be fixed in the next future.
if d.HasChange("life_cycle") || d.HasChange("comment") {
lifeCycle := d.Get("life_cycle").(int)
topicComment := d.Get("comment").(string)
var requestInfo *datahub.DataHub
raw, err := client.WithDataHubClient(func(dataHubClient datahub.DataHubApi) (interface{}, error) {
requestInfo = dataHubClient.(*datahub.DataHub)
return dataHubClient.UpdateTopic(projectName, topicName, topicComment)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "UpdateTopic", AliyunDatahubSdkGo)
}
if debugOn() {
requestMap := make(map[string]string)
requestMap["ProjectName"] = projectName
requestMap["TopicName"] = topicName
requestMap["LifeCycle"] = strconv.Itoa(lifeCycle)
requestMap["TopicComment"] = topicComment
addDebug("UpdateTopic", raw, requestInfo, requestMap)
}
err = resource.Retry(1*time.Minute, func() *resource.RetryError {
datahubService := DatahubService{client}
object, err := datahubService.DescribeDatahubTopic(d.Id())
if err != nil {
return resource.NonRetryableError(err)
}
if object.Comment != topicComment || object.LifeCycle != lifeCycle {
return resource.RetryableError(fmt.Errorf("waiting for updating topic %s comment and lifecycle finished timwout. "+
"current comment is %s and lifecycle is %d", d.Id(), object.Comment, object.LifeCycle))
}
return nil
})
if err != nil {
return WrapError(err)
}
}
return resourceAliyunDatahubTopicRead(d, meta)
}
func resourceAliyunDatahubTopicDelete(d *schema.ResourceData, meta interface{}) error {
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
projectName, topicName := parts[0], parts[1]
client := meta.(*connectivity.AliyunClient)
datahubService := DatahubService{client}
var requestInfo *datahub.DataHub
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := client.WithDataHubClient(func(dataHubClient datahub.DataHubApi) (interface{}, error) {
requestInfo = dataHubClient.(*datahub.DataHub)
return dataHubClient.DeleteTopic(projectName, topicName)
})
if err != nil {
if isRetryableDatahubError(err) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if debugOn() {
requestMap := make(map[string]string)
requestMap["ProjectName"] = projectName
requestMap["TopicName"] = topicName
addDebug("DeleteTopic", raw, requestInfo, requestMap)
}
return nil
})
if err != nil {
if isDatahubNotExistError(err) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DeleteTopic", AliyunDatahubSdkGo)
}
return WrapError(datahubService.WaitForDatahubTopic(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"fmt"
"log"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudDBAccountPrivilege() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDBAccountPrivilegeCreate,
Read: resourceAlicloudDBAccountPrivilegeRead,
Update: resourceAlicloudDBAccountPrivilegeUpdate,
Delete: resourceAlicloudDBAccountPrivilegeDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"account_name": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"privilege": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"ReadOnly", "ReadWrite", "DDLOnly", "DMLOnly", "DBOwner"}, false),
Default: "ReadOnly",
ForceNew: true,
},
"db_names": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
MinItems: 1,
},
},
}
}
func resourceAlicloudDBAccountPrivilegeCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
instanceId := d.Get("instance_id").(string)
account := d.Get("account_name").(string)
privilege := d.Get("privilege").(string)
dbList := d.Get("db_names").(*schema.Set).List()
// wait instance running before granting
if err := rdsService.WaitForDBInstance(instanceId, Running, DefaultLongTimeout); err != nil {
return WrapError(err)
}
d.SetId(fmt.Sprintf("%s%s%s%s%s", instanceId, COLON_SEPARATED, account, COLON_SEPARATED, privilege))
if len(dbList) > 0 {
for _, db := range dbList {
if err := resource.Retry(10*time.Minute, func() *resource.RetryError {
if err := rdsService.GrantAccountPrivilege(d.Id(), db.(string)); err != nil {
if IsExpectedErrors(err, OperationDeniedDBStatus) || NeedRetry(err) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
}); err != nil {
return WrapError(err)
}
}
}
return resourceAlicloudDBAccountPrivilegeRead(d, meta)
}
func resourceAlicloudDBAccountPrivilegeRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rsdService := RdsService{client}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
if !d.IsNewResource() && len(d.Get("db_names").(*schema.Set).List()) < 0 {
log.Println("[WARN] Resource alicloud_db_account_privilege has no any databaces in this state.")
return nil
}
object, err := rsdService.DescribeDBAccountPrivilege(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_id", object["DBInstanceId"])
d.Set("account_name", object["AccountName"])
d.Set("privilege", parts[2])
var names []string
databasePrivilege := object["DatabasePrivileges"].(map[string]interface{})["DatabasePrivilege"].([]interface{})
for _, pri := range databasePrivilege {
pri := pri.(map[string]interface{})
if pri["AccountPrivilege"] == parts[2] {
if len(d.Get("db_names").(*schema.Set).List()) > 0 {
for _, name := range d.Get("db_names").(*schema.Set).List() {
if pri["DBName"].(string) == name.(string) {
names = append(names, pri["DBName"].(string))
break
}
}
} else {
names = append(names, pri["DBName"].(string))
}
}
}
if len(names) < 1 && strings.HasPrefix(object["DBInstanceId"].(string), "pgm-") {
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
action := "DescribeDatabases"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": object["DBInstanceId"],
"SourceIp": client.SourceIp,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InternalError", "OperationDenied.DBInstanceStatus"}) {
return resource.RetryableError(WrapErrorf(err, DefaultErrorMsg, object["DBInstanceId"], action, AlibabaCloudSdkGoERROR))
}
return resource.NonRetryableError(WrapErrorf(err, DefaultErrorMsg, object["DBInstanceId"], action, AlibabaCloudSdkGoERROR))
}
addDebug(action, response, request)
dataBases := response["Databases"].(map[string]interface{})["Database"].([]interface{})
for _, db := range dataBases {
db := db.(map[string]interface{})
accountPrivilegeInfos := db["Accounts"].(map[string]interface{})["AccountPrivilegeInfo"].([]interface{})
for _, account := range accountPrivilegeInfos {
account := account.(map[string]interface{})
if account["Account"] == object["AccountName"] && (account["AccountPrivilege"] == parts[2] || account["AccountPrivilege"] == "ALL") {
names = append(names, db["DBName"].(string))
}
}
}
return nil
})
if err != nil {
return WrapError(err)
}
}
d.Set("db_names", names)
return nil
}
func resourceAlicloudDBAccountPrivilegeUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
d.Partial(true)
if d.HasChange("db_names") {
parts := strings.Split(d.Id(), COLON_SEPARATED)
o, n := d.GetChange("db_names")
os := o.(*schema.Set)
ns := n.(*schema.Set)
remove := os.Difference(ns).List()
add := ns.Difference(os).List()
if len(remove) > 0 {
if strings.HasPrefix(d.Id(), "pgm-") {
return WrapError(fmt.Errorf("At present, the PostgreSql database does not support revoking the current privilege."))
}
// wait instance running before revoking
if err := rdsService.WaitForDBInstance(parts[0], Running, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
for _, db := range remove {
if err := rdsService.RevokeAccountPrivilege(d.Id(), db.(string)); err != nil {
return WrapError(err)
}
}
}
if len(add) > 0 {
// wait instance running before granting
if err := rdsService.WaitForDBInstance(parts[0], Running, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
for _, db := range add {
if err := rdsService.GrantAccountPrivilege(d.Id(), db.(string)); err != nil {
return WrapError(err)
}
}
}
d.SetPartial("db_names")
}
d.Partial(false)
return resourceAlicloudDBAccountPrivilegeRead(d, meta)
}
func resourceAlicloudDBAccountPrivilegeDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
object, err := rdsService.DescribeDBAccountPrivilege(d.Id())
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
if strings.HasPrefix(d.Id(), "pgm-") {
return nil
}
dbNames := make([]string, 0)
databasePrivileges := object["DatabasePrivileges"].(map[string]interface{})["DatabasePrivilege"].([]interface{})
if len(databasePrivileges) > 0 && len(d.Get("db_names").(*schema.Set).List()) > 0 {
for _, pri := range databasePrivileges {
pri := pri.(map[string]interface{})
if pri["AccountPrivilege"] == parts[2] {
dbName := pri["DBName"].(string)
for _, name := range d.Get("db_names").(*schema.Set).List() {
if dbName == name.(string) {
if err := rdsService.RevokeAccountPrivilege(d.Id(), dbName); err != nil {
return WrapError(err)
}
dbNames = append(dbNames, dbName)
break
}
}
}
}
}
for _, dbName := range dbNames {
if err := rdsService.WaitForAccountPrivilege(d.Id(), dbName, Deleted, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
}
return nil
}
package alicloud
import (
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudDBBackupPolicy() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDBBackupPolicyCreate,
Read: resourceAlicloudDBBackupPolicyRead,
Update: resourceAlicloudDBBackupPolicyUpdate,
Delete: resourceAlicloudDBBackupPolicyDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"backup_period": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
Computed: true,
ConflictsWith: []string{"preferred_backup_period"},
Deprecated: "Attribute 'backup_period' has been deprecated from version 1.69.0. Use `preferred_backup_period` instead",
},
"preferred_backup_period": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
// terraform does not support ValidateFunc of TypeList attr
// ValidateFunc: validateAllowedStringValue([]string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}),
Optional: true,
Computed: true,
},
"backup_time": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice(BACKUP_TIME, false),
Optional: true,
Computed: true,
ConflictsWith: []string{"preferred_backup_time"},
Deprecated: "Attribute 'backup_time' has been deprecated from version 1.69.0. Use `preferred_backup_time` instead",
},
"preferred_backup_time": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice(BACKUP_TIME, false),
Optional: true,
Default: "02:00Z-03:00Z",
},
"retention_period": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(7, 730),
Optional: true,
Computed: true,
ConflictsWith: []string{"backup_retention_period"},
Deprecated: "Attribute 'retention_period' has been deprecated from version 1.69.0. Use `backup_retention_period` instead",
},
"backup_retention_period": {
Type: schema.TypeInt,
Optional: true,
Default: 7,
},
"log_backup": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
Deprecated: "Attribute 'log_backup' has been deprecated from version 1.68.0. Use `enable_backup_log` instead",
},
"enable_backup_log": {
Type: schema.TypeBool,
Computed: true,
Optional: true,
},
"log_retention_period": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
DiffSuppressFunc: logRetentionPeriodDiffSuppressFunc,
ConflictsWith: []string{"log_backup_retention_period"},
Deprecated: "Attribute 'log_retention_period' has been deprecated from version 1.69.0. Use `log_backup_retention_period` instead",
},
"log_backup_retention_period": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
DiffSuppressFunc: logRetentionPeriodDiffSuppressFunc,
},
"local_log_retention_hours": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(0, 7*24),
Computed: true,
Optional: true,
DiffSuppressFunc: enableBackupLogDiffSuppressFunc,
},
"local_log_retention_space": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(0, 50),
Computed: true,
Optional: true,
DiffSuppressFunc: enableBackupLogDiffSuppressFunc,
},
"high_space_usage_protection": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"Enable", "Disable"}, false),
Default: "Enable",
Optional: true,
DiffSuppressFunc: enableBackupLogDiffSuppressFunc,
},
"log_backup_frequency": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"compress_type": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"1", "4", "8"}, false),
Computed: true,
Optional: true,
},
"archive_backup_retention_period": {
Type: schema.TypeInt,
Computed: true,
Optional: true,
DiffSuppressFunc: archiveBackupPeriodDiffSuppressFunc,
},
"archive_backup_keep_count": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(1, 31),
Computed: true,
Optional: true,
DiffSuppressFunc: enableBackupLogDiffSuppressFunc,
},
"archive_backup_keep_policy": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"ByMonth", "ByWeek", "KeepAll"}, false),
Computed: true,
Optional: true,
DiffSuppressFunc: enableBackupLogDiffSuppressFunc,
},
"released_keep_policy": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"None", "Lastest", "All"}, false),
Optional: true,
Computed: true,
},
},
}
}
func resourceAlicloudDBBackupPolicyCreate(d *schema.ResourceData, meta interface{}) error {
d.SetId(d.Get("instance_id").(string))
return resourceAlicloudDBBackupPolicyUpdate(d, meta)
}
func resourceAlicloudDBBackupPolicyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
object, err := rdsService.DescribeBackupPolicy(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_id", d.Id())
d.Set("backup_time", object["PreferredBackupTime"])
d.Set("backup_period", strings.Split(object["PreferredBackupPeriod"].(string), ","))
d.Set("retention_period", formatInt(object["BackupRetentionPeriod"]))
d.Set("preferred_backup_time", object["PreferredBackupTime"])
d.Set("preferred_backup_period", strings.Split(object["PreferredBackupPeriod"].(string), ","))
d.Set("backup_retention_period", formatInt(object["BackupRetentionPeriod"]))
d.Set("log_backup", object["BackupLog"] == "Enable")
d.Set("enable_backup_log", object["EnableBackupLog"] == "1")
d.Set("log_retention_period", formatInt(object["LogBackupRetentionPeriod"]))
d.Set("log_backup_retention_period", formatInt(object["LogBackupRetentionPeriod"]))
d.Set("local_log_retention_hours", formatInt(object["LocalLogRetentionHours"]))
d.Set("local_log_retention_space", formatInt(object["LocalLogRetentionSpace"]))
d.Set("released_keep_policy", object["ReleasedKeepPolicy"])
instance, err := rdsService.DescribeDBInstance(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
// At present, the sql server database does not support setting high_space_usage_protection and it`s has default value
if instance["Engine"] == "SQLServer" {
d.Set("high_space_usage_protection", "Enable")
} else {
d.Set("high_space_usage_protection", object["HighSpaceUsageProtection"])
}
d.Set("log_backup_frequency", object["LogBackupFrequency"])
d.Set("compress_type", object["CompressType"])
d.Set("archive_backup_retention_period", formatInt(object["ArchiveBackupRetentionPeriod"]))
d.Set("archive_backup_keep_count", formatInt(object["ArchiveBackupKeepCount"]))
d.Set("archive_backup_keep_policy", object["ArchiveBackupKeepPolicy"])
return nil
}
func resourceAlicloudDBBackupPolicyUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
updateForData := false
updateForLog := false
if d.HasChange("backup_period") || d.HasChange("backup_time") || d.HasChange("retention_period") ||
d.HasChange("preferred_backup_period") || d.HasChange("preferred_backup_time") || d.HasChange("backup_retention_period") ||
d.HasChange("compress_type") || d.HasChange("log_backup_frequency") || d.HasChange("archive_backup_retention_period") ||
d.HasChange("archive_backup_keep_count") || d.HasChange("archive_backup_keep_policy") || d.HasChange("released_keep_policy") {
updateForData = true
}
if d.HasChange("log_backup") || d.HasChange("enable_backup_log") || d.HasChange("log_backup_retention_period") || d.HasChange("log_retention_period") ||
d.HasChange("local_log_retention_hours") || d.HasChange("local_log_retention_space") || d.HasChange("high_space_usage_protection") {
updateForLog = true
}
if updateForData || updateForLog {
// wait instance running before modifying
if err := rdsService.WaitForDBInstance(d.Id(), Running, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
if err := resource.Retry(5*time.Minute, func() *resource.RetryError {
if err := rdsService.ModifyDBBackupPolicy(d, updateForData, updateForLog); err != nil {
if IsExpectedErrors(err, OperationDeniedDBStatus) || NeedRetry(err) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
}); err != nil {
return WrapError(err)
}
}
return resourceAlicloudDBBackupPolicyRead(d, meta)
}
func resourceAlicloudDBBackupPolicyDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 60*time.Second, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
conn, err := client.NewRdsClient()
if err != nil {
return err
}
action := "ModifyBackupPolicy"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": d.Id(),
"PreferredBackupPeriod": "Tuesday,Thursday,Saturday",
"BackupRetentionPeriod": "7",
"PreferredBackupTime": "02:00Z-03:00Z",
"EnableBackupLog": "1",
"SourceIp": client.SourceIp,
}
instance, err := rdsService.DescribeDBInstance(d.Id())
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
if instance["Engine"] != "SQLServer" {
request["LogBackupRetentionPeriod"] = "7"
}
if instance["Engine"] == "MySQL" && instance["DBInstanceStorageType"] == "local_ssd" {
request["ArchiveBackupRetentionPeriod"] = "0"
request["ArchiveBackupKeepCount"] = "1"
request["ArchiveBackupKeepPolicy"] = "ByMonth"
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
return rdsService.WaitForDBInstance(d.Id(), Running, DefaultTimeoutMedium)
}
package alicloud
import (
"fmt"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"regexp"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
const dbConnectionSuffixRegex = "\\.mysql\\.([a-zA-Z0-9\\-]+\\.){0,1}rds\\.aliyuncs\\.com"
const dbConnectionIdWithSuffixRegex = "^([a-zA-Z0-9\\-_]+:[a-zA-Z0-9\\-_]+)" + dbConnectionSuffixRegex + "$"
var dbConnectionIdWithSuffixRegexp = regexp.MustCompile(dbConnectionIdWithSuffixRegex)
func resourceAlicloudDBConnection() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDBConnectionCreate,
Read: resourceAlicloudDBConnectionRead,
Update: resourceAlicloudDBConnectionUpdate,
Delete: resourceAlicloudDBConnectionDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"connection_prefix": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"port": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateDBConnectionPort,
Default: "3306",
},
"connection_string": {
Type: schema.TypeString,
Computed: true,
},
"ip_address": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudDBConnectionCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
instanceId := d.Get("instance_id").(string)
prefix := d.Get("connection_prefix").(string)
if prefix == "" {
prefix = fmt.Sprintf("%stf", instanceId)
}
action := "AllocateInstancePublicConnection"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": instanceId,
"ConnectionStringPrefix": prefix,
"Port": d.Get("port"),
"SourceIp": client.SourceIp,
}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
err = resource.Retry(8*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, OperationDeniedDBStatus) || NeedRetry(err) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_db_connection", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprintf("%s%s%v", instanceId, COLON_SEPARATED, request["ConnectionStringPrefix"]))
if err := rdsService.WaitForDBConnection(d.Id(), Available, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
// wait instance running after allocating
if err := rdsService.WaitForDBInstance(instanceId, Running, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
return resourceAlicloudDBConnectionRead(d, meta)
}
func resourceAlicloudDBConnectionRead(d *schema.ResourceData, meta interface{}) error {
submatch := dbConnectionIdWithSuffixRegexp.FindStringSubmatch(d.Id())
if len(submatch) > 1 {
d.SetId(submatch[1])
}
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
object, err := rdsService.DescribeDBConnection(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("instance_id", parts[0])
d.Set("connection_prefix", parts[1])
d.Set("port", object["Port"])
d.Set("connection_string", object["ConnectionString"])
d.Set("ip_address", object["IPAddress"])
return nil
}
func resourceAlicloudDBConnectionUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
submatch := dbConnectionIdWithSuffixRegexp.FindStringSubmatch(d.Id())
if len(submatch) > 1 {
d.SetId(submatch[1])
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
if d.HasChange("port") {
action := "ModifyDBInstanceConnectionString"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": parts[0],
"SourceIp": client.SourceIp,
}
object, err := rdsService.DescribeDBConnection(d.Id())
if err != nil {
return WrapError(err)
}
request["CurrentConnectionString"] = object["ConnectionString"]
request["ConnectionStringPrefix"] = parts[1]
request["Port"] = d.Get("port")
runtime := util.RuntimeOptions{}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
if err := resource.Retry(8*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, OperationDeniedDBStatus) || NeedRetry(err) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
// wait instance running after modifying
if err := rdsService.WaitForDBInstance(request["DBInstanceId"].(string), Running, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
}
return resourceAlicloudDBConnectionRead(d, meta)
}
func resourceAlicloudDBConnectionDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
submatch := dbConnectionIdWithSuffixRegexp.FindStringSubmatch(d.Id())
if len(submatch) > 1 {
d.SetId(submatch[1])
}
split := strings.Split(d.Id(), COLON_SEPARATED)
action := "ReleaseInstancePublicConnection"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": split[0],
"SourceIp": client.SourceIp,
}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
object, err := rdsService.DescribeDBConnection(d.Id())
if err != nil {
return resource.NonRetryableError(WrapError(err))
}
request["CurrentConnectionString"] = object["ConnectionString"]
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"OperationDenied.DBInstanceStatus"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if NotFoundError(err) || IsExpectedErrors(err, []string{"InvalidCurrentConnectionString.NotFound", "AtLeastOneNetTypeExists"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return rdsService.WaitForDBConnection(d.Id(), Deleted, DefaultTimeoutMedium)
}
package alicloud
import (
"fmt"
"regexp"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudDBDatabase() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDBDatabaseCreate,
Read: resourceAlicloudDBDatabaseRead,
Update: resourceAlicloudDBDatabaseUpdate,
Delete: resourceAlicloudDBDatabaseDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"name": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-z][a-z0-9_-]*[a-z0-9]$`), "The name can consist of lowercase letters, numbers, underscores, and middle lines, and must begin with letters and end with letters or numbers"),
},
"character_set": {
Type: schema.TypeString,
Optional: true,
Default: "utf8",
ForceNew: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudDBDatabaseCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "CreateDatabase"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": d.Get("instance_id"),
"DBName": d.Get("name"),
"CharacterSetName": d.Get("character_set"),
"SourceIp": client.SourceIp,
}
if v, ok := d.GetOk("description"); ok && v.(string) != "" {
request["DBDescription"] = v
}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, OperationDeniedDBStatus) || NeedRetry(err) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprintf("%v%s%v", request["DBInstanceId"], COLON_SEPARATED, request["DBName"]))
return resourceAlicloudDBDatabaseRead(d, meta)
}
func resourceAlicloudDBDatabaseRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rsdService := RdsService{client}
object, err := rsdService.DescribeDBDatabase(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_id", object["DBInstanceId"])
d.Set("name", object["DBName"])
d.Set("character_set", object["CharacterSetName"])
d.Set("description", object["DBDescription"])
return nil
}
func resourceAlicloudDBDatabaseUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
if d.HasChange("description") && !d.IsNewResource() {
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "ModifyDBDescription"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": parts[0],
"DBName": parts[1],
"DBDescription": d.Get("description"),
"SourceIp": client.SourceIp,
}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
}
return resourceAlicloudDBDatabaseRead(d, meta)
}
func resourceAlicloudDBDatabaseDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteDatabase"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": parts[0],
"DBName": parts[1],
"SourceIp": client.SourceIp,
}
// wait instance status is running before deleting database
if err := rdsService.WaitForDBInstance(parts[0], Running, 1800); err != nil {
return WrapError(err)
}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NotFoundError(err) || IsExpectedErrors(err, []string{"InvalidDBName.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return WrapError(rdsService.WaitForDBDatabase(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"fmt"
"log"
"strings"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/hashicorp/go-uuid"
"github.com/hashicorp/terraform-plugin-sdk/helper/hashcode"
"strconv"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudDBInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDBInstanceCreate,
Read: resourceAlicloudDBInstanceRead,
Update: resourceAlicloudDBInstanceUpdate,
Delete: resourceAlicloudDBInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(20 * time.Minute),
Update: schema.DefaultTimeout(30 * time.Minute),
Delete: schema.DefaultTimeout(20 * time.Minute),
},
Schema: map[string]*schema.Schema{
"engine": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"engine_version": {
Type: schema.TypeString,
// Remove this limitation and refer to https://www.alibabacloud.com/help/doc-detail/26228.htm each time
//ValidateFunc: validateAllowedStringValue([]string{"5.5", "5.6", "5.7", "2008r2", "2012", "9.4", "9.3", "10.0"}),
ForceNew: true,
Required: true,
},
"instance_type": {
Type: schema.TypeString,
Required: true,
},
"instance_storage": {
Type: schema.TypeInt,
Required: true,
},
"instance_charge_type": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{string(Postpaid), string(Prepaid)}, false),
Optional: true,
Default: Postpaid,
},
"period": {
Type: schema.TypeInt,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 24, 36}),
Optional: true,
DiffSuppressFunc: PostPaidDiffSuppressFunc,
},
"monitoring_period": {
Type: schema.TypeInt,
ValidateFunc: validation.IntInSlice([]int{5, 60, 300}),
Optional: true,
Computed: true,
},
"auto_renew": {
Type: schema.TypeBool,
Optional: true,
Default: false,
DiffSuppressFunc: PostPaidDiffSuppressFunc,
},
"auto_renew_period": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(1, 12),
Optional: true,
Default: 1,
DiffSuppressFunc: PostPaidAndRenewDiffSuppressFunc,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"db_time_zone": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
// If it is a new resource, do not suppress.
if d.Id() == "" {
return false
}
// If it is not a new resource and it is a multi-zone deployment, it needs to be suppressed.
return len(strings.Split(new, ",")) > 1
},
},
"private_ip_address": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"instance_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"connection_string": {
Type: schema.TypeString,
Computed: true,
},
"connection_string_prefix": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(8, 64),
},
"port": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"security_ips": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
Optional: true,
},
"db_instance_ip_array_name": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: securityIpsDiffSuppressFunc,
},
"db_instance_ip_array_attribute": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: securityIpsDiffSuppressFunc,
},
"security_ip_type": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: securityIpsDiffSuppressFunc,
},
"whitelist_network_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Classic", "VPC", "MIX"}, false),
DiffSuppressFunc: securityIpsDiffSuppressFunc,
},
"modify_mode": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Cover", "Append", "Delete"}, false),
DiffSuppressFunc: securityIpsDiffSuppressFunc,
},
"security_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"security_group_ids"},
Deprecated: "Attribute `security_group_id` has been deprecated from 1.69.0 and use `security_group_ids` instead.",
},
"security_group_ids": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
Optional: true,
},
"security_ip_mode": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{NormalMode, SafetyMode}, false),
Optional: true,
Default: NormalMode,
},
"parameters": {
Type: schema.TypeSet,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"value": {
Type: schema.TypeString,
Required: true,
},
},
},
Set: parameterToHash,
Optional: true,
Computed: true,
},
"pg_hba_conf": {
Type: schema.TypeSet,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"type": {
Type: schema.TypeString,
Required: true,
},
"mask": {
Type: schema.TypeString,
Optional: true,
// if attribute contains Optional feature, need to add Default: "", otherwise when terraform plan is executed, unmodified items wil detect differences.
Default: "",
},
"database": {
Type: schema.TypeString,
Required: true,
},
"priority_id": {
Type: schema.TypeInt,
Required: true,
},
"address": {
Type: schema.TypeString,
Required: true,
},
"user": {
Type: schema.TypeString,
Required: true,
},
"method": {
Type: schema.TypeString,
Required: true,
},
"option": {
Type: schema.TypeString,
Optional: true,
Default: "",
},
},
},
Optional: true,
Computed: true,
},
"force_restart": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"tags": tagsSchema(),
"maintain_time": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
// Default to Manual
"auto_upgrade_minor_version": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Auto", "Manual"}, false),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("engine").(string) != "MySQL"
},
},
"db_instance_storage_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"local_ssd", "cloud_ssd", "cloud_essd", "cloud_essd2", "cloud_essd3"}, false),
},
"sql_collector_status": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Enabled", "Disabled"}, false),
Computed: true,
},
"sql_collector_config_value": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{30, 180, 365, 1095, 1825}),
Default: 30,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"ssl_action": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"Open", "Close", "Update"}, false),
Optional: true,
Computed: true,
},
"tde_status": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"Enabled"}, false),
Optional: true,
ForceNew: true,
},
"ssl_status": {
Type: schema.TypeString,
Computed: true,
},
"encryption_key": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("engine").(string) != "PostgreSQL" && d.Get("engine").(string) != "MySQL" && d.Get("engine").(string) != "SQLServer"
},
},
"zone_id_slave_a": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"zone_id_slave_b": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ca_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"server_cert": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"server_key": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"client_ca_enabled": {
Type: schema.TypeInt,
Optional: true,
},
"client_ca_cert": {
Type: schema.TypeString,
Optional: true,
},
"client_crl_enabled": {
Type: schema.TypeInt,
Optional: true,
},
"client_cert_revocation_list": {
Type: schema.TypeString,
Optional: true,
},
"acl": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"replication_acl": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"upgrade_db_instance_kernel_version": {
Type: schema.TypeBool,
Optional: true,
},
"upgrade_time": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Immediate", "MaintainTime", "SpecifyTime"}, false),
DiffSuppressFunc: kernelVersionDiffSuppressFunc,
},
"switch_time": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: kernelVersionDiffSuppressFunc,
},
"target_minor_version": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: kernelVersionDiffSuppressFunc,
Computed: true,
},
"storage_auto_scale": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"Enable", "Disable"}, false),
Optional: true,
},
"storage_threshold": {
Type: schema.TypeInt,
ValidateFunc: validation.IntInSlice([]int{10, 20, 30, 40, 50}),
DiffSuppressFunc: StorageAutoScaleDiffSuppressFunc,
Optional: true,
},
"storage_upper_bound": {
Type: schema.TypeInt,
ValidateFunc: validation.IntAtLeast(0),
DiffSuppressFunc: StorageAutoScaleDiffSuppressFunc,
Optional: true,
},
"ha_config": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Auto", "Manual"}, false),
},
"manual_ha_time": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("ha_config"); ok && v.(string) == "Manual" {
return false
}
return true
},
},
"released_keep_policy": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"None", "Lastest", "All"}, false),
},
"fresh_white_list_readins": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func parameterToHash(v interface{}) int {
m := v.(map[string]interface{})
return hashcode.String(m["name"].(string) + "|" + m["value"].(string))
}
func resourceAlicloudDBInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
action := "CreateDBInstance"
request, err := buildDBCreateRequest(d, meta)
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetId(response["DBInstanceId"].(string))
// wait instance status change from Creating to running
stateConf := BuildStateConf([]string{"Creating"}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 3*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudDBInstanceUpdate(d, meta)
}
func resourceAlicloudDBInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
d.Partial(true)
stateConf := BuildStateConf([]string{"DBInstanceClassChanging", "DBInstanceNetTypeChanging", "CONFIG_ENCRYPTING", "SSL_MODIFYING"}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 60*time.Second, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if d.HasChange("parameters") {
if err := rdsService.ModifyParameters(d, "parameters"); err != nil {
return WrapError(err)
}
}
if d.HasChange("pg_hba_conf") {
err := rdsService.ModifyPgHbaConfig(d, "pg_hba_conf")
if err != nil {
return WrapError(err)
}
}
if err := rdsService.setInstanceTags(d); err != nil {
return WrapError(err)
}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
if d.HasChanges("storage_auto_scale", "storage_threshold", "storage_upper_bound") {
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 3*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
action := "ModifyDasInstanceConfig"
request := map[string]interface{}{
"DBInstanceId": d.Id(),
"RegionId": client.RegionId,
"SourceIp": client.SourceIp,
}
if v, ok := d.GetOk("storage_auto_scale"); ok && v.(string) != "" {
request["StorageAutoScale"] = v
}
if v, ok := d.GetOk("storage_threshold"); ok {
request["StorageThreshold"] = v.(int)
}
if v, ok := d.GetOk("storage_upper_bound"); ok {
request["StorageUpperBound"] = v.(int)
}
var response map[string]interface{}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
stateConf = BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 3*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
d.SetPartial("storage_auto_scale")
d.SetPartial("storage_threshold")
d.SetPartial("storage_upper_bound")
// wait instance status is running after modifying
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
payType := PayType(d.Get("instance_charge_type").(string))
if !d.IsNewResource() && d.HasChange("instance_charge_type") && payType == Prepaid {
action := "ModifyDBInstancePayType"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": d.Id(),
"PayType": payType,
"AutoPay": "true",
"UsedTime": d.Get("period"),
"Period": Month,
"SourceIp": client.SourceIp,
}
period := d.Get("period").(int)
if period > 9 {
request["UsedTime"] = period / 12
request["Period"] = Year
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
// wait instance status is Normal after modifying
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("instance_charge_type")
d.SetPartial("period")
}
if payType == Prepaid && (d.HasChange("auto_renew") || d.HasChange("auto_renew_period")) {
action := "ModifyInstanceAutoRenewalAttribute"
request := map[string]interface{}{
"DBInstanceId": d.Id(),
"RegionId": client.RegionId,
"SourceIp": client.SourceIp,
}
auto_renew := d.Get("auto_renew").(bool)
if auto_renew {
request["AutoRenew"] = "True"
} else {
request["AutoRenew"] = "False"
}
request["Duration"] = strconv.Itoa(d.Get("auto_renew_period").(int))
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetPartial("auto_renew")
d.SetPartial("auto_renew_period")
}
if d.HasChange("security_group_ids") || d.HasChange("security_group_id") {
groupIds := d.Get("security_group_id").(string)
if d.HasChange("security_group_ids") {
groupIds = strings.Join(expandStringList(d.Get("security_group_ids").(*schema.Set).List())[:], COMMA_SEPARATED)
}
err := rdsService.ModifySecurityGroupConfiguration(d.Id(), groupIds)
if err != nil {
return WrapError(err)
}
d.SetPartial("security_group_ids")
d.SetPartial("security_group_id")
}
if d.HasChange("monitoring_period") {
period := d.Get("monitoring_period").(int)
action := "ModifyDBInstanceMonitor"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": d.Id(),
"Period": strconv.Itoa(period),
"SourceIp": client.SourceIp,
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
}
if d.HasChange("maintain_time") {
action := "ModifyDBInstanceMaintainTime"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": d.Id(),
"MaintainTime": d.Get("maintain_time"),
"ClientToken": buildClientToken(action),
"SourceIp": client.SourceIp,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetPartial("maintain_time")
}
if d.HasChange("auto_upgrade_minor_version") {
action := "ModifyDBInstanceAutoUpgradeMinorVersion"
request := map[string]interface{}{
"RegionId": client.SourceIp,
"DBInstanceId": d.Id(),
"AutoUpgradeMinorVersion": d.Get("auto_upgrade_minor_version"),
"ClientToken": buildClientToken(action),
"SourceIp": client.SourceIp,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 3*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("auto_upgrade_minor_version")
}
if d.HasChange("security_ip_mode") && d.Get("security_ip_mode").(string) == SafetyMode {
action := "MigrateSecurityIPMode"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": d.Id(),
"SourceIp": client.SourceIp,
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetPartial("security_ip_mode")
}
if d.HasChange("sql_collector_status") {
action := "ModifySQLCollectorPolicy"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": d.Id(),
"SourceIp": client.SourceIp,
}
if d.Get("sql_collector_status").(string) == "Enabled" {
request["SQLCollectorStatus"] = "Enable"
} else {
request["SQLCollectorStatus"] = d.Get("sql_collector_status")
}
// wait instance status is running after modifying
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 0, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetPartial("sql_collector_status")
}
if d.Get("sql_collector_status").(string) == "Enabled" && d.HasChange("sql_collector_config_value") && d.Get("engine").(string) == string(MySQL) {
action := "ModifySQLCollectorRetention"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": d.Id(),
"ConfigValue": strconv.Itoa(d.Get("sql_collector_config_value").(int)),
"SourceIp": client.SourceIp,
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetPartial("sql_collector_config_value")
}
if d.HasChange("ssl_action") {
action := "ModifyDBInstanceSSL"
request := map[string]interface{}{
"DBInstanceId": d.Id(),
"RegionId": client.RegionId,
"SourceIp": client.SourceIp,
}
sslAction := d.Get("ssl_action").(string)
if sslAction == "Close" {
request["SSLEnabled"] = 0
}
if sslAction == "Open" {
request["SSLEnabled"] = 1
}
if sslAction == "Update" {
request["SSLEnabled"] = 2
}
if sslAction == "Update" && d.Get("engine").(string) == "PostgreSQL" {
request["SSLEnabled"] = 1
}
instance, err := rdsService.DescribeDBInstance(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
if d.Get("engine").(string) == "PostgreSQL" {
if v, ok := d.GetOk("ca_type"); ok && v.(string) != "" {
request["CAType"] = v.(string)
}
if v, ok := d.GetOk("server_cert"); ok && v.(string) != "" {
request["ServerCert"] = v.(string)
}
if v, ok := d.GetOk("server_key"); ok && v.(string) != "" {
request["ServerKey"] = v.(string)
}
if v, ok := d.GetOk("client_ca_enabled"); ok {
request["ClientCAEnabled"] = v.(int)
}
if v, ok := d.GetOk("client_ca_cert"); ok && v.(string) != "" {
request["ClientCACert"] = v.(string)
}
if v, ok := d.GetOk("client_crl_enabled"); ok {
request["ClientCrlEnabled"] = v.(int)
}
if v, ok := d.GetOk("client_cert_revocation_list"); ok && v.(string) != "" {
request["ClientCertRevocationList"] = v.(string)
}
if v, ok := d.GetOk("acl"); ok && v.(string) != "" {
request["ACL"] = v.(string)
}
if v, ok := d.GetOk("replication_acl"); ok && v.(string) != "" {
request["ReplicationACL"] = v.(string)
}
}
request["ConnectionString"] = instance["ConnectionString"]
var response map[string]interface{}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 3*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("ssl_action")
// wait instance status is running after modifying
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if d.HasChange("tde_status") {
action := "ModifyDBInstanceTDE"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": d.Id(),
"TDEStatus": d.Get("tde_status"),
"SourceIp": client.SourceIp,
}
if "MySQL" == d.Get("engine").(string) {
if v, ok := d.GetOk("encryption_key"); ok && v.(string) != "" {
request["EncryptionKey"] = v.(string)
roleArn, err := findKmsRoleArn(client, v.(string))
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
request["RoleARN"] = roleArn
}
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetPartial("tde_status")
// wait instance status is running after modifying
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if d.HasChanges("ha_config", "manual_ha_time") {
action := "ModifyHASwitchConfig"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": d.Id(),
"SourceIp": client.SourceIp,
}
if v, ok := d.GetOk("ha_config"); ok && v.(string) != "" {
request["HAConfig"] = v
}
if v, ok := d.GetOk("manual_ha_time"); ok && v.(string) != "" {
request["ManualHATime"] = v
}
var response map[string]interface{}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 3*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
d.SetPartial("ha_config")
d.SetPartial("manual_ha_time")
// wait instance status is running after modifying
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if d.IsNewResource() {
d.Partial(false)
return resourceAlicloudDBInstanceRead(d, meta)
}
if d.HasChange("instance_name") {
action := "ModifyDBInstanceDescription"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": d.Id(),
"DBInstanceDescription": d.Get("instance_name"),
"SourceIp": client.SourceIp,
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetPartial("instance_name")
}
if d.HasChange("security_ips") {
ipList := expandStringList(d.Get("security_ips").(*schema.Set).List())
ipstr := strings.Join(ipList[:], COMMA_SEPARATED)
// default disable connect from outside
if ipstr == "" {
ipstr = LOCAL_HOST_IP
}
action := "ModifySecurityIps"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": d.Id(),
"SecurityIps": ipstr,
"SourceIp": client.SourceIp,
}
if v, ok := d.GetOk("db_instance_ip_array_name"); ok && v.(string) != "" {
request["DBInstanceIPArrayName"] = v
}
if v, ok := d.GetOk("db_instance_ip_array_attribute"); ok && v.(string) != "" {
request["DBInstanceIPArrayAttribute"] = v
}
if v, ok := d.GetOk("security_ip_type"); ok && v.(string) != "" {
request["SecurityIPType"] = v
}
if v, ok := d.GetOk("whitelist_network_type"); ok && v.(string) != "" {
request["WhitelistNetworkType"] = v
}
if v, ok := d.GetOk("modify_mode"); ok && v.(string) != "" {
request["ModifyMode"] = v
}
if v, ok := d.GetOk("fresh_white_list_readins"); ok && v.(string) != "" {
request["FreshWhiteListReadins"] = v
}
var response map[string]interface{}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 1*time.Second, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("security_ips")
d.SetPartial("db_instance_ip_array_name")
d.SetPartial("db_instance_ip_array_attribute")
d.SetPartial("security_ip_type")
d.SetPartial("whitelist_network_type")
// wait instance status is running after modifying
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if !d.IsNewResource() && d.HasChange("resource_group_id") {
action := "ModifyResourceGroup"
request := map[string]interface{}{
"DBInstanceId": d.Id(),
"ResourceGroupId": d.Get("resource_group_id"),
"ClientToken": buildClientToken(action),
"SourceIp": client.SourceIp,
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetPartial("resource_group_id")
}
update := false
action := "ModifyDBInstanceSpec"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": d.Id(),
"PayType": d.Get("instance_charge_type"),
"SourceIp": client.SourceIp,
}
if d.HasChange("instance_type") {
request["DBInstanceClass"] = d.Get("instance_type")
update = true
}
if d.HasChange("instance_storage") {
request["DBInstanceStorage"] = d.Get("instance_storage")
update = true
}
if d.HasChange("db_instance_storage_type") {
request["DBInstanceStorageType"] = d.Get("db_instance_storage_type")
update = true
}
if update {
// wait instance status is running before modifying
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
runtime := util.RuntimeOptions{}
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidOrderTask.NotSupport"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
d.SetPartial("instance_type")
d.SetPartial("instance_storage")
d.SetPartial("db_instance_storage_type")
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
// wait instance status is running after modifying
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
vpcService := VpcService{client}
netUpdate := false
netAction := "SwitchDBInstanceVpc"
netRequest := map[string]interface{}{
"DBInstanceId": d.Id(),
"RegionId": client.RegionId,
"SourceIp": client.SourceIp,
}
if d.HasChanges("vswitch_id") {
netUpdate = true
}
if d.HasChange("private_ip_address") {
netUpdate = true
}
if netUpdate {
v := d.Get("vswitch_id").(string)
vsw, err := vpcService.DescribeVSwitch(v)
if err != nil {
return WrapError(err)
}
netRequest["VPCId"] = vsw.VpcId
netRequest["VSwitchId"] = v
if v, ok := d.GetOk("private_ip_address"); ok && v.(string) != "" {
netRequest["PrivateIpAddress"] = v
}
var response map[string]interface{}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(netAction), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, netRequest, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), netAction, AlibabaCloudSdkGoERROR)
}
addDebug(netAction, response, netRequest)
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 3*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("vswitch_id")
d.SetPartial("private_ip_address")
// wait instance status is running after modifying
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
connectUpdate := false
connectAction := "ModifyDBInstanceConnectionString"
connectRequest := map[string]interface{}{
"DBInstanceId": d.Id(),
"RegionId": client.RegionId,
"SourceIp": client.SourceIp,
}
if d.HasChange("port") {
connectUpdate = true
}
if d.HasChange("connection_string_prefix") {
connectUpdate = true
}
if connectUpdate {
if v, ok := d.GetOk("port"); ok && v.(string) != "" {
connectRequest["Port"] = v
}
if v, ok := d.GetOk("connection_string_prefix"); ok && v.(string) != "" {
connectRequest["ConnectionStringPrefix"] = v
} else {
connectRequest["ConnectionStringPrefix"] = strings.Split(d.Get("connection_string").(string), ".")[0]
}
connectRequest["CurrentConnectionString"] = d.Get("connection_string")
var response map[string]interface{}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(connectAction), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, connectRequest, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), netAction, AlibabaCloudSdkGoERROR)
}
addDebug(connectAction, response, connectRequest)
d.SetPartial("port")
d.SetPartial("connection_string")
// wait instance status is running after modifying
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 3*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if d.HasChange("upgrade_db_instance_kernel_version") {
action := "UpgradeDBInstanceKernelVersion"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": d.Id(),
"SourceIp": client.SourceIp,
}
if v, ok := d.GetOk("upgrade_time"); ok && v.(string) != "" {
request["UpgradeTime"] = v
}
if v, ok := d.GetOk("switch_time"); ok && v.(string) != "" {
request["SwitchTime"] = v
}
if v, ok := d.GetOk("target_minor_version"); ok && v.(string) != "" {
request["TargetMinorVersion"] = v
}
var response map[string]interface{}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 3*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("target_minor_version")
// wait instance status is running after modifying
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.Partial(false)
return resourceAlicloudDBInstanceRead(d, meta)
}
func resourceAlicloudDBInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
instance, err := rdsService.DescribeDBInstance(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
dbInstanceIpArrayName := "default"
if v, ok := d.GetOk("db_instance_ip_array_name"); ok {
dbInstanceIpArrayName = v.(string)
}
ips, err := rdsService.GetSecurityIps(d.Id(), dbInstanceIpArrayName)
if err != nil {
return WrapError(err)
}
tags, err := rdsService.describeTags(d)
if err != nil {
return WrapError(err)
}
if len(tags) > 0 {
d.Set("tags", rdsService.tagsToMap(tags))
}
monitoringPeriod, err := rdsService.DescribeDbInstanceMonitor(d.Id())
if err != nil {
return WrapError(err)
}
sqlCollectorPolicy, err := rdsService.DescribeSQLCollectorPolicy(d.Id())
if err != nil {
return WrapError(err)
}
sqlCollectorRetention, err := rdsService.DescribeSQLCollectorRetention(d.Id())
if err != nil {
return WrapError(err)
}
netInfoResponse, err := rdsService.DescribeDBInstanceNetInfo(d.Id())
if err != nil {
return WrapError(err)
}
var privateIpAddress string
for _, item := range netInfoResponse {
ipType := item.(map[string]interface{})["IPType"]
if ipType == "Private" {
privateIpAddress = item.(map[string]interface{})["IPAddress"].(string)
break
}
}
d.Set("storage_auto_scale", d.Get("storage_auto_scale"))
d.Set("storage_threshold", d.Get("storage_threshold"))
d.Set("storage_upper_bound", d.Get("storage_upper_bound"))
d.Set("resource_group_id", instance["ResourceGroupId"])
d.Set("monitoring_period", monitoringPeriod)
d.Set("security_ips", ips)
d.Set("db_instance_ip_array_name", d.Get("db_instance_ip_array_name"))
d.Set("db_instance_ip_array_attribute", d.Get("db_instance_ip_array_attribute"))
d.Set("security_ip_type", d.Get("security_ip_type"))
d.Set("whitelist_network_type", d.Get("whitelist_network_type"))
d.Set("security_ip_mode", instance["SecurityIPMode"])
d.Set("engine", instance["Engine"])
d.Set("engine_version", instance["EngineVersion"])
d.Set("instance_type", instance["DBInstanceClass"])
d.Set("port", instance["Port"])
d.Set("instance_storage", instance["DBInstanceStorage"])
d.Set("db_instance_storage_type", instance["DBInstanceStorageType"])
d.Set("zone_id", instance["ZoneId"])
d.Set("instance_charge_type", instance["PayType"])
d.Set("period", d.Get("period"))
d.Set("vswitch_id", instance["VSwitchId"])
d.Set("private_ip_address", privateIpAddress)
d.Set("connection_string", instance["ConnectionString"])
d.Set("instance_name", instance["DBInstanceDescription"])
d.Set("maintain_time", instance["MaintainTime"])
d.Set("auto_upgrade_minor_version", instance["AutoUpgradeMinorVersion"])
d.Set("target_minor_version", instance["CurrentKernelVersion"])
slaveZones := instance["SlaveZones"].(map[string]interface{})["SlaveZone"].([]interface{})
if len(slaveZones) == 2 {
d.Set("zone_id_slave_a", slaveZones[0].(map[string]interface{})["ZoneId"])
d.Set("zone_id_slave_b", slaveZones[1].(map[string]interface{})["ZoneId"])
} else if len(slaveZones) == 1 {
d.Set("zone_id_slave_a", slaveZones[0].(map[string]interface{})["ZoneId"])
}
if sqlCollectorPolicy["SQLCollectorStatus"] == "Enable" {
d.Set("sql_collector_status", "Enabled")
} else {
d.Set("sql_collector_status", sqlCollectorPolicy["SQLCollectorStatus"])
}
configValue, err := strconv.Atoi(sqlCollectorRetention["ConfigValue"].(string))
if err != nil {
return WrapError(err)
}
d.Set("sql_collector_config_value", configValue)
if err = rdsService.RefreshParameters(d, "parameters"); err != nil {
return WrapError(err)
}
if err = rdsService.RefreshPgHbaConf(d, "pg_hba_conf"); err != nil {
return WrapError(err)
}
if err = rdsService.SetTimeZone(d); err != nil {
return WrapError(err)
}
if instance["PayType"] == string(Prepaid) {
action := "DescribeInstanceAutoRenewalAttribute"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": d.Id(),
"SourceIp": client.SourceIp,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
items := response["Items"].(map[string]interface{})["Item"].([]interface{})
if response != nil && len(items) > 0 {
renew := items[0].(map[string]interface{})
d.Set("auto_renew", renew["AutoRenew"] == "True")
d.Set("auto_renew_period", renew["Duration"])
}
//period, err := computePeriodByUnit(instance["CreationTime"], instance["ExpireTime"], d.Get("period").(int), "Month")
//if err != nil {
// return WrapError(err)
//}
//d.Set("period", period)
}
groups, err := rdsService.DescribeSecurityGroupConfiguration(d.Id())
if err != nil {
return WrapError(err)
}
if len(groups) > 0 {
d.Set("security_group_id", strings.Join(groups, COMMA_SEPARATED))
d.Set("security_group_ids", groups)
}
sslAction, err := rdsService.DescribeDBInstanceSSL(d.Id())
if err != nil && !IsExpectedErrors(err, []string{"InvaildEngineInRegion.ValueNotSupported", "InstanceEngineType.NotSupport", "OperationDenied.DBInstanceType"}) {
return WrapError(err)
}
d.Set("ssl_status", sslAction["RequireUpdate"])
d.Set("ssl_action", d.Get("ssl_action"))
d.Set("client_ca_enabled", d.Get("client_ca_enabled"))
d.Set("client_crl_enabled", d.Get("client_crl_enabled"))
d.Set("ca_type", sslAction["CAType"])
d.Set("server_cert", sslAction["ServerCert"])
d.Set("server_key", sslAction["ServerKey"])
d.Set("client_ca_cert", sslAction["ClientCACert"])
d.Set("client_cert_revocation_list", sslAction["ClientCertRevocationList"])
d.Set("acl", sslAction["ACL"])
d.Set("replication_acl", sslAction["ReplicationACL"])
tdeInfo, err := rdsService.DescribeRdsTDEInfo(d.Id())
if err != nil && !IsExpectedErrors(err, []string{"InvaildEngineInRegion.ValueNotSupported", "InstanceEngineType.NotSupport", "OperationDenied.DBInstanceType"}) {
return WrapError(err)
}
d.Set("tde_Status", tdeInfo["TDEStatus"])
res, err := rdsService.DescribeHASwitchConfig(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("ha_config", res["HAConfig"])
d.Set("manual_ha_time", res["ManualHATime"])
return nil
}
func resourceAlicloudDBInstanceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
instance, err := rdsService.DescribeDBInstance(d.Id())
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
if PayType(instance["PayType"].(string)) == Prepaid {
log.Printf("[WARN] Cannot destroy Subscription resource: alicloud_db_instance. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
action := "DeleteDBInstance"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": d.Id(),
"SourceIp": client.SourceIp,
}
if v, ok := d.GetOk("released_keep_policy"); ok && v.(string) != "" {
request["ReleasedKeepPolicy"] = v
}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
err = resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil && !NotFoundError(err) {
if IsExpectedErrors(err, []string{"OperationDenied.DBInstanceStatus", "OperationDenied.ReadDBInstanceStatus"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"Processing", "Pending", "NoStart", "Failed", "Default"}, []string{}, d.Timeout(schema.TimeoutDelete), 30*time.Second, rdsService.RdsTaskStateRefreshFunc(d.Id(), "DeleteDBInstance"))
if _, err = stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
func buildDBCreateRequest(d *schema.ResourceData, meta interface{}) (map[string]interface{}, error) {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
request := map[string]interface{}{
"RegionId": client.RegionId,
"EngineVersion": Trim(d.Get("engine_version").(string)),
"Engine": Trim(d.Get("engine").(string)),
"DBInstanceStorage": d.Get("instance_storage"),
"DBInstanceClass": Trim(d.Get("instance_type").(string)),
"DBInstanceNetType": Intranet,
"DBInstanceDescription": d.Get("instance_name"),
"DBInstanceStorageType": d.Get("db_instance_storage_type"),
"SourceIp": client.SourceIp,
}
if v, ok := d.GetOk("resource_group_id"); ok && v.(string) != "" {
request["ResourceGroupId"] = v
}
if request["Engine"] == "PostgreSQL" || request["Engine"] == "MySQL" || request["Engine"] == "SQLServer" {
if v, ok := d.GetOk("encryption_key"); ok && v.(string) != "" {
request["EncryptionKey"] = v.(string)
roleArn, err := findKmsRoleArn(client, v.(string))
if err != nil {
return nil, WrapError(err)
}
request["RoleARN"] = roleArn
}
}
if zone, ok := d.GetOk("zone_id"); ok && Trim(zone.(string)) != "" {
request["ZoneId"] = Trim(zone.(string))
}
vswitchId := Trim(d.Get("vswitch_id").(string))
request["InstanceNetworkType"] = Classic
if vswitchId != "" {
request["VSwitchId"] = vswitchId
request["InstanceNetworkType"] = strings.ToUpper(string(Vpc))
// check vswitchId in zone
v := strings.Split(vswitchId, COMMA_SEPARATED)[0]
vsw, err := vpcService.DescribeVSwitch(v)
if err != nil {
return nil, WrapError(err)
}
if request["ZoneId"] == nil {
request["ZoneId"] = vsw.ZoneId
}
if request["VPCId"] == nil {
request["VPCId"] = vsw.VpcId
}
//else if strings.Contains(request.ZoneId, MULTI_IZ_SYMBOL) {
// zonestr := strings.Split(strings.SplitAfter(request.ZoneId, "(")[1], ")")[0]
// if !strings.Contains(zonestr, string([]byte(vsw.ZoneId)[len(vsw.ZoneId)-1])) {
// return nil, WrapError(Error("The specified vswitch %s isn't in the multi zone %s.", vsw.VSwitchId, request.ZoneId))
// }
//} else if request.ZoneId != vsw.ZoneId {
// return nil, WrapError(Error("The specified vswitch %s isn't in the zone %s.", vsw.VSwitchId, request.ZoneId))
//}
}
request["PayType"] = Trim(d.Get("instance_charge_type").(string))
// if charge type is postpaid, the commodity code must set to bards
//args.CommodityCode = rds.Bards
// At present, API supports two charge options about 'Prepaid'.
// 'Month': valid period ranges [1-9]; 'Year': valid period range [1-3]
// This resource only supports to input Month period [1-9, 12, 24, 36] and the values need to be converted before using them.
if PayType(request["PayType"].(string)) == Prepaid {
period := d.Get("period").(int)
request["UsedTime"] = strconv.Itoa(period)
request["Period"] = Month
if period > 9 {
request["UsedTime"] = strconv.Itoa(period / 12)
request["Period"] = Year
}
}
request["SecurityIPList"] = LOCAL_HOST_IP
if len(d.Get("security_ips").(*schema.Set).List()) > 0 {
request["SecurityIPList"] = strings.Join(expandStringList(d.Get("security_ips").(*schema.Set).List())[:], COMMA_SEPARATED)
}
if v, ok := d.GetOk("zone_id_slave_a"); ok {
request["ZoneIdSlave1"] = v
}
if v, ok := d.GetOk("zone_id_slave_b"); ok {
request["ZoneIdSlave2"] = v
}
if v, ok := d.GetOk("db_time_zone"); ok {
request["DBTimeZone"] = v
}
uuid, err := uuid.GenerateUUID()
if err != nil {
uuid = resource.UniqueId()
}
request["ClientToken"] = fmt.Sprintf("Terraform-Alicloud-%d-%s", time.Now().Unix(), uuid)
return request, nil
}
func findKmsRoleArn(client *connectivity.AliyunClient, k string) (string, error) {
action := "DescribeKey"
var response map[string]interface{}
request := make(map[string]interface{})
request["KeyId"] = k
conn, err := client.NewKmsClient()
if err != nil {
return "", WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return "", WrapErrorf(err, DataDefaultErrorMsg, k, action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.KeyMetadata.Creator", response)
if err != nil {
return "", WrapErrorf(err, FailedGetAttributeMsg, action, "$.VersionIds.VersionId", response)
}
return strings.Join([]string{"acs:ram::", fmt.Sprint(resp), ":role/aliyunrdsinstanceencryptiondefaultrole"}, ""), nil
}
package alicloud
import (
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudDBReadonlyInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDBReadonlyInstanceCreate,
Read: resourceAlicloudDBReadonlyInstanceRead,
Update: resourceAlicloudDBReadonlyInstanceUpdate,
Delete: resourceAlicloudDBReadonlyInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(60 * time.Minute),
Update: schema.DefaultTimeout(30 * time.Minute),
Delete: schema.DefaultTimeout(20 * time.Minute),
},
Schema: map[string]*schema.Schema{
"engine_version": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"master_db_instance_id": {
Type: schema.TypeString,
Required: true,
},
"instance_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
Computed: true,
},
"instance_type": {
Type: schema.TypeString,
Required: true,
},
"instance_storage": {
Type: schema.TypeInt,
Required: true,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
},
"parameters": {
Type: schema.TypeSet,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"value": {
Type: schema.TypeString,
Required: true,
},
},
},
Set: parameterToHash,
Optional: true,
Computed: true,
},
"engine": {
Type: schema.TypeString,
Computed: true,
},
"connection_string": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"force_restart": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"ssl_enabled": {
Type: schema.TypeInt,
ValidateFunc: validation.IntInSlice([]int{0, 1}),
Optional: true,
Computed: true,
},
"ca_type": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"aliyun", "custom"}, false),
Optional: true,
Computed: true,
DiffSuppressFunc: sslEnabledDiffSuppressFunc,
},
"server_cert": {
Type: schema.TypeString,
Optional: true,
Computed: true,
DiffSuppressFunc: sslEnabledDiffSuppressFunc,
},
"server_key": {
Type: schema.TypeString,
Optional: true,
Computed: true,
DiffSuppressFunc: sslEnabledDiffSuppressFunc,
},
"client_ca_enabled": {
Type: schema.TypeInt,
ValidateFunc: validation.IntInSlice([]int{0, 1}),
Optional: true,
DiffSuppressFunc: sslEnabledDiffSuppressFunc,
},
"client_ca_cert": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: sslEnabledDiffSuppressFunc,
},
"client_crl_enabled": {
Type: schema.TypeInt,
ValidateFunc: validation.IntInSlice([]int{0, 1}),
Optional: true,
DiffSuppressFunc: sslEnabledDiffSuppressFunc,
},
"client_cert_revocation_list": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: sslEnabledDiffSuppressFunc,
},
"acl": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"cert", "perfer", "verify-ca", "verify-full"}, false),
Optional: true,
Computed: true,
DiffSuppressFunc: sslEnabledDiffSuppressFunc,
},
"replication_acl": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"cert", "perfer", "verify-ca", "verify-full"}, false),
Optional: true,
Computed: true,
DiffSuppressFunc: sslEnabledDiffSuppressFunc,
},
"upgrade_db_instance_kernel_version": {
Type: schema.TypeBool,
Optional: true,
},
"upgrade_time": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Immediate", "MaintainTime", "SpecifyTime"}, false),
DiffSuppressFunc: kernelVersionDiffSuppressFunc,
},
"switch_time": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: kernelVersionDiffSuppressFunc,
},
"target_minor_version": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: kernelVersionDiffSuppressFunc,
Computed: true,
},
},
}
}
func resourceAlicloudDBReadonlyInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
request, err := buildDBReadonlyCreateRequest(d, meta)
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
action := "CreateReadOnlyDBInstance"
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(2*time.Second, 0*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"OperationDenied.PrimaryDBInstanceStatus"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetId(response["DBInstanceId"].(string))
// wait instance status change from Creating to running
stateConf := BuildStateConf([]string{"Creating"}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 15*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudDBReadonlyInstanceUpdate(d, meta)
}
func resourceAlicloudDBReadonlyInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
d.Partial(true)
if d.HasChange("parameters") {
if err := rdsService.ModifyParameters(d, "parameters"); err != nil {
return WrapError(err)
}
}
if err := rdsService.setInstanceTags(d); err != nil {
return WrapError(err)
}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
sslUpdate := false
sslAction := "ModifyDBInstanceSSL"
sslRequest := map[string]interface{}{
"DBInstanceId": d.Id(),
"RegionId": client.RegionId,
"SourceIp": client.SourceIp,
}
if d.HasChange("ssl_enabled") {
sslRequest["SSLEnabled"] = d.Get("ssl_enabled").(int)
sslUpdate = true
}
if d.HasChange("ca_type") {
sslRequest["CAType"] = d.Get("ca_type")
sslUpdate = true
}
if d.HasChange("server_cert") {
sslRequest["ServerCert"] = d.Get("server_cert")
sslUpdate = true
}
if d.HasChange("server_key") {
sslRequest["ServerKey"] = d.Get("server_key")
sslUpdate = true
}
if d.HasChange("client_ca_enabled") {
sslRequest["ClientCAEnabled"] = d.Get("client_ca_enabled")
sslUpdate = true
}
if d.HasChange("client_ca_cert") {
sslRequest["ClientCACert"] = d.Get("client_ca_cert")
sslUpdate = true
}
if d.HasChange("client_crl_enabled") {
sslRequest["ClientCrlEnabled"] = d.Get("client_crl_enabled")
sslUpdate = true
}
if d.HasChange("client_cert_revocation_list") {
sslRequest["ClientCertRevocationList"] = d.Get("client_cert_revocation_list")
sslUpdate = true
}
if d.HasChange("acl") {
sslRequest["ACL"] = d.Get("acl")
sslUpdate = true
}
if d.HasChange("replication_acl") {
sslRequest["ReplicationACL"] = d.Get("replication_acl")
sslUpdate = true
}
if sslUpdate {
instance, err := rdsService.DescribeDBInstance(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
sslRequest["ConnectionString"] = instance["ConnectionString"]
var response map[string]interface{}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(sslAction), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, sslRequest, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), sslAction, AlibabaCloudSdkGoERROR)
}
addDebug(sslAction, response, sslRequest)
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 3*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("ssl_enabled")
d.SetPartial("ca_type")
d.SetPartial("server_cert")
d.SetPartial("server_key")
d.SetPartial("client_ca_enabled")
d.SetPartial("client_ca_cert")
d.SetPartial("client_crl_enabled")
d.SetPartial("client_cert_revocation_list")
d.SetPartial("acl")
d.SetPartial("replication_acl")
// wait instance status is running after modifying
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if d.IsNewResource() {
d.Partial(false)
return resourceAlicloudDBInstanceRead(d, meta)
}
if d.HasChange("instance_name") {
action := "ModifyDBInstanceDescription"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": d.Id(),
"DBInstanceDescription": d.Get("instance_name"),
"SourceIp": client.SourceIp,
}
runtime := util.RuntimeOptions{}
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"OperationDenied.DBInstanceStatus", "OperationDenied.MasterDBInstanceState"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
d.SetPartial("instance_name")
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if !d.IsNewResource() && d.HasChange("resource_group_id") {
action := "ModifyResourceGroup"
request := map[string]interface{}{
"DBInstanceId": d.Id(),
"ResourceGroupId": d.Get("resource_group_id"),
"ClientToken": buildClientToken(action),
"SourceIp": client.SourceIp,
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetPartial("resource_group_id")
}
update := false
action := "ModifyDBInstanceSpec"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": d.Id(),
"PayType": Postpaid,
"SourceIp": client.SourceIp,
}
if d.HasChange("instance_type") {
request["DBInstanceClass"] = d.Get("instance_type")
update = true
}
if d.HasChange("instance_storage") {
request["DBInstanceStorage"] = d.Get("instance_storage")
update = true
}
if update {
// wait instance status is running before modifying
stateConf := BuildStateConf([]string{"DBInstanceClassChanging", "DBInstanceNetTypeChanging"}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 10*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
_, err := stateConf.WaitForState()
if err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
runtime := util.RuntimeOptions{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidOrderTask.NotSupport", "OperationDenied.DBInstanceStatus", "OperationDenied.MasterDBInstanceState"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
d.SetPartial("instance_type")
d.SetPartial("instance_storage")
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
// wait instance status is running after modifying
_, err = stateConf.WaitForState()
if err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if d.HasChange("upgrade_db_instance_kernel_version") {
action := "UpgradeDBInstanceKernelVersion"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": d.Id(),
"SourceIp": client.SourceIp,
}
if v, ok := d.GetOk("upgrade_time"); ok && v.(string) != "" {
request["UpgradeTime"] = v
}
if v, ok := d.GetOk("switch_time"); ok && v.(string) != "" {
request["SwitchTime"] = v
}
if v, ok := d.GetOk("target_minor_version"); ok && v.(string) != "" {
request["TargetMinorVersion"] = v
}
var response map[string]interface{}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 3*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("target_minor_version")
// wait instance status is running after modifying
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.Partial(false)
return resourceAlicloudDBReadonlyInstanceRead(d, meta)
}
func resourceAlicloudDBReadonlyInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
instance, err := rdsService.DescribeDBInstance(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("engine", instance["Engine"])
d.Set("master_db_instance_id", instance["MasterInstanceId"])
d.Set("engine_version", instance["EngineVersion"])
d.Set("instance_type", instance["DBInstanceClass"])
d.Set("port", instance["Port"])
d.Set("instance_storage", instance["DBInstanceStorage"])
d.Set("zone_id", instance["ZoneId"])
d.Set("vswitch_id", instance["VSwitchId"])
d.Set("connection_string", instance["ConnectionString"])
d.Set("instance_name", instance["DBInstanceDescription"])
d.Set("resource_group_id", instance["ResourceGroupId"])
d.Set("target_minor_version", instance["CurrentKernelVersion"])
sslAction, err := rdsService.DescribeDBInstanceSSL(d.Id())
if err != nil && !IsExpectedErrors(err, []string{"InvaildEngineInRegion.ValueNotSupported", "InstanceEngineType.NotSupport", "OperationDenied.DBInstanceType"}) {
return WrapError(err)
}
d.Set("ssl_status", sslAction["RequireUpdate"])
d.Set("ssl_enabled", d.Get("ssl_enabled"))
d.Set("client_ca_enabled", d.Get("client_ca_enabled"))
d.Set("client_crl_enabled", d.Get("client_crl_enabled"))
d.Set("ca_type", sslAction["CAType"])
d.Set("server_cert", sslAction["ServerCert"])
d.Set("server_key", sslAction["ServerKey"])
d.Set("client_ca_cert", sslAction["ClientCACert"])
d.Set("client_cert_revocation_list", sslAction["ClientCertRevocationList"])
d.Set("acl", sslAction["ACL"])
d.Set("replication_acl", sslAction["ReplicationACL"])
if err = rdsService.RefreshParameters(d, "parameters"); err != nil {
return err
}
tags, err := rdsService.describeTags(d)
if err != nil {
return WrapError(err)
}
if len(tags) > 0 {
d.Set("tags", rdsService.tagsToMap(tags))
}
return nil
}
func resourceAlicloudDBReadonlyInstanceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
instance, err := rdsService.DescribeDBInstance(d.Id())
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
if PayType(instance["PayType"].(string)) == Prepaid {
return WrapError(Error("At present, 'Prepaid' instance cannot be deleted and must wait it to be expired and release it automatically."))
}
action := "DeleteDBInstance"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": d.Id(),
"SourceIp": client.SourceIp,
}
runtime := util.RuntimeOptions{}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"RwSplitNetType.Exist", "OperationDenied.DBInstanceStatus", "OperationDenied.MasterDBInstanceState"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"Creating", "Active", "Deleting"}, []string{}, d.Timeout(schema.TimeoutDelete), 1*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err = stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
func buildDBReadonlyCreateRequest(d *schema.ResourceData, meta interface{}) (map[string]interface{}, error) {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": Trim(d.Get("master_db_instance_id").(string)),
"EngineVersion": Trim(d.Get("engine_version").(string)),
"DBInstanceStorage": d.Get("instance_storage"),
"DBInstanceClass": Trim(d.Get("instance_type").(string)),
"DBInstanceDescription": d.Get("instance_name"),
"SourceIp": client.SourceIp,
}
if v, ok := d.GetOk("resource_group_id"); ok && v.(string) != "" {
request["ResourceGroupId"] = v
}
if zone, ok := d.GetOk("zone_id"); ok && Trim(zone.(string)) != "" {
request["ZoneId"] = Trim(zone.(string))
}
vswitchId := Trim(d.Get("vswitch_id").(string))
request["InstanceNetworkType"] = Classic
if vswitchId != "" {
request["VSwitchId"] = vswitchId
request["InstanceNetworkType"] = strings.ToUpper(string(Vpc))
// check vswitchId in zone
vsw, err := vpcService.DescribeVSwitch(vswitchId)
if err != nil {
return nil, WrapError(err)
}
if request["ZoneId"] == "" {
request["ZoneId"] = vsw.ZoneId
} else if strings.Contains(request["ZoneId"].(string), MULTI_IZ_SYMBOL) {
zonestr := strings.Split(strings.SplitAfter(request["ZoneId"].(string), "(")[1], ")")[0]
if !strings.Contains(zonestr, string([]byte(vsw.ZoneId)[len(vsw.ZoneId)-1])) {
return nil, WrapError(Error("The specified vswitch %s isn't in the multi zone %v.", vsw.VSwitchId, request["ZoneId"]))
}
} else if request["ZoneId"] != vsw.ZoneId {
return nil, WrapError(Error("The specified vswitch %s isn't in the multi zone %v.", vsw.VSwitchId, request["ZoneId"]))
}
request["VPCId"] = vsw.VpcId
}
request["PayType"] = Postpaid
request["ClientToken"] = buildClientToken("CreateReadOnlyDBInstance")
return request, nil
}
package alicloud
import (
"encoding/json"
"regexp"
"strconv"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
const dbConnectionPrefixWithSuffixRegex = "^([a-zA-Z0-9\\-_]+)" + dbConnectionSuffixRegex + "$"
var dbConnectionPrefixWithSuffixRegexp = regexp.MustCompile(dbConnectionPrefixWithSuffixRegex)
func resourceAlicloudDBReadWriteSplittingConnection() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDBReadWriteSplittingConnectionCreate,
Read: resourceAlicloudDBReadWriteSplittingConnectionRead,
Update: resourceAlicloudDBReadWriteSplittingConnectionUpdate,
Delete: resourceAlicloudDBReadWriteSplittingConnectionDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"connection_prefix": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(1, 31),
},
"distribution_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"Standard", "Custom"}, false),
},
"weight": {
Type: schema.TypeMap,
Optional: true,
},
"max_delay_time": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"connection_string": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
},
}
}
func resourceAlicloudDBReadWriteSplittingConnectionCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
action := "AllocateReadWriteSplittingConnection"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": Trim(d.Get("instance_id").(string)),
"MaxDelayTime": strconv.Itoa(d.Get("max_delay_time").(int)),
"SourceIp": client.SourceIp,
}
prefix, ok := d.GetOk("connection_prefix")
if ok && prefix.(string) != "" {
request["ConnectionStringPrefix"] = prefix
}
port, ok := d.GetOk("port")
if ok {
request["Port"] = strconv.Itoa(port.(int))
}
request["DistributionType"] = d.Get("distribution_type")
if weight, ok := d.GetOk("weight"); ok && weight != nil && len(weight.(map[string]interface{})) > 0 {
if serial, err := json.Marshal(weight); err != nil {
return WrapError(err)
} else {
request["Weight"] = string(serial)
}
}
runtime := util.RuntimeOptions{}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
if err := resource.Retry(60*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, DBReadInstanceNotReadyStatus) || NeedRetry(err) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetId(request["DBInstanceId"].(string))
// wait read write splitting connection ready after creation
// for it may take up to 10 hours to create a readonly instance
if err := rdsService.WaitForDBReadWriteSplitting(request["DBInstanceId"].(string), "", 60*60*10); err != nil {
return WrapError(err)
}
return resourceAlicloudDBReadWriteSplittingConnectionUpdate(d, meta)
}
func resourceAlicloudDBReadWriteSplittingConnectionRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
proxy, proxyErr := rdsService.DescribeDBProxy(d.Id())
if proxyErr != nil {
if NotFoundError(proxyErr) {
d.SetId("")
return nil
}
return WrapError(proxyErr)
}
if proxy["DBProxyInstanceType"] == "2" {
return resourceAlicloudDBProxyEndpointRead(d, rdsService, proxy["DBProxyInstanceName"].(string))
}
err := rdsService.WaitForDBReadWriteSplitting(d.Id(), "", DefaultLongTimeout)
if err != nil {
return WrapError(err)
}
object, err := rdsService.DescribeDBReadWriteSplittingConnection(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_id", d.Id())
d.Set("connection_string", object["ConnectionString"])
d.Set("distribution_type", object["DistributionType"])
if port, err := strconv.Atoi(object["Port"].(string)); err == nil {
d.Set("port", port)
}
if mdt, err := strconv.Atoi(object["MaxDelayTime"].(string)); err == nil {
d.Set("max_delay_time", mdt)
}
if w, ok := d.GetOk("weight"); ok {
documented := w.(map[string]interface{})
dBInstanceWeights := object["DBInstanceWeights"].(map[string]interface{})["DBInstanceWeight"].([]interface{})
for _, config := range dBInstanceWeights {
config := config.(map[string]interface{})
if config["Availability"] != "Available" {
delete(documented, config["DBInstanceId"].(string))
continue
}
if config["Weight"] != "0" {
if _, ok := documented[config["DBInstanceId"].(string)]; ok {
documented[config["DBInstanceId"].(string)] = config["Weight"]
}
}
}
d.Set("weight", documented)
}
submatch := dbConnectionPrefixWithSuffixRegexp.FindStringSubmatch(object["ConnectionString"].(string))
if len(submatch) > 1 {
d.Set("connection_prefix", submatch[1])
}
return nil
}
func resourceAlicloudDBReadWriteSplittingConnectionUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
action := "ModifyReadWriteSplittingConnection"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": d.Id(),
"SourceIp": client.SourceIp,
}
update := false
if d.HasChange("max_delay_time") {
request["MaxDelayTime"] = strconv.Itoa(d.Get("max_delay_time").(int))
update = true
}
if !update && d.IsNewResource() {
return resourceAlicloudDBReadWriteSplittingConnectionRead(d, meta)
}
if d.HasChange("weight") {
if weight, ok := d.GetOk("weight"); ok && weight != nil && len(weight.(map[string]interface{})) > 0 {
if serial, err := json.Marshal(weight); err != nil {
return err
} else {
request["Weight"] = string(serial)
}
}
update = true
}
if d.HasChange("distribution_type") {
request["DistributionType"] = d.Get("distribution_type")
update = true
}
if update {
// wait instance running before modifying
if err := rdsService.WaitForDBInstance(request["DBInstanceId"].(string), Running, 60*60); err != nil {
return WrapError(err)
}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
if err := resource.Retry(30*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, OperationDeniedDBStatus) || IsExpectedErrors(err, DBReadInstanceNotReadyStatus) || NeedRetry(err) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
// wait instance running after modifying
if err := rdsService.WaitForDBInstance(request["DBInstanceId"].(string), Running, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
}
return resourceAlicloudDBReadWriteSplittingConnectionRead(d, meta)
}
func resourceAlicloudDBReadWriteSplittingConnectionDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
action := "ReleaseReadWriteSplittingConnection"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": d.Id(),
"SourceIp": client.SourceIp,
}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
if err := resource.Retry(30*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, OperationDeniedDBStatus) || NeedRetry(err) {
return resource.RetryableError(err)
}
if NotFoundError(err) || IsExpectedErrors(err, []string{"InvalidRwSplitNetType.NotFound"}) {
return nil
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return WrapError(rdsService.WaitForDBReadWriteSplitting(d.Id(), Deleted, DefaultLongTimeout))
}
func resourceAlicloudDBProxyEndpointRead(d *schema.ResourceData, rdsService RdsService, endPointName string) error {
endpointInfo, endpointError := rdsService.DescribeDBProxyEndpoint(d.Id(), endPointName)
if endpointError != nil {
if NotFoundError(endpointError) {
d.SetId("")
return nil
}
return WrapError(endpointError)
}
d.Set("instance_id", d.Id())
d.Set("connection_string", endpointInfo["DBProxyConnectString"])
d.Set("distribution_type", endpointInfo["ReadOnlyInstanceDistributionType"])
if port, err := strconv.Atoi(endpointInfo["DBProxyConnectStringPort"].(string)); err == nil {
d.Set("port", port)
}
if mdt, err := strconv.Atoi(endpointInfo["ReadOnlyInstanceMaxDelayTime"].(string)); err == nil {
d.Set("max_delay_time", mdt)
}
submatch := dbConnectionPrefixWithSuffixRegexp.FindStringSubmatch(endpointInfo["DBProxyConnectString"].(string))
if len(submatch) > 1 {
d.Set("connection_prefix", submatch[1])
}
var documented map[string]interface{}
if w, ok := d.GetOk("weight"); ok {
documented = w.(map[string]interface{})
} else {
documented = make(map[string]interface{})
}
var weight []map[string]interface{}
rawData := []byte(endpointInfo["ReadOnlyInstanceWeight"].(string))
parseErr := json.Unmarshal(rawData, &weight)
if parseErr != nil {
return WrapError(parseErr)
}
for _, configNode := range weight {
var dbInstanceId string
if instanceId, ok := configNode["DBInstanceId"]; ok {
dbInstanceId = instanceId.(string)
}
if _, ok := configNode["Availability"]; ok && configNode["Availability"] != "Available" {
delete(documented, dbInstanceId)
continue
}
if _, ok := configNode["Weight"]; ok && configNode["Weight"] != "0" {
if _, ok := documented[dbInstanceId]; ok {
documented[dbInstanceId] = configNode["Weight"]
}
}
}
d.Set("weight", documented)
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudDbfsInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDbfsInstanceCreate,
Read: resourceAlicloudDbfsInstanceRead,
Update: resourceAlicloudDbfsInstanceUpdate,
Delete: resourceAlicloudDbfsInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
Update: schema.DefaultTimeout(15 * time.Minute),
Delete: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"attach_mode": {
Type: schema.TypeString,
Optional: true,
},
"attach_point": {
Type: schema.TypeString,
Optional: true,
},
"category": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"standard"}, false),
},
"delete_snapshot": {
Type: schema.TypeBool,
Optional: true,
},
"ecs_list": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ecs_id": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"enable_raid": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"encryption": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"instance_name": {
Type: schema.TypeString,
Required: true,
},
"kms_key_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"performance_level": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PL0", "PL1", "PL2", "PL3"}, false),
},
"raid_stripe_unit_number": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"size": {
Type: schema.TypeInt,
Required: true,
},
"snapshot_id": {
Type: schema.TypeString,
Optional: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
"used_scene": {
Type: schema.TypeString,
Optional: true,
},
"zone_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudDbfsInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateDbfs"
request := make(map[string]interface{})
conn, err := client.NewDbfsClient()
if err != nil {
return WrapError(err)
}
request["Category"] = d.Get("category")
if v, ok := d.GetOkExists("delete_snapshot"); ok {
request["DeleteSnapshot"] = v
}
if v, ok := d.GetOkExists("enable_raid"); ok {
request["EnableRaid"] = v
}
if v, ok := d.GetOkExists("encryption"); ok {
request["Encryption"] = v
}
request["FsName"] = d.Get("instance_name")
if v, ok := d.GetOk("kms_key_id"); ok {
request["KMSKeyId"] = v
}
if v, ok := d.GetOk("performance_level"); ok {
request["PerformanceLevel"] = v
}
if v, ok := d.GetOk("raid_stripe_unit_number"); ok {
request["RaidStripeUnitNumber"] = v
}
request["RegionId"] = client.RegionId
request["SizeG"] = d.Get("size")
if v, ok := d.GetOk("snapshot_id"); ok {
request["SnapshotId"] = v
}
if v, ok := d.GetOk("used_scene"); ok {
request["UsedScene"] = v
}
request["ZoneId"] = d.Get("zone_id")
request["ClientToken"] = buildClientToken("CreateDbfs")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-18"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_dbfs_instance", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["FsId"]))
dbfsService := DbfsService{client}
stateConf := BuildStateConf([]string{}, []string{"unattached"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, dbfsService.DbfsInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudDbfsInstanceUpdate(d, meta)
}
func resourceAlicloudDbfsInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dbfsService := DbfsService{client}
object, err := dbfsService.DescribeDbfsInstance(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_dbfs_instance dbfsService.DescribeDbfsInstance Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("category", object["Category"])
if ecsListList, ok := object["EcsList"]; ok && ecsListList != nil {
ecsListMaps := make([]map[string]interface{}, 0)
for _, ecsListListItem := range ecsListList.([]interface{}) {
if ecsListListItemMap, ok := ecsListListItem.(map[string]interface{}); ok {
ecsListListItemMap["ecs_id"] = ecsListListItemMap["EcsId"]
ecsListMaps = append(ecsListMaps, ecsListListItemMap)
}
d.Set("ecs_list", ecsListMaps)
}
}
d.Set("enable_raid", object["EnableRaid"])
d.Set("encryption", object["Encryption"])
d.Set("kms_key_id", object["KMSKeyId"])
d.Set("performance_level", object["PerformanceLevel"])
if v, ok := object["SizeG"]; ok && fmt.Sprint(v) != "0" {
d.Set("size", formatInt(v))
}
d.Set("status", object["Status"])
d.Set("tags", tagsToMap(object["Tags"]))
d.Set("zone_id", object["ZoneId"])
d.Set("instance_name", object["FsName"])
return nil
}
func resourceAlicloudDbfsInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"FsId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("instance_name") {
update = true
}
request["FsName"] = d.Get("instance_name")
if update {
action := "RenameDbfs"
conn, err := client.NewDbfsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-18"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("instance_name")
}
update = false
resizeDbfsReq := map[string]interface{}{
"FsId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("size") {
update = true
}
resizeDbfsReq["NewSizeG"] = d.Get("size")
if update {
action := "ResizeDbfs"
conn, err := client.NewDbfsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-18"), StringPointer("AK"), nil, resizeDbfsReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, resizeDbfsReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
dbfsService := DbfsService{client}
stateConf := BuildStateConf([]string{}, []string{"attached"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, dbfsService.DbfsInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("size")
}
if d.HasChange("tags") {
oraw, nraw := d.GetChange("tags")
remove := oraw.(map[string]interface{})
create := nraw.(map[string]interface{})
if len(remove) > 0 {
deleteTagsBatchReq := map[string]interface{}{
"DbfsList": "[\"" + d.Id() + "\"]",
"RegionId": client.RegionId,
}
tagsMaps := make([]map[string]interface{}, 0)
for key, value := range remove {
tagsMap := map[string]interface{}{}
tagsMap["TagKey"] = key
tagsMap["TagValue"] = value
tagsMaps = append(tagsMaps, tagsMap)
}
deleteTagsBatchReq["Tags"], _ = convertListMapToJsonString(tagsMaps)
action := "DeleteTagsBatch"
conn, err := client.NewDbfsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-18"), StringPointer("AK"), nil, deleteTagsBatchReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, deleteTagsBatchReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if len(create) > 0 {
addTagsBatchReq := map[string]interface{}{
"DbfsList": "[\"" + d.Id() + "\"]",
"RegionId": client.RegionId,
}
tagsMaps := make([]map[string]interface{}, 0)
for key, value := range create {
tagsMap := map[string]interface{}{}
tagsMap["TagKey"] = key
tagsMap["TagValue"] = value
tagsMaps = append(tagsMaps, tagsMap)
}
addTagsBatchReq["Tags"], _ = convertListMapToJsonString(tagsMaps)
action := "AddTagsBatch"
conn, err := client.NewDbfsClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("AddTagsBatch")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-18"), StringPointer("AK"), nil, addTagsBatchReq, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, addTagsBatchReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("tags")
}
if d.HasChange("ecs_list") {
oldEcsList, newEcsList := d.GetChange("ecs_list")
oldEcsListSet := oldEcsList.(*schema.Set)
newEcsListSet := newEcsList.(*schema.Set)
removed := oldEcsListSet.Difference(newEcsListSet)
added := newEcsListSet.Difference(oldEcsListSet)
if removed.Len() > 0 {
detachdbfsrequest := map[string]interface{}{
"FsId": d.Id(),
}
detachdbfsrequest["RegionId"] = client.RegionId
detachdbfsrequest["ECSInstanceId"] = d.Get("ecs_instance_id")
for _, ecsArg := range removed.List() {
ecsMap := ecsArg.(map[string]interface{})
detachdbfsrequest["ECSInstanceId"] = ecsMap["ecs_id"]
action := "DetachDbfs"
conn, err := client.NewDbfsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-18"), StringPointer("AK"), nil, detachdbfsrequest, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, detachdbfsrequest)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
dbfsService := DbfsService{client}
stateConf := BuildStateConf([]string{}, []string{"unattached", "attached"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, dbfsService.DbfsInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
}
if added.Len() > 0 {
attachdbfsrequest := map[string]interface{}{
"FsId": d.Id(),
}
attachdbfsrequest["RegionId"] = client.RegionId
action := "AttachDbfs"
for _, ecsArg := range added.List() {
ecsMap := ecsArg.(map[string]interface{})
attachdbfsrequest["ECSInstanceId"] = ecsMap["ecs_id"]
conn, err := client.NewDbfsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-18"), StringPointer("AK"), nil, attachdbfsrequest, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, attachdbfsrequest)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
dbfsService := DbfsService{client}
stateConf := BuildStateConf([]string{}, []string{"attached"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, dbfsService.DbfsInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
}
d.SetPartial("ecs_list")
}
d.Partial(false)
return resourceAlicloudDbfsInstanceRead(d, meta)
}
func resourceAlicloudDbfsInstanceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dbfsService := DbfsService{client}
action := "DeleteDbfs"
var response map[string]interface{}
conn, err := client.NewDbfsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"FsId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-18"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist.DBFS"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, dbfsService.DbfsInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
func convertDbfsInstancePaymentTypeResponse(source string) string {
switch source {
case "postpaid":
return "PayAsYouGo"
}
return source
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudDcdnDomain() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDcdnDomainCreate,
Read: resourceAlicloudDcdnDomainRead,
Update: resourceAlicloudDcdnDomainUpdate,
Delete: resourceAlicloudDcdnDomainDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(5 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"cert_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"cert_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"cas", "free", "upload"}, false),
},
"check_url": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"domain_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"force_set": {
Type: schema.TypeString,
Optional: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"ssl_pri": {
Type: schema.TypeString,
Optional: true,
},
"ssl_protocol": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"off", "on"}, false),
Default: "off",
},
"ssl_pub": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("ssl_protocol").(string) != "on"
},
},
"scope": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"domestic", "global", "overseas"}, false),
Default: "domestic",
},
"security_token": {
Type: schema.TypeString,
Optional: true,
},
"sources": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"content": {
Type: schema.TypeString,
Required: true,
},
"port": {
Type: schema.TypeInt,
Optional: true,
Default: 80,
ValidateFunc: validation.IntInSlice([]int{443, 80}),
},
"priority": {
Type: schema.TypeString,
Optional: true,
Default: "20",
},
"type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"ipaddr", "domain", "oss"}, false),
},
"weight": {
Type: schema.TypeString,
Optional: true,
Default: "10",
},
},
},
},
"status": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"offline", "online"}, false),
Default: "online",
},
"top_level_domain": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudDcdnDomainCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dcdnService := DcdnService{client}
var response map[string]interface{}
action := "AddDcdnDomain"
request := make(map[string]interface{})
conn, err := client.NewDcdnClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("check_url"); ok {
request["CheckUrl"] = v
}
request["DomainName"] = d.Get("domain_name")
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("scope"); ok {
request["Scope"] = v
}
if v, ok := d.GetOk("security_token"); ok {
request["SecurityToken"] = v
}
sources, err := dcdnService.convertSourcesToString(d.Get("sources").(*schema.Set).List())
if err != nil {
return WrapError(err)
}
request["Sources"] = sources
if v, ok := d.GetOk("top_level_domain"); ok {
request["TopLevelDomain"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_dcdn_domain", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["DomainName"]))
stateConf := BuildStateConf([]string{}, []string{"online"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, dcdnService.DcdnDomainStateRefreshFunc(d.Id(), []string{"check_failed", "configure_failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudDcdnDomainUpdate(d, meta)
}
func resourceAlicloudDcdnDomainRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dcdnService := DcdnService{client}
object, err := dcdnService.DescribeDcdnDomain(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_dcdn_domain dcdnService.DescribeDcdnDomain Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("domain_name", d.Id())
d.Set("resource_group_id", object["ResourceGroupId"])
d.Set("ssl_protocol", convertSSLProtocolResponse(formatSSLProtocolString(object["SSLProtocol"])))
d.Set("scope", object["Scope"])
if v, ok := object["Sources"].(map[string]interface{})["Source"].([]interface{}); ok {
source := make([]map[string]interface{}, 0)
for _, val := range v {
item := val.(map[string]interface{})
source = append(source, map[string]interface{}{
"content": item["Content"],
"port": item["Port"],
"priority": item["Priority"],
"type": item["Type"],
"weight": item["Weight"],
})
}
if err := d.Set("sources", source); err != nil {
return WrapError(err)
}
}
d.Set("status", object["DomainStatus"])
describeDcdnDomainCertificateInfoObject, err := dcdnService.DescribeDcdnDomainCertificateInfo(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("cert_name", describeDcdnDomainCertificateInfoObject["CertName"])
d.Set("ssl_pub", describeDcdnDomainCertificateInfoObject["SSLPub"])
return nil
}
func resourceAlicloudDcdnDomainUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dcdnService := DcdnService{client}
var response map[string]interface{}
d.Partial(true)
if !d.IsNewResource() && d.HasChange("scope") {
request := map[string]interface{}{
"DomainName": d.Id(),
}
request["Property"] = fmt.Sprintf(`{"coverage":"%s"}`, d.Get("scope").(string))
action := "ModifyDCdnDomainSchdmByProperty"
conn, err := client.NewDcdnClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"online"}, d.Timeout(schema.TimeoutUpdate), 3*time.Second, dcdnService.DcdnDomainStateRefreshFunc(d.Id(), []string{"configure_failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("scope")
}
update := false
request := map[string]interface{}{
"DomainName": d.Id(),
}
if d.HasChange("ssl_protocol") {
update = true
}
request["SSLProtocol"] = d.Get("ssl_protocol")
if d.HasChange("cert_name") {
update = true
request["CertName"] = d.Get("cert_name")
}
request["Region"] = client.RegionId
if d.HasChange("ssl_pub") {
update = true
request["SSLPub"] = d.Get("ssl_pub")
}
if update {
if _, ok := d.GetOk("cert_type"); ok {
request["CertType"] = d.Get("cert_type")
}
if _, ok := d.GetOk("force_set"); ok {
request["ForceSet"] = d.Get("force_set")
}
if _, ok := d.GetOk("ssl_pri"); ok {
request["SSLPri"] = d.Get("ssl_pri")
}
if _, ok := d.GetOk("security_token"); ok {
request["SecurityToken"] = d.Get("security_token")
}
action := "SetDcdnDomainCertificate"
conn, err := client.NewDcdnClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("ssl_protocol")
d.SetPartial("cert_name")
d.SetPartial("ssl_pub")
}
update = false
updateDcdnDomainReq := map[string]interface{}{
"DomainName": d.Id(),
}
if !d.IsNewResource() && d.HasChange("resource_group_id") {
update = true
updateDcdnDomainReq["ResourceGroupId"] = d.Get("resource_group_id")
}
if !d.IsNewResource() && d.HasChange("sources") {
update = true
sources, err := dcdnService.convertSourcesToString(d.Get("sources").(*schema.Set).List())
if err != nil {
return WrapError(err)
}
updateDcdnDomainReq["Sources"] = sources
}
if update {
if _, ok := d.GetOk("security_token"); ok {
updateDcdnDomainReq["SecurityToken"] = d.Get("security_token")
}
if _, ok := d.GetOk("top_level_domain"); ok {
updateDcdnDomainReq["TopLevelDomain"] = d.Get("top_level_domain")
}
action := "UpdateDcdnDomain"
conn, err := client.NewDcdnClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-15"), StringPointer("AK"), nil, updateDcdnDomainReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"online"}, d.Timeout(schema.TimeoutUpdate), 3*time.Second, dcdnService.DcdnDomainStateRefreshFunc(d.Id(), []string{"configure_failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("resource_group_id")
d.SetPartial("sources")
}
if d.HasChange("status") {
object, err := dcdnService.DescribeDcdnDomain(d.Id())
if err != nil {
return WrapError(err)
}
target := d.Get("status").(string)
if object["DomainStatus"].(string) != target {
if target == "offline" {
request := map[string]interface{}{
"DomainName": d.Id(),
}
if v, ok := d.GetOk("security_token"); ok {
request["SecurityToken"] = v
}
action := "StopDcdnDomain"
conn, err := client.NewDcdnClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"offline"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, dcdnService.DcdnDomainStateRefreshFunc(d.Id(), []string{"configure_failed", "check_failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if target == "online" {
request := map[string]interface{}{
"DomainName": d.Id(),
}
if v, ok := d.GetOk("security_token"); ok {
request["SecurityToken"] = v
}
action := "StartDcdnDomain"
conn, err := client.NewDcdnClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"online"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, dcdnService.DcdnDomainStateRefreshFunc(d.Id(), []string{"configure_failed", "check_failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.SetPartial("status")
}
}
d.Partial(false)
stateConf := BuildStateConf([]string{}, []string{"online"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, dcdnService.DcdnDomainStateRefreshFunc(d.Id(), []string{"check_failed", "configure_failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudDcdnDomainRead(d, meta)
}
func resourceAlicloudDcdnDomainDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dcdnService := DcdnService{client}
action := "DeleteDcdnDomain"
var response map[string]interface{}
conn, err := client.NewDcdnClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DomainName": d.Id(),
}
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("security_token"); ok {
request["SecurityToken"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 3*time.Second, dcdnService.DcdnDomainStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
func convertSSLProtocolResponse(source string) string {
switch source {
case "":
return "off"
}
return source
}
func formatSSLProtocolString(source interface{}) string {
if source == nil {
return ""
} else {
return source.(string)
}
}
package alicloud
import (
"encoding/json"
"fmt"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudDcdnDomainConfig() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDcdnDomainConfigCreate,
Read: resourceAlicloudDcdnDomainConfigRead,
Update: resourceAlicloudDcdnDomainConfigUpdate,
Delete: resourceAlicloudDcdnDomainConfigDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"config_id": {
Type: schema.TypeString,
Computed: true,
},
"domain_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(5, 67),
},
"function_args": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"arg_name": {
Type: schema.TypeString,
Required: true,
},
"arg_value": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"function_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudDcdnDomainConfigCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dcdnService := DcdnService{client}
var response map[string]interface{}
action := "BatchSetDcdnDomainConfigs"
request := make(map[string]interface{})
conn, err := client.NewDcdnClient()
if err != nil {
return WrapError(err)
}
config := make([]map[string]interface{}, 1)
functionArgs := d.Get("function_args").(*schema.Set).List()
args := make([]map[string]interface{}, len(functionArgs))
for key, value := range functionArgs {
arg := value.(map[string]interface{})
args[key] = map[string]interface{}{
"argName": arg["arg_name"],
"argValue": arg["arg_value"],
}
}
config[0] = map[string]interface{}{
"functionArgs": args,
"functionName": d.Get("function_name").(string),
}
bytconfig, _ := json.Marshal(config)
request["DomainNames"] = d.Get("domain_name").(string)
request["Functions"] = string(bytconfig)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_dcdn_domain", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprintf("%s:%s:%s", request["DomainNames"], d.Get("function_name"), ""))
object, err := dcdnService.DescribeDcdnDomainConfig(d.Id())
if err != nil {
return WrapError(err)
}
d.SetId(fmt.Sprintf("%s:%s:%s", request["DomainNames"], object["FunctionName"], object["ConfigId"]))
stateConf := BuildStateConf([]string{}, []string{"success"}, d.Timeout(schema.TimeoutCreate), 2*time.Second, dcdnService.DcdnDomainConfigStateRefreshFunc(d.Id(), []string{"failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudDcdnDomainConfigRead(d, meta)
}
func resourceAlicloudDcdnDomainConfigRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dcdnService := &DcdnService{client: client}
object, err := dcdnService.DescribeDcdnDomainConfig(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
functionArgMaps := make([]map[string]interface{}, 0)
for _, functionArg := range object["FunctionArgs"].(map[string]interface{})["FunctionArg"].([]interface{}) {
functionArgItem := functionArg.(map[string]interface{})
functionArgMap := make(map[string]interface{}, 0)
functionArgMap["arg_name"] = functionArgItem["ArgName"]
functionArgMap["arg_value"] = functionArgItem["ArgValue"]
functionArgMaps = append(functionArgMaps, functionArgMap)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
d.Set("config_id", parts[2])
d.Set("domain_name", parts[0])
d.Set("function_args", functionArgMaps)
d.Set("function_name", parts[1])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudDcdnDomainConfigUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dcdnService := DcdnService{client}
var response map[string]interface{}
if d.HasChange("function_args") {
action := "BatchSetDcdnDomainConfigs"
request := make(map[string]interface{})
conn, err := client.NewDcdnClient()
if err != nil {
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
config := make([]map[string]interface{}, 1)
functionArgs := d.Get("function_args").(*schema.Set).List()
args := make([]map[string]interface{}, len(functionArgs))
for key, value := range functionArgs {
arg := value.(map[string]interface{})
args[key] = map[string]interface{}{
"argName": arg["arg_name"],
"argValue": arg["arg_value"],
}
}
config[0] = map[string]interface{}{
"functionArgs": args,
"functionName": parts[1],
"configId": parts[2],
}
bytconfig, _ := json.Marshal(config)
request["DomainNames"] = parts[0]
request["Functions"] = string(bytconfig)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"success"}, d.Timeout(schema.TimeoutCreate), 2*time.Second, dcdnService.DcdnDomainConfigStateRefreshFunc(d.Id(), []string{"failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudDcdnDomainConfigRead(d, meta)
}
func resourceAlicloudDcdnDomainConfigDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dcdnService := DcdnService{client}
var response map[string]interface{}
action := "DeleteDcdnSpecificConfig"
conn, err := client.NewDcdnClient()
if err != nil {
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
request := make(map[string]interface{})
request["ConfigId"] = parts[2]
request["DomainName"] = parts[0]
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 1*time.Second, dcdnService.DcdnDomainConfigStateRefreshFunc(d.Id(), []string{"failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"strconv"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/bssopenapi"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ddosbgp"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudDdosbgpInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDdosbgpInstanceCreate,
Read: resourceAlicloudDdosbgpInstanceRead,
Update: resourceAlicloudDdosbgpInstanceUpdate,
Delete: resourceAlicloudDdosbgpInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"type": {
Type: schema.TypeString,
Optional: true,
Required: false,
Default: string(Enterprise),
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Enterprise", "Professional"}, false),
},
"name": {
Type: schema.TypeString,
Optional: true,
Required: false,
ValidateFunc: validation.StringLenBetween(1, 64),
},
"base_bandwidth": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Default: 20,
},
"bandwidth": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
},
"ip_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"IPv4", "IPv6"}, false),
},
"ip_count": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
},
"period": {
Type: schema.TypeInt,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 24, 36}),
Optional: true,
Default: 12,
ForceNew: true,
},
},
}
}
func resourceAlicloudDdosbgpInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := buildDdosbgpCreateRequest(client.RegionId, d, meta)
var response *bssopenapi.CreateInstanceResponse
err := resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := client.WithBssopenapiClient(func(bssopenapiClient *bssopenapi.Client) (interface{}, error) {
return bssopenapiClient.CreateInstance(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"NotApplicable"}) {
request.RegionId = string(connectivity.APSouthEast1)
request.Domain = connectivity.BssOpenAPIEndpointInternational
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response = raw.(*bssopenapi.CreateInstanceResponse)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ddosbgp_instance", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
instanceId := response.Data.InstanceId
if !response.Success {
return WrapError(Error(response.Message))
}
d.SetId(instanceId)
return resourceAlicloudDdosbgpInstanceUpdate(d, meta)
}
func resourceAlicloudDdosbgpInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ddosbgpService := DdosbgpService{client}
insInfo, err := ddosbgpService.DescribeDdosbgpInstance(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
specInfo, err := ddosbgpService.DescribeDdosbgpInstanceSpec(d.Id(), client.RegionId)
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
ddosbgpInstanceType := string(Enterprise)
if insInfo.InstanceType == "0" {
ddosbgpInstanceType = string(Professional)
}
d.Set("name", insInfo.Remark)
d.Set("region", specInfo.Region)
d.Set("bandwidth", specInfo.PackConfig.PackAdvThre)
d.Set("base_bandwidth", specInfo.PackConfig.PackBasicThre)
d.Set("ip_type", insInfo.IpType)
d.Set("ip_count", specInfo.PackConfig.IpSpec)
d.Set("type", ddosbgpInstanceType)
return nil
}
func resourceAlicloudDdosbgpInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
if d.HasChange("name") {
request := ddosbgp.CreateModifyRemarkRequest()
request.InstanceId = d.Id()
request.RegionId = client.RegionId
request.ResourceRegionId = client.RegionId
request.Remark = d.Get("name").(string)
raw, err := client.WithDdosbgpClient(func(ddosbgpClient *ddosbgp.Client) (interface{}, error) {
return ddosbgpClient.ModifyRemark(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
return resourceAlicloudDdosbgpInstanceRead(d, meta)
}
func resourceAlicloudDdosbgpInstanceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ddosbgpService := DdosbgpService{client}
request := ddosbgp.CreateReleaseInstanceRequest()
request.InstanceId = d.Id()
request.RegionId = client.RegionId
raw, err := client.WithDdosbgpClient(func(ddosbgpClient *ddosbgp.Client) (interface{}, error) {
return ddosbgpClient.ReleaseInstance(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InstanceNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(ddosbgpService.WaitForDdosbgpInstance(d.Id(), Deleted, DefaultTimeoutMedium))
}
func buildDdosbgpCreateRequest(region string, d *schema.ResourceData, meta interface{}) *bssopenapi.CreateInstanceRequest {
request := bssopenapi.CreateCreateInstanceRequest()
request.ProductCode = "ddos"
request.ProductType = "ddosbgp"
request.SubscriptionType = "Subscription"
request.Period = requests.NewInteger(d.Get("period").(int))
ddosbgpInstanceType := "1"
if d.Get("type").(string) == string(Professional) {
ddosbgpInstanceType = "0"
}
baseBandWidth := d.Get("base_bandwidth").(int)
bandWidth := d.Get("bandwidth").(int)
ipCount := d.Get("ip_count").(int)
ddosbgpInstanceIpType := "v4"
if d.Get("ip_type").(string) == string(IPv6) {
ddosbgpInstanceIpType = "v6"
}
request.Parameter = &[]bssopenapi.CreateInstanceParameter{
{
Code: "Type",
Value: ddosbgpInstanceType,
},
{
Code: "Region",
Value: region,
},
{
Code: "IpType",
Value: ddosbgpInstanceIpType,
},
{
Code: "BaseBandwidth",
Value: strconv.Itoa(baseBandWidth),
},
{
Code: "Bandwidth",
Value: strconv.Itoa(bandWidth),
},
{
Code: "IpCount",
Value: strconv.Itoa(ipCount),
},
}
return request
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudDdoscooDomainResource() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDdoscooDomainResourceCreate,
Read: resourceAlicloudDdoscooDomainResourceRead,
Update: resourceAlicloudDdoscooDomainResourceUpdate,
Delete: resourceAlicloudDdoscooDomainResourceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"domain": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"https_ext": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.ValidateJsonString,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
equal, _ := compareJsonTemplateAreEquivalent(old, new)
return equal
},
},
"instance_ids": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"proxy_types": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"proxy_ports": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeInt},
ForceNew: true,
},
"proxy_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"http", "https", "websocket", "websockets"}, false),
},
},
},
ForceNew: true,
},
"real_servers": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"rs_type": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
ValidateFunc: validation.IntInSlice([]int{0, 1}),
},
},
}
}
func resourceAlicloudDdoscooDomainResourceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateDomainResource"
request := make(map[string]interface{})
conn, err := client.NewDdoscooClient()
if err != nil {
return WrapError(err)
}
request["Domain"] = d.Get("domain")
if v, ok := d.GetOk("https_ext"); ok {
request["HttpsExt"] = v
}
request["InstanceIds"] = d.Get("instance_ids")
proxyTypesMaps := make([]map[string]interface{}, 0)
for _, proxyTypes := range d.Get("proxy_types").(*schema.Set).List() {
proxyTypesMap := make(map[string]interface{})
proxyTypesArg := proxyTypes.(map[string]interface{})
proxyTypesMap["ProxyPorts"] = proxyTypesArg["proxy_ports"]
proxyTypesMap["ProxyType"] = proxyTypesArg["proxy_type"]
proxyTypesMaps = append(proxyTypesMaps, proxyTypesMap)
}
request["ProxyTypes"] = proxyTypesMaps
request["RealServers"] = d.Get("real_servers")
request["RsType"] = d.Get("rs_type")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ddoscoo_domain_resource", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["Domain"]))
return resourceAlicloudDdoscooDomainResourceRead(d, meta)
}
func resourceAlicloudDdoscooDomainResourceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ddoscooService := DdoscooService{client}
object, err := ddoscooService.DescribeDdoscooDomainResource(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ddoscoo_domain_resource ddoscooService.DescribeDdoscooDomainResource Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("domain", d.Id())
d.Set("https_ext", object["HttpsExt"])
d.Set("instance_ids", object["InstanceIds"])
proxyTypes := make([]map[string]interface{}, 0)
if proxyTypesList, ok := object["ProxyTypes"].([]interface{}); ok {
for _, v := range proxyTypesList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"proxy_ports": m1["ProxyPorts"],
"proxy_type": m1["ProxyType"],
}
proxyTypes = append(proxyTypes, temp1)
}
}
}
if err := d.Set("proxy_types", proxyTypes); err != nil {
return WrapError(err)
}
d.Set("real_servers", object["RealServers"])
d.Set("rs_type", formatInt(object["RsType"]))
return nil
}
func resourceAlicloudDdoscooDomainResourceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"Domain": d.Id(),
}
ProxyTypes := make([]map[string]interface{}, len(d.Get("proxy_types").(*schema.Set).List()))
for i, ProxyTypesValue := range d.Get("proxy_types").(*schema.Set).List() {
ProxyTypesMap := ProxyTypesValue.(map[string]interface{})
ProxyTypes[i] = map[string]interface{}{
"ProxyPorts": ProxyTypesMap["proxy_ports"],
"ProxyType": ProxyTypesMap["proxy_type"],
}
}
request["ProxyTypes"] = ProxyTypes
if d.HasChange("real_servers") {
update = true
}
request["RealServers"] = d.Get("real_servers")
request["RsType"] = d.Get("rs_type")
if d.HasChange("https_ext") {
update = true
request["HttpsExt"] = d.Get("https_ext")
}
if d.HasChange("instance_ids") {
update = true
}
request["InstanceIds"] = d.Get("instance_ids")
if update {
action := "ModifyDomainResource"
conn, err := client.NewDdoscooClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudDdoscooDomainResourceRead(d, meta)
}
func resourceAlicloudDdoscooDomainResourceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteDomainResource"
var response map[string]interface{}
conn, err := client.NewDdoscooClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"Domain": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"encoding/json"
"fmt"
"log"
"strconv"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ddoscoo"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudDdoscooInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDdoscooInstanceCreate,
Read: resourceAlicloudDdoscooInstanceRead,
Update: resourceAlicloudDdoscooInstanceUpdate,
Delete: resourceAlicloudDdoscooInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(1, 64),
},
"base_bandwidth": {
Type: schema.TypeString,
Required: true,
},
"bandwidth": {
Type: schema.TypeString,
Required: true,
},
"service_bandwidth": {
Type: schema.TypeString,
Required: true,
},
"port_count": {
Type: schema.TypeString,
Required: true,
},
"domain_count": {
Type: schema.TypeString,
Required: true,
},
"period": {
Type: schema.TypeInt,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 24, 36}),
Optional: true,
Default: 1,
ForceNew: true,
},
"product_type": {
Type: schema.TypeString,
Optional: true,
Default: "ddoscoo",
ValidateFunc: validation.StringInSlice([]string{"ddoscoo", "ddoscoo_intl"}, false),
},
},
}
}
func resourceAlicloudDdoscooInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ddoscooService := DdoscooService{client}
var response map[string]interface{}
action := "CreateInstance"
request := make(map[string]interface{})
conn, err := client.NewBssopenapiClient()
if err != nil {
return WrapError(err)
}
request["Period"] = requests.NewInteger(d.Get("period").(int))
request["ProductCode"] = "ddos"
request["ProductType"] = d.Get("product_type").(string)
request["SubscriptionType"] = "Subscription"
request["Parameter"] = []map[string]string{
{
"Code": "ServicePartner",
"Value": "coop-line-001",
},
{
"Code": "Bandwidth",
"Value": d.Get("bandwidth").(string),
},
{
"Code": "BaseBandwidth",
"Value": d.Get("base_bandwidth").(string),
},
{
"Code": "DomainCount",
"Value": d.Get("domain_count").(string),
},
{
"Code": "PortCount",
"Value": d.Get("port_count").(string),
},
{
"Code": "ServiceBandwidth",
"Value": d.Get("service_bandwidth").(string),
},
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-14"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if err != nil {
if IsExpectedErrors(err, []string{"NotApplicable"}) {
conn.Endpoint = String(connectivity.BssOpenAPIEndpointInternational)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ddoscoo_instance", action, AlibabaCloudSdkGoERROR)
}
if response["Code"].(string) != "Success" {
return WrapErrorf(fmt.Errorf("%v", response), DefaultErrorMsg, "alicloud_ddoscoo_instance", action, AlibabaCloudSdkGoERROR)
}
response = response["Data"].(map[string]interface{})
d.SetId(fmt.Sprint(response["InstanceId"]))
stateConf := BuildStateConf([]string{"Pending"}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, ddoscooService.DdosStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudDdoscooInstanceUpdate(d, client)
}
func resourceAlicloudDdoscooInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ddoscooService := DdoscooService{client}
insInfo, err := ddoscooService.DescribeDdoscooInstance(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
specInfo, err := ddoscooService.DescribeDdoscooInstanceSpec(d)
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", insInfo.Remark)
d.Set("bandwidth", strconv.Itoa(specInfo.ElasticBandwidth))
d.Set("base_bandwidth", strconv.Itoa(specInfo.BaseBandwidth))
d.Set("domain_count", strconv.Itoa(specInfo.DomainLimit))
d.Set("port_count", strconv.Itoa(specInfo.PortLimit))
d.Set("service_bandwidth", strconv.Itoa(specInfo.BandwidthMbps))
return nil
}
func resourceAlicloudDdoscooInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ddoscooService := DdoscooService{client}
d.Partial(true)
if d.HasChange("name") {
if err := ddoscooService.UpdateDdoscooInstanceName(d.Id(), d.Get("name").(string)); err != nil {
return WrapError(err)
}
d.SetPartial("name")
}
if d.IsNewResource() {
d.Partial(false)
return resourceAlicloudDdoscooInstanceRead(d, meta)
}
if d.HasChange("bandwidth") {
if err := ddoscooService.UpdateInstanceSpec("bandwidth", "Bandwidth", d, meta); err != nil {
return WrapError(err)
}
d.SetPartial("bandwidth")
}
if d.HasChange("base_bandwidth") {
if err := ddoscooService.UpdateInstanceSpec("base_bandwidth", "BaseBandwidth", d, meta); err != nil {
return WrapError(err)
}
d.SetPartial("base_bandwidth")
}
if d.HasChange("domain_count") {
if err := ddoscooService.UpdateInstanceSpec("domain_count", "DomainCount", d, meta); err != nil {
return WrapError(err)
}
d.SetPartial("domain_count")
}
if d.HasChange("port_count") {
if err := ddoscooService.UpdateInstanceSpec("port_count", "PortCount", d, meta); err != nil {
return WrapError(err)
}
d.SetPartial("port_count")
}
if d.HasChange("service_bandwidth") {
if err := ddoscooService.UpdateInstanceSpec("service_bandwidth", "ServiceBandwidth", d, meta); err != nil {
return WrapError(err)
}
d.SetPartial("service_bandwidth")
}
d.Partial(false)
return resourceAlicloudDdoscooInstanceRead(d, meta)
}
type JsonObject struct {
Code string `json:"Code"`
Message string `json:"Message"`
}
func resourceAlicloudDdoscooInstanceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ddoscoo.CreateReleaseInstanceRequest()
request.RegionId = "cn-hangzhou"
request.InstanceId = d.Id()
raw, err := client.WithDdoscooClient(func(ddoscooClient *ddoscoo.Client) (interface{}, error) {
return ddoscooClient.ReleaseInstance(request)
})
var DeleteResult JsonObject
if err != nil {
_ = json.Unmarshal([]byte(raw.(*ddoscoo.ReleaseInstanceResponse).GetHttpContentString()), &DeleteResult)
if DeleteResult.Code == "InstanceNotExpire" {
log.Printf("[INFO] instance cannot be deleted and must wait it to be expired and release it automatically")
return WrapError(Error("At present, 'Prepaid' instance cannot be deleted and must wait it to be expired and release it automatically."))
}
if IsExpectedErrors(err, []string{"InstanceNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudDdoscooPort() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDdoscooPortCreate,
Read: resourceAlicloudDdoscooPortRead,
Update: resourceAlicloudDdoscooPortUpdate,
Delete: resourceAlicloudDdoscooPortDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"backend_port": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"frontend_port": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"frontend_protocol": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"tcp", "udp"}, false),
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"real_servers": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
}
}
func resourceAlicloudDdoscooPortCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreatePort"
request := make(map[string]interface{})
conn, err := client.NewDdoscooClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("backend_port"); ok {
request["BackendPort"] = v
}
request["FrontendPort"] = d.Get("frontend_port")
request["FrontendProtocol"] = d.Get("frontend_protocol")
request["InstanceId"] = d.Get("instance_id")
request["RealServers"] = d.Get("real_servers")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ddoscoo_port", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["InstanceId"], ":", request["FrontendPort"], ":", request["FrontendProtocol"]))
return resourceAlicloudDdoscooPortRead(d, meta)
}
func resourceAlicloudDdoscooPortRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ddoscooService := DdoscooService{client}
object, err := ddoscooService.DescribeDdoscooPort(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ddoscoo_port ddoscooService.DescribeDdoscooPort Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
d.Set("frontend_port", parts[1])
d.Set("frontend_protocol", parts[2])
d.Set("instance_id", parts[0])
d.Set("backend_port", fmt.Sprint(formatInt(object["BackendPort"])))
d.Set("real_servers", object["RealServers"])
return nil
}
func resourceAlicloudDdoscooPortUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"FrontendPort": parts[1],
"FrontendProtocol": parts[2],
"InstanceId": parts[0],
}
request["BackendPort"] = d.Get("backend_port")
if d.HasChange("real_servers") {
update = true
}
request["RealServers"] = d.Get("real_servers")
if update {
action := "ModifyPort"
conn, err := client.NewDdoscooClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudDdoscooPortRead(d, meta)
}
func resourceAlicloudDdoscooPortDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
action := "DeletePort"
var response map[string]interface{}
conn, err := client.NewDdoscooClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"FrontendPort": parts[1],
"FrontendProtocol": parts[2],
"InstanceId": parts[0],
}
if v, ok := d.GetOk("backend_port"); ok {
request["BackendPort"] = v
}
request["RealServers"] = d.Get("real_servers")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"strconv"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ddoscoo"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudDdoscooSchedulerRule() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDdoscooSchedulerRuleCreate,
Read: resourceAlicloudDdoscooSchedulerRuleRead,
Update: resourceAlicloudDdoscooSchedulerRuleUpdate,
Delete: resourceAlicloudDdoscooSchedulerRuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"cname": {
Type: schema.TypeString,
Computed: true,
},
"param": {
Type: schema.TypeString,
Optional: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
},
"rule_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"rule_type": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntInSlice([]int{2, 3, 6}),
},
"rules": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"status": {
Type: schema.TypeInt,
Computed: true,
},
"type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"A", "CNAME"}, false),
},
"value": {
Type: schema.TypeString,
Optional: true,
},
"value_type": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 6}),
},
"priority": {
Type: schema.TypeInt,
Optional: true,
},
"region_id": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
},
}
}
func resourceAlicloudDdoscooSchedulerRuleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ddoscooService := DdoscooService{client}
request := ddoscoo.CreateCreateSchedulerRuleRequest()
if v, ok := d.GetOk("param"); ok {
request.Param = v.(string)
}
if v, ok := d.GetOk("resource_group_id"); ok {
request.ResourceGroupId = v.(string)
}
request.RuleName = d.Get("rule_name").(string)
request.RuleType = requests.NewInteger(d.Get("rule_type").(int))
rules, err := ddoscooService.convertRulesToString(d.Get("rules").(*schema.Set).List())
if err != nil {
return WrapError(err)
}
request.Rules = rules
raw, err := client.WithDdoscooClient(func(ddoscooClient *ddoscoo.Client) (interface{}, error) {
return ddoscooClient.CreateSchedulerRule(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ddoscoo_scheduler_rule", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ := raw.(*ddoscoo.CreateSchedulerRuleResponse)
d.SetId(fmt.Sprintf("%v", response.RuleName))
return resourceAlicloudDdoscooSchedulerRuleRead(d, meta)
}
func resourceAlicloudDdoscooSchedulerRuleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ddoscooService := DdoscooService{client}
object, err := ddoscooService.DescribeDdoscooSchedulerRule(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("rule_name", d.Id())
d.Set("cname", object.Cname)
rule_type, _ := strconv.Atoi(object.RuleType)
d.Set("rule_type", rule_type)
rules := make([]map[string]interface{}, len(object.Rules))
for i, v := range object.Rules {
rules[i] = map[string]interface{}{
"priority": v.Priority,
"region_id": v.RegionId,
"status": v.Status,
"type": v.Type,
"value": v.Value,
"value_type": v.ValueType,
}
}
if err := d.Set("rules", rules); err != nil {
return WrapError(err)
}
return nil
}
func resourceAlicloudDdoscooSchedulerRuleUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ddoscooService := DdoscooService{client}
update := false
request := ddoscoo.CreateModifySchedulerRuleRequest()
request.RuleName = d.Id()
if d.HasChange("rule_type") {
update = true
}
request.RuleType = requests.NewInteger(d.Get("rule_type").(int))
if d.HasChange("rules") {
update = true
}
rules, err := ddoscooService.convertRulesToString(d.Get("rules").(*schema.Set).List())
if err != nil {
return WrapError(err)
}
request.Rules = rules
if d.HasChange("param") {
update = true
request.Param = d.Get("param").(string)
}
if d.HasChange("resource_group_id") {
update = true
request.ResourceGroupId = d.Get("resource_group_id").(string)
}
if update {
raw, err := client.WithDdoscooClient(func(ddoscooClient *ddoscoo.Client) (interface{}, error) {
return ddoscooClient.ModifySchedulerRule(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudDdoscooSchedulerRuleRead(d, meta)
}
func resourceAlicloudDdoscooSchedulerRuleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ddoscoo.CreateDeleteSchedulerRuleRequest()
request.RuleName = d.Id()
if v, ok := d.GetOk("resource_group_id"); ok {
request.ResourceGroupId = v.(string)
}
raw, err := client.WithDdoscooClient(func(ddoscooClient *ddoscoo.Client) (interface{}, error) {
return ddoscooClient.DeleteSchedulerRule(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudDfsAccessGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDfsAccessGroupCreate,
Read: resourceAlicloudDfsAccessGroupRead,
Update: resourceAlicloudDfsAccessGroupUpdate,
Delete: resourceAlicloudDfsAccessGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"access_group_name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(1, 100),
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(1, 100),
},
"network_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"VPC"}, false),
},
},
}
}
func resourceAlicloudDfsAccessGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateAccessGroup"
request := make(map[string]interface{})
conn, err := client.NewAlidfsClient()
if err != nil {
return WrapError(err)
}
request["AccessGroupName"] = d.Get("access_group_name")
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["NetworkType"] = d.Get("network_type")
request["InputRegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-06-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_dfs_access_group", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["AccessGroupId"]))
return resourceAlicloudDfsAccessGroupRead(d, meta)
}
func resourceAlicloudDfsAccessGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dfsService := DfsService{client}
object, err := dfsService.DescribeDfsAccessGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_dfs_access_group dfsService.DescribeDfsAccessGroup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("access_group_name", object["AccessGroupName"])
d.Set("description", object["Description"])
d.Set("network_type", object["NetworkType"])
return nil
}
func resourceAlicloudDfsAccessGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"AccessGroupId": d.Id(),
}
request["InputRegionId"] = client.RegionId
if d.HasChange("access_group_name") {
update = true
request["AccessGroupName"] = d.Get("access_group_name")
}
if d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
}
if update {
action := "ModifyAccessGroup"
conn, err := client.NewAlidfsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-06-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudDfsAccessGroupRead(d, meta)
}
func resourceAlicloudDfsAccessGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteAccessGroup"
var response map[string]interface{}
conn, err := client.NewAlidfsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AccessGroupId": d.Id(),
}
request["InputRegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-06-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidParameter.AccessGroupNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudDfsAccessRule() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDfsAccessRuleCreate,
Read: resourceAlicloudDfsAccessRuleRead,
Update: resourceAlicloudDfsAccessRuleUpdate,
Delete: resourceAlicloudDfsAccessRuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"access_group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"access_rule_id": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"network_segment": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"priority": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(1, 100),
},
"rw_access_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"RDONLY", "RDWR"}, false),
},
},
}
}
func resourceAlicloudDfsAccessRuleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateAccessRule"
request := make(map[string]interface{})
conn, err := client.NewAlidfsClient()
if err != nil {
return WrapError(err)
}
request["AccessGroupId"] = d.Get("access_group_id")
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["NetworkSegment"] = d.Get("network_segment")
request["Priority"] = d.Get("priority")
request["InputRegionId"] = client.RegionId
request["RWAccessType"] = d.Get("rw_access_type")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-06-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_dfs_access_rule", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["AccessGroupId"], ":", response["AccessRuleId"]))
return resourceAlicloudDfsAccessRuleRead(d, meta)
}
func resourceAlicloudDfsAccessRuleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dfsService := DfsService{client}
object, err := dfsService.DescribeDfsAccessRule(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_dfs_access_rule dfsService.DescribeDfsAccessRule Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("access_group_id", parts[0])
d.Set("access_rule_id", parts[1])
d.Set("description", object["Description"])
d.Set("network_segment", object["NetworkSegment"])
if v, ok := object["Priority"]; ok && fmt.Sprint(v) != "0" {
d.Set("priority", formatInt(v))
}
d.Set("rw_access_type", object["RWAccessType"])
return nil
}
func resourceAlicloudDfsAccessRuleUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"AccessGroupId": parts[0],
"AccessRuleId": parts[1],
}
request["InputRegionId"] = client.RegionId
if d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
}
if d.HasChange("priority") {
update = true
request["Priority"] = d.Get("priority")
}
if d.HasChange("rw_access_type") {
update = true
request["RWAccessType"] = d.Get("rw_access_type")
}
if update {
action := "ModifyAccessRule"
conn, err := client.NewAlidfsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-06-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudDfsAccessRuleRead(d, meta)
}
func resourceAlicloudDfsAccessRuleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteAccessRule"
var response map[string]interface{}
conn, err := client.NewAlidfsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AccessGroupId": parts[0],
"AccessRuleId": parts[1],
}
request["InputRegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-06-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidParameter.AccessRuleNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudDfsFileSystem() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDfsFileSystemCreate,
Read: resourceAlicloudDfsFileSystemRead,
Update: resourceAlicloudDfsFileSystemUpdate,
Delete: resourceAlicloudDfsFileSystemDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
},
"file_system_name": {
Type: schema.TypeString,
Required: true,
},
"protocol_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"HDFS"}, false),
},
"provisioned_throughput_in_mi_bps": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IntBetween(1, 1024),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("throughput_mode"); ok && v.(string) == "Provisioned" {
return false
}
return true
},
},
"space_capacity": {
Type: schema.TypeInt,
Required: true,
},
"storage_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PERFORMANCE", "STANDARD"}, false),
},
"throughput_mode": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
ValidateFunc: validation.StringInSlice([]string{"Provisioned", "Standard"}, false),
},
"zone_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudDfsFileSystemCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateFileSystem"
request := make(map[string]interface{})
conn, err := client.NewAlidfsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["FileSystemName"] = d.Get("file_system_name")
if v, ok := d.GetOk("partition_number"); ok {
request["PartitionNumber"] = v
}
request["ProtocolType"] = d.Get("protocol_type")
if v, ok := d.GetOk("provisioned_throughput_in_mi_bps"); ok {
request["ProvisionedThroughputInMiBps"] = v
}
request["InputRegionId"] = client.RegionId
request["SpaceCapacity"] = d.Get("space_capacity")
request["StorageType"] = d.Get("storage_type")
if v, ok := d.GetOk("throughput_mode"); ok {
request["ThroughputMode"] = v
}
request["ZoneId"] = d.Get("zone_id")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-06-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_dfs_file_system", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["FileSystemId"]))
return resourceAlicloudDfsFileSystemRead(d, meta)
}
func resourceAlicloudDfsFileSystemRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dfsService := DfsService{client}
object, err := dfsService.DescribeDfsFileSystem(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_dfs_file_system dfsService.DescribeDfsFileSystem Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", object["Description"])
d.Set("file_system_name", object["FileSystemName"])
d.Set("protocol_type", object["ProtocolType"])
d.Set("provisioned_throughput_in_mi_bps", formatInt(object["ProvisionedThroughputInMiBps"]))
d.Set("space_capacity", formatInt(object["SpaceCapacity"]))
d.Set("storage_type", object["StorageType"])
d.Set("throughput_mode", object["ThroughputMode"])
d.Set("zone_id", object["ZoneId"])
return nil
}
func resourceAlicloudDfsFileSystemUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"FileSystemId": d.Id(),
}
request["InputRegionId"] = client.RegionId
if d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
}
if d.HasChange("file_system_name") {
update = true
request["FileSystemName"] = d.Get("file_system_name")
}
if d.HasChange("provisioned_throughput_in_mi_bps") {
update = true
if v, ok := d.GetOk("provisioned_throughput_in_mi_bps"); ok {
request["ProvisionedThroughputInMiBps"] = v
}
}
if d.HasChange("space_capacity") {
update = true
request["SpaceCapacity"] = d.Get("space_capacity")
}
if d.HasChange("throughput_mode") {
update = true
if v, ok := d.GetOk("throughput_mode"); ok {
request["ThroughputMode"] = v
}
}
if update {
action := "ModifyFileSystem"
conn, err := client.NewAlidfsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-06-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudDfsFileSystemRead(d, meta)
}
func resourceAlicloudDfsFileSystemDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteFileSystem"
var response map[string]interface{}
conn, err := client.NewAlidfsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"FileSystemId": d.Id(),
}
request["InputRegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-06-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidParameter.FileSystemNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudDfsMountPoint() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDfsMountPointCreate,
Read: resourceAlicloudDfsMountPointRead,
Update: resourceAlicloudDfsMountPointUpdate,
Delete: resourceAlicloudDfsMountPointDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"access_group_id": {
Type: schema.TypeString,
Required: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"file_system_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"mount_point_id": {
Type: schema.TypeString,
Computed: true,
},
"network_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"VPC"}, false),
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Inactive"}, false),
},
"vpc_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"vswitch_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudDfsMountPointCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateMountPoint"
request := make(map[string]interface{})
conn, err := client.NewAlidfsClient()
if err != nil {
return WrapError(err)
}
request["AccessGroupId"] = d.Get("access_group_id")
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["FileSystemId"] = d.Get("file_system_id")
request["NetworkType"] = d.Get("network_type")
request["InputRegionId"] = client.RegionId
request["VpcId"] = d.Get("vpc_id")
request["VSwitchId"] = d.Get("vswitch_id")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-06-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_dfs_mount_point", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["FileSystemId"], ":", response["MountPointId"]))
return resourceAlicloudDfsMountPointUpdate(d, meta)
}
func resourceAlicloudDfsMountPointRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dfsService := DfsService{client}
object, err := dfsService.DescribeDfsMountPoint(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_dfs_mount_point dfsService.DescribeDfsMountPoint Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("file_system_id", parts[0])
d.Set("mount_point_id", parts[1])
d.Set("access_group_id", object["AccessGroupId"])
d.Set("description", object["Description"])
d.Set("network_type", object["NetworkType"])
d.Set("status", object["Status"])
d.Set("vpc_id", object["VpcId"])
d.Set("vswitch_id", object["VSwitchId"])
return nil
}
func resourceAlicloudDfsMountPointUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"FileSystemId": parts[0],
"MountPointId": parts[1],
}
request["InputRegionId"] = client.RegionId
if !d.IsNewResource() && d.HasChange("access_group_id") {
update = true
request["AccessGroupId"] = d.Get("access_group_id")
}
if !d.IsNewResource() && d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
}
if d.HasChange("status") {
update = true
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
}
if update {
action := "ModifyMountPoint"
conn, err := client.NewAlidfsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-06-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudDfsMountPointRead(d, meta)
}
func resourceAlicloudDfsMountPointDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteMountPoint"
var response map[string]interface{}
conn, err := client.NewAlidfsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"FileSystemId": parts[0],
"MountPointId": parts[1],
}
request["InputRegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-06-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidParameter.MountPointNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudDirectMailDomain() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDirectMailDomainCreate,
Read: resourceAlicloudDirectMailDomainRead,
Delete: resourceAlicloudDirectMailDomainDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"domain_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(4, 50),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudDirectMailDomainCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateDomain"
request := make(map[string]interface{})
conn, err := client.NewDmClient()
if err != nil {
return WrapError(err)
}
request["DomainName"] = d.Get("domain_name")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-11-23"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_direct_mail_domain", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["DomainId"]))
return resourceAlicloudDirectMailDomainRead(d, meta)
}
func resourceAlicloudDirectMailDomainRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dmService := DmService{client}
object, err := dmService.DescribeDirectMailDomain(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_direct_mail_domain dmService.DescribeDirectMailDomain Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("domain_name", object["DomainName"])
d.Set("status", object["DomainStatus"])
return nil
}
func resourceAlicloudDirectMailDomainDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteDomain"
var response map[string]interface{}
conn, err := client.NewDmClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DomainId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-11-23"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudDirectMailMailAddress() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDirectMailMailAddressCreate,
Read: resourceAlicloudDirectMailMailAddressRead,
Update: resourceAlicloudDirectMailMailAddressUpdate,
Delete: resourceAlicloudDirectMailMailAddressDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"account_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-z0-9_-]+@[a-z0-9_-]+(\.[a-z0-9_-]+)+$`), "The email address must be filled in the format of account@domain, and only lowercase letters or numbers can be used."),
},
"password": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[0-9A-Za-z]{10,20}$`), "The password must be length 10-20 string, contains numbers, uppercase letters, lowercase letters at the same time."),
},
"reply_address": {
Type: schema.TypeString,
Optional: true,
},
"sendtype": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"batch", "trigger"}, false),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudDirectMailMailAddressCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateMailAddress"
request := make(map[string]interface{})
conn, err := client.NewDmClient()
if err != nil {
return WrapError(err)
}
request["AccountName"] = d.Get("account_name")
if v, ok := d.GetOk("reply_address"); ok {
request["ReplyAddress"] = v
}
request["Sendtype"] = d.Get("sendtype")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-11-23"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_direct_mail_mail_address", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["MailAddressId"]))
return resourceAlicloudDirectMailMailAddressUpdate(d, meta)
}
func resourceAlicloudDirectMailMailAddressRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dmService := DmService{client}
object, err := dmService.DescribeDirectMailMailAddress(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_direct_mail_mail_address dmService.DescribeDirectMailMailAddress Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("account_name", object["AccountName"])
d.Set("reply_address", object["ReplyAddress"])
d.Set("sendtype", object["Sendtype"])
d.Set("status", object["AccountStatus"])
return nil
}
func resourceAlicloudDirectMailMailAddressUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"MailAddressId": d.Id(),
}
if d.HasChange("password") {
update = true
if v, ok := d.GetOk("password"); ok {
request["Password"] = v
}
}
if !d.IsNewResource() && d.HasChange("reply_address") {
update = true
if v, ok := d.GetOk("reply_address"); ok {
request["ReplyAddress"] = v
}
}
if update {
action := "ModifyMailAddress"
conn, err := client.NewDmClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-11-23"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudDirectMailMailAddressRead(d, meta)
}
func resourceAlicloudDirectMailMailAddressDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteMailAddress"
var response map[string]interface{}
conn, err := client.NewDmClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"MailAddressId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-11-23"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidMailAddressId.Malformed"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudDirectMailReceivers() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDirectMailReceiversCreate,
Read: resourceAlicloudDirectMailReceiversRead,
Delete: resourceAlicloudDirectMailReceiversDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(1, 50),
},
"receivers_alias": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(1, 30),
},
"receivers_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(1, 30),
},
"status": {
Type: schema.TypeInt,
Computed: true,
},
},
}
}
func resourceAlicloudDirectMailReceiversCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateReceiver"
request := make(map[string]interface{})
conn, err := client.NewDmClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Desc"] = v
}
request["ReceiversAlias"] = d.Get("receivers_alias")
request["ReceiversName"] = d.Get("receivers_name")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-11-23"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_direct_mail_receivers", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["ReceiverId"]))
return resourceAlicloudDirectMailReceiversRead(d, meta)
}
func resourceAlicloudDirectMailReceiversRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dmService := DmService{client}
object, err := dmService.DescribeDirectMailReceivers(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_direct_mail_receivers dmService.DescribeDirectMailReceivers Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", object["Desc"])
d.Set("receivers_alias", object["ReceiversAlias"])
d.Set("receivers_name", object["ReceiversName"])
d.Set("status", formatInt(object["ReceiversStatus"]))
return nil
}
func resourceAlicloudDirectMailReceiversDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteReceiver"
var response map[string]interface{}
conn, err := client.NewDmClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ReceiverId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-11-23"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudDirectMailTag() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDirectMailTagCreate,
Read: resourceAlicloudDirectMailTagRead,
Update: resourceAlicloudDirectMailTagUpdate,
Delete: resourceAlicloudDirectMailTagDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"tag_name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[A-Za-z0-9]{1,50}$`), "The name must be `1` to `50` characters in length, and can contain letters and digits."),
},
},
}
}
func resourceAlicloudDirectMailTagCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateTag"
request := make(map[string]interface{})
conn, err := client.NewDmClient()
if err != nil {
return WrapError(err)
}
request["TagName"] = d.Get("tag_name")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-11-23"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_direct_mail_tag", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["TagId"]))
return resourceAlicloudDirectMailTagRead(d, meta)
}
func resourceAlicloudDirectMailTagRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dmService := DmService{client}
object, err := dmService.DescribeDirectMailTag(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_direct_mail_tag dmService.DescribeDirectMailTag Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("tag_name", object["TagName"])
return nil
}
func resourceAlicloudDirectMailTagUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"TagId": d.Id(),
}
if d.HasChange("tag_name") {
update = true
request["TagName"] = d.Get("tag_name")
}
if update {
action := "ModifyTag"
conn, err := client.NewDmClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-11-23"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudDirectMailTagRead(d, meta)
}
func resourceAlicloudDirectMailTagDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteTag"
var response map[string]interface{}
conn, err := client.NewDmClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"TagId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-11-23"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudDmsEnterpriseInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDmsEnterpriseInstanceCreate,
Read: resourceAlicloudDmsEnterpriseInstanceRead,
Update: resourceAlicloudDmsEnterpriseInstanceUpdate,
Delete: resourceAlicloudDmsEnterpriseInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"data_link_name": {
Type: schema.TypeString,
Optional: true,
},
"database_password": {
Type: schema.TypeString,
Required: true,
Sensitive: true,
},
"database_user": {
Type: schema.TypeString,
Required: true,
},
"dba_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"dba_nick_name": {
Type: schema.TypeString,
Computed: true,
},
"dba_uid": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
},
"ddl_online": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{0, 1, 2}),
},
"ecs_instance_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"ecs_region": {
Type: schema.TypeString,
Optional: true,
},
"env_type": {
Type: schema.TypeString,
Required: true,
},
"export_timeout": {
Type: schema.TypeInt,
Required: true,
},
"host": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"instance_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"instance_alias"},
},
"instance_alias": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Field 'instance_alias' has been deprecated from version 1.100.0. Use 'instance_name' instead.",
ConflictsWith: []string{"instance_name"},
},
"instance_source": {
Type: schema.TypeString,
Required: true,
},
"instance_type": {
Type: schema.TypeString,
Required: true,
},
"network_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"port": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
},
"query_timeout": {
Type: schema.TypeInt,
Required: true,
},
"safe_rule": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"safe_rule_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"sid": {
Type: schema.TypeString,
Optional: true,
},
"skip_test": {
Type: schema.TypeBool,
Optional: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"state": {
Type: schema.TypeString,
Computed: true,
Deprecated: "Field 'state' has been deprecated from version 1.100.0. Use 'status' instead.",
},
"tid": {
Type: schema.TypeInt,
Optional: true,
},
"use_dsql": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{0, 1}),
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudDmsEnterpriseInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "RegisterInstance"
request := make(map[string]interface{})
conn, err := client.NewDmsenterpriseClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("data_link_name"); ok {
request["DataLinkName"] = v
}
request["DatabasePassword"] = d.Get("database_password")
request["DatabaseUser"] = d.Get("database_user")
request["DbaUid"] = d.Get("dba_uid")
if v, ok := d.GetOk("ddl_online"); ok {
request["DdlOnline"] = v
}
if v, ok := d.GetOk("ecs_instance_id"); ok {
request["EcsInstanceId"] = v
}
if v, ok := d.GetOk("ecs_region"); ok {
request["EcsRegion"] = v
}
request["EnvType"] = d.Get("env_type")
request["ExportTimeout"] = d.Get("export_timeout")
request["Host"] = d.Get("host")
if v, ok := d.GetOk("instance_name"); ok {
request["InstanceAlias"] = v
} else if v, ok := d.GetOk("instance_alias"); ok {
request["InstanceAlias"] = v
} else {
return WrapError(Error(`[ERROR] Argument "instance_alias" or "instance_name" must be set one!`))
}
request["InstanceSource"] = d.Get("instance_source")
request["InstanceType"] = d.Get("instance_type")
request["NetworkType"] = d.Get("network_type")
request["Port"] = d.Get("port")
request["QueryTimeout"] = d.Get("query_timeout")
request["SafeRule"] = d.Get("safe_rule")
if v, ok := d.GetOk("sid"); ok {
request["Sid"] = v
}
if v, ok := d.GetOkExists("skip_test"); ok {
request["SkipTest"] = v
}
if v, ok := d.GetOk("tid"); ok {
request["Tid"] = v
}
if v, ok := d.GetOk("use_dsql"); ok {
request["UseDsql"] = v
}
if v, ok := d.GetOk("vpc_id"); ok {
request["VpcId"] = v
}
wait := incrementalWait(3*time.Second, 2*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-11-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"RegisterInstanceFailure"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_dms_enterprise_instance", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["Host"], ":", request["Port"]))
return resourceAlicloudDmsEnterpriseInstanceUpdate(d, meta)
}
func resourceAlicloudDmsEnterpriseInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dms_enterpriseService := Dms_enterpriseService{client}
object, err := dms_enterpriseService.DescribeDmsEnterpriseInstance(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_dms_enterprise_instance dms_enterpriseService.DescribeDmsEnterpriseInstance Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("host", parts[0])
d.Set("port", formatInt(parts[1]))
d.Set("data_link_name", object["DataLinkName"])
d.Set("database_user", object["DatabaseUser"])
d.Set("dba_id", object["DbaId"])
d.Set("ddl_online", formatInt(object["DdlOnline"]))
d.Set("ecs_instance_id", object["EcsInstanceId"])
d.Set("ecs_region", object["EcsRegion"])
d.Set("env_type", object["EnvType"])
d.Set("export_timeout", formatInt(object["ExportTimeout"]))
d.Set("instance_id", object["InstanceId"])
d.Set("instance_name", object["InstanceAlias"])
d.Set("instance_alias", object["InstanceAlias"])
d.Set("instance_source", object["InstanceSource"])
d.Set("instance_type", object["InstanceType"])
d.Set("query_timeout", formatInt(object["QueryTimeout"]))
d.Set("safe_rule_id", object["SafeRuleId"])
d.Set("sid", object["Sid"])
d.Set("status", object["State"])
d.Set("state", object["State"])
d.Set("use_dsql", formatInt(object["UseDsql"]))
d.Set("vpc_id", object["VpcId"])
d.Set("dba_nick_name", object["DbaNickName"])
return nil
}
func resourceAlicloudDmsEnterpriseInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"Host": parts[0],
"Port": parts[1],
}
if !d.IsNewResource() && d.HasChange("database_password") {
update = true
}
request["DatabasePassword"] = d.Get("database_password")
if !d.IsNewResource() && d.HasChange("database_user") {
update = true
}
request["DatabaseUser"] = d.Get("database_user")
if d.HasChange("dba_id") {
update = true
}
request["DbaId"] = d.Get("dba_id")
if !d.IsNewResource() && d.HasChange("env_type") {
update = true
}
request["EnvType"] = d.Get("env_type")
if !d.IsNewResource() && d.HasChange("export_timeout") {
update = true
}
request["ExportTimeout"] = d.Get("export_timeout")
if d.HasChange("instance_id") {
update = true
}
request["InstanceId"] = d.Get("instance_id")
if !d.IsNewResource() && d.HasChange("instance_name") {
update = true
request["InstanceAlias"] = d.Get("instance_name")
}
if !d.IsNewResource() && d.HasChange("instance_alias") {
update = true
request["InstanceAlias"] = d.Get("instance_alias")
}
if request["InstanceAlias"] == nil {
request["InstanceAlias"] = d.Get("instance_name")
}
if !d.IsNewResource() && d.HasChange("instance_source") {
update = true
}
request["InstanceSource"] = d.Get("instance_source")
if !d.IsNewResource() && d.HasChange("instance_type") {
update = true
}
request["InstanceType"] = d.Get("instance_type")
if !d.IsNewResource() && d.HasChange("query_timeout") {
update = true
}
request["QueryTimeout"] = d.Get("query_timeout")
if d.HasChange("safe_rule_id") {
update = true
}
request["SafeRuleId"] = d.Get("safe_rule_id")
if !d.IsNewResource() && d.HasChange("data_link_name") {
update = true
request["DataLinkName"] = d.Get("data_link_name")
}
if !d.IsNewResource() && d.HasChange("ddl_online") {
update = true
request["DdlOnline"] = d.Get("ddl_online")
}
if !d.IsNewResource() && d.HasChange("ecs_instance_id") {
update = true
request["EcsInstanceId"] = d.Get("ecs_instance_id")
}
if !d.IsNewResource() && d.HasChange("ecs_region") {
update = true
request["EcsRegion"] = d.Get("ecs_region")
}
if !d.IsNewResource() && d.HasChange("sid") {
update = true
request["Sid"] = d.Get("sid")
}
if !d.IsNewResource() && d.HasChange("use_dsql") {
update = true
request["UseDsql"] = d.Get("use_dsql")
}
if !d.IsNewResource() && d.HasChange("vpc_id") {
update = true
request["VpcId"] = d.Get("vpc_id")
}
if update {
if _, ok := d.GetOkExists("skip_test"); ok {
request["SkipTest"] = d.Get("skip_test")
}
if _, ok := d.GetOk("tid"); ok {
request["Tid"] = d.Get("tid")
}
action := "UpdateInstance"
conn, err := client.NewDmsenterpriseClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-11-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudDmsEnterpriseInstanceRead(d, meta)
}
func resourceAlicloudDmsEnterpriseInstanceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteInstance"
var response map[string]interface{}
conn, err := client.NewDmsenterpriseClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"Host": parts[0],
"Port": parts[1],
}
if v, ok := d.GetOk("sid"); ok {
request["Sid"] = v
}
if v, ok := d.GetOk("tid"); ok {
request["Tid"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-11-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InstanceNoEnoughNumber"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudDmsEnterpriseUser() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDmsEnterpriseUserCreate,
Read: resourceAlicloudDmsEnterpriseUserRead,
Update: resourceAlicloudDmsEnterpriseUserUpdate,
Delete: resourceAlicloudDmsEnterpriseUserDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"max_execute_count": {
Type: schema.TypeInt,
Optional: true,
},
"max_result_count": {
Type: schema.TypeInt,
Optional: true,
},
"mobile": {
Type: schema.TypeString,
Optional: true,
},
"role_names": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"status": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"DISABLE", "NORMAL"}, false),
Default: "NORMAL",
},
"tid": {
Type: schema.TypeInt,
Optional: true,
},
"uid": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"user_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"nick_name"},
},
"nick_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Field 'nick_name' has been deprecated from version 1.100.0. Use 'user_name' instead.",
ConflictsWith: []string{"user_name"},
},
},
}
}
func resourceAlicloudDmsEnterpriseUserCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "RegisterUser"
request := make(map[string]interface{})
conn, err := client.NewDmsenterpriseClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("mobile"); ok {
request["Mobile"] = v
}
if v, ok := d.GetOk("role_names"); ok && v != nil {
request["RoleNames"] = convertListToCommaSeparate(v.(*schema.Set).List())
}
if v, ok := d.GetOk("tid"); ok {
request["Tid"] = v
}
request["Uid"] = d.Get("uid")
if v, ok := d.GetOk("user_name"); ok {
request["UserNick"] = v
} else if v, ok := d.GetOk("nick_name"); ok {
request["UserNick"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-11-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_dms_enterprise_user", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["Uid"]))
return resourceAlicloudDmsEnterpriseUserUpdate(d, meta)
}
func resourceAlicloudDmsEnterpriseUserRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dms_enterpriseService := Dms_enterpriseService{client}
object, err := dms_enterpriseService.DescribeDmsEnterpriseUser(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_dms_enterprise_user dms_enterpriseService.DescribeDmsEnterpriseUser Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("uid", d.Id())
d.Set("mobile", object["Mobile"])
d.Set("role_names", object["RoleNameList"].(map[string]interface{})["RoleNames"])
d.Set("status", object["State"])
d.Set("user_name", object["NickName"])
d.Set("nick_name", object["NickName"])
return nil
}
func resourceAlicloudDmsEnterpriseUserUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dms_enterpriseService := Dms_enterpriseService{client}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"Uid": d.Id(),
}
if !d.IsNewResource() && d.HasChange("mobile") {
update = true
request["Mobile"] = d.Get("mobile")
}
if !d.IsNewResource() && d.HasChange("role_names") {
update = true
request["RoleNames"] = convertListToCommaSeparate(d.Get("role_names").(*schema.Set).List())
}
if !d.IsNewResource() && d.HasChange("user_name") {
update = true
request["UserNick"] = d.Get("user_name")
}
if !d.IsNewResource() && d.HasChange("nick_name") {
update = true
request["UserNick"] = d.Get("nick_name")
}
if update {
if _, ok := d.GetOk("max_execute_count"); ok {
request["MaxExecuteCount"] = d.Get("max_execute_count")
}
if _, ok := d.GetOk("max_result_count"); ok {
request["MaxResultCount"] = d.Get("max_result_count")
}
if _, ok := d.GetOk("tid"); ok {
request["Tid"] = d.Get("tid")
}
action := "UpdateUser"
conn, err := client.NewDmsenterpriseClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-11-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("mobile")
d.SetPartial("role_names")
d.SetPartial("nick_name")
d.SetPartial("user_name")
}
if d.HasChange("status") {
object, err := dms_enterpriseService.DescribeDmsEnterpriseUser(d.Id())
if err != nil {
return WrapError(err)
}
target := d.Get("status").(string)
if object["State"].(string) != target {
if target == "DISABLE" {
request := map[string]interface{}{
"Uid": d.Id(),
}
if v, ok := d.GetOk("tid"); ok {
request["Tid"] = v
}
action := "DisableUser"
conn, err := client.NewDmsenterpriseClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-11-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if target == "NORMAL" {
request := map[string]interface{}{
"Uid": d.Id(),
}
if v, ok := d.GetOk("tid"); ok {
request["Tid"] = v
}
action := "EnableUser"
conn, err := client.NewDmsenterpriseClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-11-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("status")
}
}
d.Partial(false)
return resourceAlicloudDmsEnterpriseUserRead(d, meta)
}
func resourceAlicloudDmsEnterpriseUserDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteUser"
var response map[string]interface{}
conn, err := client.NewDmsenterpriseClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"Uid": d.Id(),
}
if v, ok := d.GetOk("tid"); ok {
request["Tid"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-11-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/alidns"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudDns() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDnsCreate,
Read: resourceAlicloudDnsRead,
Update: resourceAlicloudDnsUpdate,
Delete: resourceAlicloudDnsDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(5, 67),
ForceNew: true,
},
"domain_id": {
Type: schema.TypeString,
Computed: true,
},
"group_id": {
Type: schema.TypeString,
Optional: true,
},
"dns_server": {
Type: schema.TypeSet,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudDnsCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := alidns.CreateAddDomainRequest()
request.RegionId = client.RegionId
request.DomainName = d.Get("name").(string)
request.ResourceGroupId = d.Get("resource_group_id").(string)
raw, err := client.WithDnsClient(func(dnsClient *alidns.Client) (interface{}, error) {
return dnsClient.AddDomain(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_dns", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*alidns.AddDomainResponse)
d.SetId(response.DomainName)
return resourceAlicloudDnsUpdate(d, meta)
}
func resourceAlicloudDnsUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := alidns.CreateChangeDomainGroupRequest()
request.RegionId = client.RegionId
request.DomainName = d.Id()
request.GroupId = d.Get("group_id").(string)
if d.HasChange("group_id") {
raw, err := client.WithDnsClient(func(dnsClient *alidns.Client) (interface{}, error) {
return dnsClient.ChangeDomainGroup(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
return resourceAlicloudDnsRead(d, meta)
}
func resourceAlicloudDnsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dnsService := &DnsService{client: client}
object, err := dnsService.DescribeDns(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("group_id", object.GroupId)
d.Set("domain_id", object.DomainId)
d.Set("name", object.DomainName)
d.Set("dns_server", object.DnsServers.DnsServer)
return nil
}
func resourceAlicloudDnsDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := alidns.CreateDeleteDomainRequest()
request.DomainName = d.Id()
request.RegionId = client.RegionId
return resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithDnsClient(func(dnsClient *alidns.Client) (interface{}, error) {
return dnsClient.DeleteDomain(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"RecordForbidden.DNSChange", "InternalError", "DnsSystemBusyness"}) {
return resource.RetryableError(WrapErrorf(err, DefaultTimeoutMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR))
}
return resource.NonRetryableError(WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR))
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
}
package alicloud
import (
"log"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/services/alidns"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudAlidnsDomainAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudAlidnsDomainAttachmentCreate,
Read: resourceAlicloudAlidnsDomainAttachmentRead,
Update: resourceAlicloudAlidnsDomainAttachmentUpdate,
Delete: resourceAlicloudAlidnsdomainAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"domain_names": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Required: true,
},
},
}
}
func resourceAlicloudAlidnsDomainAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
d.SetId(d.Get("instance_id").(string))
return resourceAlicloudAlidnsDomainAttachmentUpdate(d, meta)
}
func resourceAlicloudAlidnsDomainAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dnsService := DnsService{client}
object, err := dnsService.DescribeAlidnsDomainAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_alidns_domain_attachment alidnsService.DescribeAlidnsDomain Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_id", d.Id())
d.Set("domain_names", flatten(object))
return nil
}
func resourceAlicloudAlidnsDomainAttachmentUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dnsService := DnsService{client}
o, n := d.GetChange("domain_names")
oldmap := make(map[string]string)
newmap := make(map[string]string)
add := make([]string, 0)
remove := make([]string, 0)
for _, v := range o.(*schema.Set).List() {
oldmap[v.(string)] = v.(string)
}
for _, v := range n.(*schema.Set).List() {
if _, ok := oldmap[v.(string)]; !ok {
add = append(add, v.(string))
}
}
for _, v := range n.(*schema.Set).List() {
newmap[v.(string)] = v.(string)
}
for _, v := range o.(*schema.Set).List() {
if _, ok := newmap[v.(string)]; !ok {
remove = append(remove, v.(string))
}
}
if len(remove) > 0 {
removeNames := strings.Join(remove, ",")
request := alidns.CreateUnbindInstanceDomainsRequest()
request.InstanceId = d.Id()
request.DomainNames = removeNames
raw, err := client.WithDnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.UnbindInstanceDomains(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
if len(add) > 0 {
addNames := strings.Join(add, ",")
request := alidns.CreateBindInstanceDomainsRequest()
request.InstanceId = d.Id()
request.DomainNames = addNames
raw, err := client.WithDnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.BindInstanceDomains(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
if err := dnsService.WaitForAlidnsDomainAttachment(d.Id(), map[string]interface{}{"Domain": d.Get("domain_names").(*schema.Set).List()}, false, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
return resourceAlicloudAlidnsDomainAttachmentRead(d, meta)
}
func resourceAlicloudAlidnsdomainAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dnsService := DnsService{client}
domainNames := d.Get("domain_names").(*schema.Set).List()
deleteSli := make([]string, 0)
for _, v := range domainNames {
deleteSli = append(deleteSli, v.(string))
}
request := alidns.CreateUnbindInstanceDomainsRequest()
request.InstanceId = d.Id()
request.DomainNames = strings.Join(deleteSli, ",")
raw, err := client.WithDnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.UnbindInstanceDomains(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(dnsService.WaitForAlidnsDomainAttachment(d.Id(), nil, true, DefaultTimeout))
}
func flatten(input alidns.DescribeInstanceDomainsResponse) []string {
domainNames := make([]string, 0)
for _, v := range input.InstanceDomains {
domainNames = append(domainNames, v.DomainName)
}
return domainNames
}
package alicloud
import (
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/alidns"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudDnsGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDnsGroupCreate,
Read: resourceAlicloudDnsGroupRead,
Update: resourceAlicloudDnsGroupUpdate,
Delete: resourceAlicloudDnsGroupDelete,
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
},
}
}
func resourceAlicloudDnsGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := alidns.CreateAddDomainGroupRequest()
request.RegionId = client.RegionId
request.GroupName = d.Get("name").(string)
raw, err := client.WithDnsClient(func(dnsClient *alidns.Client) (interface{}, error) {
return dnsClient.AddDomainGroup(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_dns_group", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*alidns.AddDomainGroupResponse)
d.SetId(response.GroupId)
return resourceAlicloudDnsGroupRead(d, meta)
}
func resourceAlicloudDnsGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := alidns.CreateUpdateDomainGroupRequest()
request.RegionId = client.RegionId
request.GroupId = d.Id()
if d.HasChange("name") {
request.GroupName = d.Get("name").(string)
raw, err := client.WithDnsClient(func(dnsClient *alidns.Client) (interface{}, error) {
return dnsClient.UpdateDomainGroup(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
return resourceAlicloudDnsGroupRead(d, meta)
}
func resourceAlicloudDnsGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dnsService := &DnsService{client: client}
object, err := dnsService.DescribeDnsGroup(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", object.GroupName)
return nil
}
func resourceAlicloudDnsGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := alidns.CreateDeleteDomainGroupRequest()
request.RegionId = client.RegionId
request.GroupId = d.Id()
return resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithDnsClient(func(dnsClient *alidns.Client) (interface{}, error) {
return dnsClient.DeleteDomainGroup(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"Fobidden.NotEmptyGroup"}) {
return resource.RetryableError(WrapErrorf(err, DefaultTimeoutMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR))
}
return resource.NonRetryableError(WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR))
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
}
package alicloud
import (
"strconv"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/alidns"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudDnsRecord() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDnsRecordCreate,
Read: resourceAlicloudDnsRecordRead,
Update: resourceAlicloudDnsRecordUpdate,
Delete: resourceAlicloudDnsRecordDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"host_record": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validateRR,
},
"type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"A", "NS", "MX", "TXT", "CNAME", "SRV", "AAAA", "CAA", "REDIRECT_URL", "FORWORD_URL"}, false),
},
"value": {
Type: schema.TypeString,
Required: true,
DiffSuppressFunc: dnsValueDiffSuppressFunc,
},
"ttl": {
Type: schema.TypeInt,
Optional: true,
Default: 600,
},
"priority": {
Type: schema.TypeInt,
Optional: true,
DiffSuppressFunc: dnsPriorityDiffSuppressFunc,
},
"routing": {
Type: schema.TypeString,
Optional: true,
Default: "default",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"locked": {
Type: schema.TypeBool,
Computed: true,
},
},
}
}
func resourceAlicloudDnsRecordCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := alidns.CreateAddDomainRecordRequest()
request.RegionId = client.RegionId
request.DomainName = d.Get("name").(string)
request.RR = d.Get("host_record").(string)
request.Type = d.Get("type").(string)
request.Value = d.Get("value").(string)
request.TTL = requests.NewInteger(d.Get("ttl").(int))
if v, ok := d.GetOk("priority"); !ok && request.Type == "MX" {
return WrapError(Error("'priority': required field when 'type' is MX."))
} else if ok {
request.Priority = requests.Integer(strconv.Itoa(v.(int)))
}
if v, ok := d.GetOk("routing"); ok {
routing := v.(string)
if routing != "default" && request.Type == "FORWORD_URL" {
return WrapError(Error("The ForwordURLRecord only support default line."))
}
request.Line = routing
}
if err := resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := client.WithDnsClient(func(dnsClient *alidns.Client) (interface{}, error) {
return dnsClient.AddDomainRecord(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InternalError"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*alidns.AddDomainRecordResponse)
d.SetId(response.RecordId)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_dns_record", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return resourceAlicloudDnsRecordRead(d, meta)
}
func resourceAlicloudDnsRecordUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := alidns.CreateUpdateDomainRecordRequest()
request.RegionId = client.RegionId
request.RecordId = d.Id()
request.RR = d.Get("host_record").(string)
request.Type = d.Get("type").(string)
if request.Type == "MX" {
request.Priority = requests.NewInteger(d.Get("priority").(int))
}
request.TTL = requests.NewInteger(d.Get("ttl").(int))
request.Line = d.Get("routing").(string)
request.Value = d.Get("value").(string)
raw, err := client.WithDnsClient(func(dnsClient *alidns.Client) (interface{}, error) {
return dnsClient.UpdateDomainRecord(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return resourceAlicloudDnsRecordRead(d, meta)
}
func resourceAlicloudDnsRecordRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dnsService := &DnsService{client: client}
object, err := dnsService.DescribeDnsRecord(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("ttl", object.TTL)
d.Set("priority", object.Priority)
d.Set("name", object.DomainName)
d.Set("host_record", object.RR)
d.Set("type", object.Type)
d.Set("value", object.Value)
d.Set("routing", object.Line)
d.Set("status", object.Status)
d.Set("locked", object.Locked)
return nil
}
func resourceAlicloudDnsRecordDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dnsService := &DnsService{client: client}
request := alidns.CreateDeleteDomainRecordRequest()
request.RegionId = client.RegionId
request.RecordId = d.Id()
return resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithDnsClient(func(dnsClient *alidns.Client) (interface{}, error) {
return dnsClient.DeleteDomainRecord(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"DomainRecordNotBelongToUser"}) {
return nil
}
if IsExpectedErrors(err, []string{"RecordForbidden.DNSChange", "InternalError"}) {
return resource.RetryableError(WrapErrorf(err, DefaultTimeoutMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR))
}
return resource.NonRetryableError(WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR))
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
_, err = dnsService.DescribeDnsRecord(d.Id())
if err != nil {
if NotFoundError(err) {
return nil
}
return resource.NonRetryableError(WrapError(err))
}
return resource.RetryableError(WrapErrorf(err, DefaultTimeoutMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR))
})
}
package alicloud
import (
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/drds"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudDRDSInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAliCloudDRDSInstanceCreate,
Read: resourceAliCloudDRDSInstanceRead,
Update: resourceAliCloudDRDSInstanceUpdate,
Delete: resourceAliCloudDRDSInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(5 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(1, 129),
},
"zone_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"specification": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_charge_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{string(PostPaid), string(PrePaid)}, false),
ForceNew: true,
Default: PostPaid,
},
"vswitch_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_series": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"drds.sn1.4c8g", "drds.sn1.8c16g", "drds.sn1.16c32g", "drds.sn1.32c64g", "drds.sn2.4c16g", "drds.sn2.8c32g", "drds.sn2.16c64g"}, false),
ForceNew: true,
},
},
}
}
func resourceAliCloudDRDSInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
drdsService := DrdsService{client}
request := drds.CreateCreateDrdsInstanceRequest()
request.RegionId = client.RegionId
request.Description = d.Get("description").(string)
request.Type = "1"
request.ZoneId = d.Get("zone_id").(string)
request.Specification = d.Get("specification").(string)
request.PayType = d.Get("instance_charge_type").(string)
request.VswitchId = d.Get("vswitch_id").(string)
request.InstanceSeries = d.Get("instance_series").(string)
request.Quantity = "1"
if request.VswitchId != "" {
vpcService := VpcService{client}
vsw, err := vpcService.DescribeVSwitch(request.VswitchId)
if err != nil {
return WrapError(err)
}
request.VpcId = vsw.VpcId
}
request.ClientToken = buildClientToken(request.GetActionName())
if request.PayType == string(PostPaid) {
request.PayType = "drdsPost"
}
if request.PayType == string(PrePaid) {
request.PayType = "drdsPre"
}
raw, err := client.WithDrdsClient(func(drdsClient *drds.Client) (interface{}, error) {
return drdsClient.CreateDrdsInstance(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_drds_instance", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*drds.CreateDrdsInstanceResponse)
idList := response.Data.DrdsInstanceIdList.DrdsInstanceIdList
if len(idList) != 1 {
return WrapError(Error("failed to get DRDS instance id and response. DrdsInstanceIdList is %#v", idList))
}
d.SetId(idList[0])
// wait instance status change from DO_CREATE to RUN
stateConf := BuildStateConf([]string{"1"}, []string{"0"}, d.Timeout(schema.TimeoutCreate), 1*time.Minute, drdsService.DrdsInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAliCloudDRDSInstanceUpdate(d, meta)
}
func resourceAliCloudDRDSInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
drdsService := DrdsService{client}
configItem := make(map[string]string)
if d.HasChange("description") {
request := drds.CreateModifyDrdsInstanceDescriptionRequest()
request.DrdsInstanceId = d.Id()
request.Description = d.Get("description").(string)
configItem["description"] = request.Description
client := meta.(*connectivity.AliyunClient)
request.RegionId = client.RegionId
raw, err := client.WithDrdsClient(func(drdsClient *drds.Client) (interface{}, error) {
return drdsClient.ModifyDrdsInstanceDescription(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
//wait for update effected and instance status returning to run
if err := drdsService.WaitDrdsInstanceConfigEffect(
d.Id(), configItem, d.Timeout(schema.TimeoutUpdate)); err != nil {
return WrapError(err)
}
stateConf := BuildStateConf([]string{}, []string{"0"}, d.Timeout(schema.TimeoutUpdate), 3*time.Second, drdsService.DrdsInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAliCloudDRDSInstanceRead(d, meta)
}
func resourceAliCloudDRDSInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
drdsService := DrdsService{client}
object, err := drdsService.DescribeDrdsInstance(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
data := object.Data
//other attribute not set,because these attribute from `data` can't get
d.Set("zone_id", data.ZoneId)
d.Set("description", data.Description)
return nil
}
func resourceAliCloudDRDSInstanceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
drdsService := DrdsService{client}
request := drds.CreateRemoveDrdsInstanceRequest()
request.RegionId = client.RegionId
request.DrdsInstanceId = d.Id()
raw, err := client.WithDrdsClient(func(drdsClient *drds.Client) (interface{}, error) {
return drdsClient.RemoveDrdsInstance(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDrdsInstanceId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*drds.RemoveDrdsInstanceResponse)
if !response.Success {
return WrapError(Error("failed to delete instance timeout "+"and got an error: %#v", err))
}
//0 -> RUN, 1->DO_CREATE, 2->EXCEPTION, 3->EXPIRE, 4->DO_RELEASE, 5->RELEASE, 6->UPGRADE, 7->DOWNGRADE, 10->VersionUpgrade, 11->VersionRollback, 14->RESTART
stateConf := BuildStateConf([]string{"0", "1", "2", "3", "4", "5", "6", "7", "10", "11", "14"}, []string{}, d.Timeout(schema.TimeoutDelete), 3*time.Second, drdsService.DrdsInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err = stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudDtsConsumerChannel() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDtsConsumerChannelCreate,
Read: resourceAlicloudDtsConsumerChannelRead,
Update: resourceAlicloudDtsConsumerChannelUpdate,
Delete: resourceAlicloudDtsConsumerChannelDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"consumer_group_id": {
Type: schema.TypeString,
Computed: true,
},
"consumer_group_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(1, 128),
},
"consumer_group_password": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(8, 32),
},
"consumer_group_user_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile("^[a-zA-Z0-9_]{1,16}$"), "The length of the name is limited to `1` to `16` characters. It can contain uppercase and lowercase letters, numbers, underscores (_)"),
},
"dts_instance_id": {
Type: schema.TypeString,
Required: true,
},
},
}
}
func resourceAlicloudDtsConsumerChannelCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateConsumerChannel"
request := make(map[string]interface{})
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
request["ConsumerGroupName"] = d.Get("consumer_group_name")
request["ConsumerGroupPassword"] = d.Get("consumer_group_password")
request["ConsumerGroupUserName"] = d.Get("consumer_group_user_name")
request["DtsInstanceId"] = d.Get("dts_instance_id")
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"OperationDenied.JobStatus"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_dts_consumer_channel", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["DtsInstanceId"], ":", response["ConsumerGroupID"]))
return resourceAlicloudDtsConsumerChannelRead(d, meta)
}
func resourceAlicloudDtsConsumerChannelRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dtsService := DtsService{client}
object, err := dtsService.DescribeDtsConsumerChannel(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_dts_consumer_channel dtsService.DescribeDtsConsumerChannel Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("consumer_group_id", parts[1])
d.Set("dts_instance_id", parts[0])
d.Set("consumer_group_name", object["ConsumerGroupName"])
d.Set("consumer_group_user_name", object["ConsumerGroupUserName"])
return nil
}
func resourceAlicloudDtsConsumerChannelUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"ConsumerGroupId": parts[1],
"DtsInstanceId": parts[0],
}
request["RegionId"] = client.RegionId
if d.HasChange("consumer_group_password") {
update = true
request["ConsumerGroupPassword"] = d.Get("consumer_group_password")
}
if update {
action := "ModifyConsumerChannel"
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"OperationDenied.JobStatus"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudDtsConsumerChannelRead(d, meta)
}
func resourceAlicloudDtsConsumerChannelDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteConsumerChannel"
var response map[string]interface{}
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ConsumerGroupId": parts[1],
"DtsInstanceId": parts[0],
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"OperationDenied.JobStatus"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
time.Sleep(10 * time.Second)
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudDtsJobMonitorRule() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDtsJobMonitorRuleCreate,
Read: resourceAlicloudDtsJobMonitorRuleRead,
Update: resourceAlicloudDtsJobMonitorRuleUpdate,
Delete: resourceAlicloudDtsJobMonitorRuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"delay_rule_time": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"dts_job_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"phone": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"state": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Y", "N"}, false),
},
"type": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"delay", "error"}, false),
},
},
}
}
func resourceAlicloudDtsJobMonitorRuleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateJobMonitorRule"
request := make(map[string]interface{})
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("delay_rule_time"); ok {
request["DelayRuleTime"] = v
}
request["DtsJobId"] = d.Get("dts_job_id")
if v, ok := d.GetOk("phone"); ok {
request["Phone"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("state"); ok {
request["State"] = v
}
if v, ok := d.GetOk("type"); ok {
request["Type"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_dts_job_monitor_rule", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetId(fmt.Sprint(request["DtsJobId"]))
return resourceAlicloudDtsJobMonitorRuleRead(d, meta)
}
func resourceAlicloudDtsJobMonitorRuleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dtsService := DtsService{client}
object, err := dtsService.DescribeDtsJobMonitorRule(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_dts_job_monitor_rule dtsService.DescribeDtsJobMonitorRule Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("dts_job_id", d.Id())
if v := object["MonitorRules"].([]interface{}); len(v) > 0 {
d.Set("delay_rule_time", v[0].(map[string]interface{})["DelayRuleTime"])
d.Set("phone", v[0].(map[string]interface{})["Phone"])
d.Set("state", v[0].(map[string]interface{})["State"])
d.Set("type", v[0].(map[string]interface{})["Type"])
}
return nil
}
func resourceAlicloudDtsJobMonitorRuleUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"DtsJobId": d.Id(),
}
if d.HasChange("delay_rule_time") {
update = true
if v, ok := d.GetOk("delay_rule_time"); ok {
request["DelayRuleTime"] = v
}
}
if d.HasChange("phone") {
update = true
if v, ok := d.GetOk("phone"); ok {
request["Phone"] = v
}
}
request["RegionId"] = client.RegionId
if d.HasChange("state") {
update = true
if v, ok := d.GetOk("state"); ok {
request["State"] = v
}
}
if v, ok := d.GetOk("type"); ok {
request["Type"] = v
}
if update {
action := "CreateJobMonitorRule"
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
}
return resourceAlicloudDtsJobMonitorRuleRead(d, meta)
}
func resourceAlicloudDtsJobMonitorRuleDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudDtsJobMonitorRule. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
package alicloud
import (
"encoding/json"
"fmt"
"log"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudDtsSubscriptionJob() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDtsSubscriptionJobCreate,
Read: resourceAlicloudDtsSubscriptionJobRead,
Update: resourceAlicloudDtsSubscriptionJobUpdate,
Delete: resourceAlicloudDtsSubscriptionJobDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Update: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"checkpoint": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"compute_unit": {
Type: schema.TypeInt,
Optional: true,
},
"database_count": {
Type: schema.TypeInt,
Optional: true,
},
"db_list": {
Type: schema.TypeString,
Optional: true,
},
"delay_notice": {
Type: schema.TypeBool,
Optional: true,
},
"delay_phone": {
Type: schema.TypeString,
Optional: true,
},
"delay_rule_time": {
Type: schema.TypeString,
Optional: true,
},
"destination_endpoint_engine_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"ADS", "DB2", "DRDS", "DataHub", "Greenplum", "MSSQL", "MySQL", "PolarDB", "PostgreSQL", "Redis", "Tablestore", "as400", "clickhouse", "kafka", "mongodb", "odps", "oracle", "polardb_o", "polardb_pg", "tidb"}, false),
},
"destination_region": {
Type: schema.TypeString,
Optional: true,
},
"dts_instance_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"dts_job_name": {
Type: schema.TypeString,
Optional: true,
},
"error_notice": {
Type: schema.TypeBool,
Optional: true,
},
"error_phone": {
Type: schema.TypeString,
Optional: true,
},
"instance_class": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"large", "medium", "micro", "small", "xlarge", "xxlarge"}, false),
},
"payment_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo", "Subscription"}, false),
},
"payment_duration_unit": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Month", "Year"}, false),
},
"payment_duration": {
Type: schema.TypeInt,
Optional: true,
},
"reserve": {
Type: schema.TypeString,
Optional: true,
},
"source_endpoint_database_name": {
Type: schema.TypeString,
Optional: true,
},
"source_endpoint_engine_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"MySQL", "Oracle"}, false),
},
"source_endpoint_ip": {
Type: schema.TypeString,
Optional: true,
},
"source_endpoint_instance_id": {
Type: schema.TypeString,
Optional: true,
},
"source_endpoint_instance_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"CEN", "DRDS", "ECS", "Express", "LocalInstance", "PolarDB", "RDS", "dg"}, false),
},
"source_endpoint_oracle_sid": {
Type: schema.TypeString,
Optional: true,
},
"source_endpoint_owner_id": {
Type: schema.TypeString,
Optional: true,
},
"source_endpoint_password": {
Type: schema.TypeString,
Optional: true,
},
"source_endpoint_port": {
Type: schema.TypeString,
Optional: true,
},
"source_endpoint_region": {
Type: schema.TypeString,
Optional: true,
},
"source_endpoint_role": {
Type: schema.TypeString,
Optional: true,
},
"source_endpoint_user_name": {
Type: schema.TypeString,
Optional: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Abnormal", "Downgrade", "Locked", "Normal", "NotStarted", "NotStarted", "PreCheckPass", "PrecheckFailed", "Prechecking", "Retrying", "Starting", "Upgrade"}, false),
},
"subscription_data_type_ddl": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"subscription_data_type_dml": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"subscription_instance_network_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"classic", "vpc"}, false),
},
"subscription_instance_vpc_id": {
Type: schema.TypeString,
Optional: true,
},
"subscription_instance_vswitch_id": {
Type: schema.TypeString,
Optional: true,
},
"sync_architecture": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"bidirectional", "oneway"}, false),
},
"synchronization_direction": {
Type: schema.TypeString,
Optional: true,
},
"tags": tagsSchema(),
},
}
}
func resourceAlicloudDtsSubscriptionJobCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateDtsInstance"
request := make(map[string]interface{})
request["AutoPay"] = false
request["AutoStart"] = true
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("compute_unit"); ok {
request["ComputeUnit"] = v
}
if v, ok := d.GetOk("database_count"); ok {
request["DatabaseCount"] = v
}
if v, ok := d.GetOk("destination_endpoint_engine_name"); ok {
request["DestinationEndpointEngineName"] = v
}
if v, ok := d.GetOk("destination_region"); ok {
request["DestinationRegion"] = v
}
if v, ok := d.GetOk("instance_class"); ok {
request["InstanceClass"] = v
}
if v, ok := d.GetOk("payment_type"); ok {
request["PayType"] = convertDtsPaymentTypeRequest(v.(string))
}
if v, ok := d.GetOk("payment_duration_unit"); ok {
request["Period"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("source_endpoint_engine_name"); ok {
request["SourceEndpointEngineName"] = v
}
if v, ok := d.GetOk("source_endpoint_region"); ok {
request["SourceRegion"] = v
}
if v, ok := d.GetOk("sync_architecture"); ok {
request["SyncArchitecture"] = v
}
request["Type"] = "SUBSCRIBE"
if v, ok := d.GetOk("payment_duration"); ok {
request["UsedTime"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_dts_subscription_job", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["JobId"]))
d.Set("dts_instance_id", response["InstanceId"])
return resourceAlicloudDtsSubscriptionJobUpdate(d, meta)
}
func resourceAlicloudDtsSubscriptionJobRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dtsService := DtsService{client}
object, err := dtsService.DescribeDtsSubscriptionJob(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_dts_subscription_job dtsService.DescribeDtsSubscriptionJob Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("checkpoint", fmt.Sprint(formatInt(object["Checkpoint"])))
d.Set("db_list", object["DbObject"])
d.Set("dts_instance_id", object["DtsInstanceID"])
d.Set("dts_job_name", object["DtsJobName"])
d.Set("payment_type", convertDtsPaymentTypeResponse(object["PayType"]))
d.Set("source_endpoint_database_name", object["SourceEndpoint"].(map[string]interface{})["DatabaseName"])
d.Set("source_endpoint_engine_name", object["SourceEndpoint"].(map[string]interface{})["EngineName"])
d.Set("source_endpoint_ip", object["SourceEndpoint"].(map[string]interface{})["Ip"])
d.Set("source_endpoint_instance_id", object["SourceEndpoint"].(map[string]interface{})["InstanceID"])
d.Set("source_endpoint_instance_type", object["SourceEndpoint"].(map[string]interface{})["InstanceType"])
d.Set("source_endpoint_oracle_sid", object["SourceEndpoint"].(map[string]interface{})["OracleSID"])
d.Set("source_endpoint_owner_id", object["SourceEndpoint"].(map[string]interface{})["AliyunUid"])
d.Set("source_endpoint_port", object["SourceEndpoint"].(map[string]interface{})["Port"])
d.Set("source_endpoint_region", object["SourceEndpoint"].(map[string]interface{})["Region"])
d.Set("source_endpoint_role", object["SourceEndpoint"].(map[string]interface{})["RoleName"])
d.Set("source_endpoint_user_name", object["SourceEndpoint"].(map[string]interface{})["UserName"])
d.Set("status", object["Status"])
d.Set("subscription_data_type_ddl", object["SubscriptionDataType"].(map[string]interface{})["Ddl"])
d.Set("subscription_data_type_dml", object["SubscriptionDataType"].(map[string]interface{})["Dml"])
var jsonData map[string]interface{}
json.Unmarshal([]byte(object["Reserved"].(string)), &jsonData)
if jsonData["netType"] != nil {
d.Set("subscription_instance_network_type", strings.ToLower(jsonData["netType"].(string)))
}
d.Set("subscription_instance_vpc_id", jsonData["vpcId"])
d.Set("subscription_instance_vswitch_id", jsonData["vswitchId"])
listTagResourcesObject, err := dtsService.ListTagResources(object["DtsInstanceID"].(string), "ALIYUN::DTS::INSTANCE")
if err != nil {
return WrapError(err)
}
d.Set("tags", tagsToMap(listTagResourcesObject))
return nil
}
func resourceAlicloudDtsSubscriptionJobUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dtsService := DtsService{client}
var response map[string]interface{}
d.Partial(true)
if d.HasChange("tags") {
if err := dtsService.SetResourceTags(d, "ALIYUN::DTS::INSTANCE"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
update := false
request := map[string]interface{}{
"DtsJobId": d.Id(),
}
if d.HasChange("dts_job_name") {
update = true
if v, ok := d.GetOk("dts_job_name"); ok {
request["DtsJobName"] = v
}
}
request["RegionId"] = client.RegionId
if update {
action := "ModifyDtsJobName"
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetPartial("dts_job_name")
}
update = false
modifyDtsJobPasswordReq := map[string]interface{}{
"DtsJobId": d.Id(),
}
modifyDtsJobPasswordReq["Endpoint"] = "src"
modifyDtsJobPasswordReq["RegionId"] = client.RegionId
if !d.IsNewResource() && d.HasChange("source_endpoint_password") {
update = true
if v, ok := d.GetOk("source_endpoint_password"); ok {
modifyDtsJobPasswordReq["Password"] = v
}
if v, ok := d.GetOk("source_endpoint_user_name"); ok {
modifyDtsJobPasswordReq["UserName"] = v
}
}
if update {
action := "ModifyDtsJobPassword"
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, modifyDtsJobPasswordReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyDtsJobPasswordReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetPartial("source_endpoint_password")
d.SetPartial("source_endpoint_user_name")
target := d.Get("status").(string)
err = resourceAlicloudDtsSubscriptionJobStatusFlow(d, meta, target)
if err != nil {
return WrapError(Error(FailedToReachTargetStatus, d.Get("status")))
}
}
if !d.IsNewResource() && d.HasChange("status") {
target := d.Get("status").(string)
err := resourceAlicloudDtsSubscriptionJobStatusFlow(d, meta, target)
if err != nil {
return WrapError(Error(FailedToReachTargetStatus, d.Get("status")))
}
}
update = false
if d.IsNewResource() {
update = true
}
configureSubscriptionReq := map[string]interface{}{
"DtsJobId": d.Id(),
}
if d.HasChange("db_list") {
update = true
}
if v, ok := d.GetOk("db_list"); ok {
configureSubscriptionReq["DbList"] = v
}
if v, ok := d.GetOk("dts_job_name"); ok {
configureSubscriptionReq["DtsJobName"] = v
}
configureSubscriptionReq["RegionId"] = client.RegionId
if d.HasChange("subscription_instance_network_type") {
update = true
}
if v, ok := d.GetOk("subscription_instance_network_type"); ok {
configureSubscriptionReq["SubscriptionInstanceNetworkType"] = v
}
if d.HasChange("checkpoint") {
update = true
}
if v, ok := d.GetOk("checkpoint"); ok {
configureSubscriptionReq["Checkpoint"] = v
}
if d.HasChange("source_endpoint_database_name") {
update = true
}
if v, ok := d.GetOk("source_endpoint_database_name"); ok {
configureSubscriptionReq["SourceEndpointDatabaseName"] = v
}
if !d.IsNewResource() && d.HasChange("source_endpoint_engine_name") {
update = true
}
if v, ok := d.GetOk("source_endpoint_engine_name"); ok {
configureSubscriptionReq["SourceEndpointEngineName"] = v
}
if d.HasChange("source_endpoint_ip") {
update = true
}
if v, ok := d.GetOk("source_endpoint_ip"); ok {
configureSubscriptionReq["SourceEndpointIP"] = v
}
if d.HasChange("source_endpoint_instance_id") {
update = true
}
if v, ok := d.GetOk("source_endpoint_instance_id"); ok {
configureSubscriptionReq["SourceEndpointInstanceID"] = v
}
if d.HasChange("source_endpoint_instance_type") {
update = true
}
if v, ok := d.GetOk("source_endpoint_instance_type"); ok {
configureSubscriptionReq["SourceEndpointInstanceType"] = v
}
if d.HasChange("source_endpoint_oracle_sid") {
update = true
}
if v, ok := d.GetOk("source_endpoint_oracle_sid"); ok {
configureSubscriptionReq["SourceEndpointOracleSID"] = v
}
if d.HasChange("source_endpoint_owner_id") {
update = true
}
if v, ok := d.GetOk("source_endpoint_owner_id"); ok {
configureSubscriptionReq["SourceEndpointOwnerID"] = v
}
if v, ok := d.GetOk("source_endpoint_password"); ok {
configureSubscriptionReq["SourceEndpointPassword"] = v
}
if d.HasChange("source_endpoint_port") {
update = true
}
if v, ok := d.GetOk("source_endpoint_port"); ok {
configureSubscriptionReq["SourceEndpointPort"] = v
}
if d.HasChange("source_endpoint_region") {
update = true
}
if v, ok := d.GetOk("source_endpoint_region"); ok {
configureSubscriptionReq["SourceEndpointRegion"] = v
}
if d.HasChange("source_endpoint_role") {
update = true
}
if v, ok := d.GetOk("source_endpoint_role"); ok {
configureSubscriptionReq["SourceEndpointRole"] = v
}
if v, ok := d.GetOk("source_endpoint_user_name"); ok {
configureSubscriptionReq["SourceEndpointUserName"] = v
}
if d.HasChange("subscription_data_type_ddl") || d.IsNewResource() {
update = true
}
if v, ok := d.GetOkExists("subscription_data_type_ddl"); ok {
configureSubscriptionReq["SubscriptionDataTypeDDL"] = v
}
if d.HasChange("subscription_data_type_dml") || d.IsNewResource() {
update = true
}
if v, ok := d.GetOkExists("subscription_data_type_dml"); ok {
configureSubscriptionReq["SubscriptionDataTypeDML"] = v
}
if d.HasChange("subscription_instance_vpc_id") {
update = true
}
if v, ok := d.GetOk("subscription_instance_vpc_id"); ok {
configureSubscriptionReq["SubscriptionInstanceVPCId"] = v
}
if d.HasChange("subscription_instance_vswitch_id") {
update = true
}
if v, ok := d.GetOk("subscription_instance_vswitch_id"); ok {
configureSubscriptionReq["SubscriptionInstanceVSwitchId"] = v
}
if update {
if v, ok := d.GetOkExists("delay_notice"); ok {
configureSubscriptionReq["DelayNotice"] = v
}
if v, ok := d.GetOk("delay_phone"); ok {
configureSubscriptionReq["DelayPhone"] = v
}
if v, ok := d.GetOk("delay_rule_time"); ok {
configureSubscriptionReq["DelayRuleTime"] = v
}
if v, ok := d.GetOkExists("error_notice"); ok {
configureSubscriptionReq["ErrorNotice"] = v
}
if v, ok := d.GetOk("error_phone"); ok {
configureSubscriptionReq["ErrorPhone"] = v
}
if v, ok := d.GetOk("reserve"); ok {
configureSubscriptionReq["Reserve"] = v
}
action := "ConfigureSubscription"
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, configureSubscriptionReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, configureSubscriptionReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("db_list")
d.SetPartial("dts_job_name")
d.SetPartial("subscription_instance_network_type")
d.SetPartial("checkpoint")
d.SetPartial("source_endpoint_database_name")
d.SetPartial("source_endpoint_engine_name")
d.SetPartial("source_endpoint_ip")
d.SetPartial("source_endpoint_instance_id")
d.SetPartial("source_endpoint_instance_type")
d.SetPartial("source_endpoint_oracle_sid")
d.SetPartial("source_endpoint_owner_id")
d.SetPartial("source_endpoint_password")
d.SetPartial("source_endpoint_port")
d.SetPartial("source_endpoint_region")
d.SetPartial("source_endpoint_role")
d.SetPartial("source_endpoint_user_name")
d.SetPartial("subscription_data_type_ddl")
d.SetPartial("subscription_data_type_dml")
d.SetPartial("subscription_instance_vpc_id")
d.SetPartial("subscription_instance_vswitch_id")
target := d.Get("status").(string)
err = resourceAlicloudDtsSubscriptionJobStatusFlow(d, meta, target)
if err != nil {
return WrapError(Error(FailedToReachTargetStatus, d.Get("status")))
}
}
d.Partial(false)
return resourceAlicloudDtsSubscriptionJobRead(d, meta)
}
func resourceAlicloudDtsSubscriptionJobDelete(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("payment_type"); ok {
if v.(string) == "Subscription" {
return nil
}
}
client := meta.(*connectivity.AliyunClient)
action := "DeleteDtsJob"
var response map[string]interface{}
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DtsJobId": d.Id(),
}
if v, ok := d.GetOk("dts_instance_id"); ok {
request["DtsInstanceId"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("synchronization_direction"); ok {
request["SynchronizationDirection"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func resourceAlicloudDtsSubscriptionJobStatusFlow(d *schema.ResourceData, meta interface{}, target string) error {
client := meta.(*connectivity.AliyunClient)
dtsService := DtsService{client}
var response map[string]interface{}
object, err := dtsService.DescribeDtsSubscriptionJob(d.Id())
if err != nil {
return WrapError(err)
}
if object["Status"].(string) != target {
if target == "NotConfigured" {
request := map[string]interface{}{
"DtsJobId": d.Id(),
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("synchronization_direction"); ok {
request["SynchronizationDirection"] = v
}
action := "ResetDtsJob"
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"NotConfigured"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, dtsService.DtsSubscriptionJobStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if target == "Normal" || (target == "Abnormal" && object["Status"].(string) == "NotStarted") {
request := map[string]interface{}{
"DtsJobId": d.Id(),
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("synchronization_direction"); ok {
request["SynchronizationDirection"] = v
}
action := "StartDtsJob"
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Starting", "Normal"}, d.Timeout(schema.TimeoutUpdate), 30*time.Second, dtsService.DtsSubscriptionJobStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if target == "Abnormal" {
request := map[string]interface{}{
"DtsJobId": d.Id(),
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("synchronization_direction"); ok {
request["SynchronizationDirection"] = v
}
action := "SuspendDtsJob"
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Abnormal"}, d.Timeout(schema.TimeoutUpdate), 30*time.Second, dtsService.DtsSubscriptionJobStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.SetPartial("status")
}
return nil
}
func convertDtsPaymentTypeResponse(source interface{}) interface{} {
switch source {
case "PostPaid":
return "PayAsYouGo"
case "PrePaid":
return "Subscription"
}
return source
}
func convertDtsPaymentTypeRequest(source interface{}) interface{} {
switch source {
case "PayAsYouGo":
return "PostPaid"
case "Subscription":
return "PrePaid"
}
return source
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudDtsSynchronizationInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDtsSynchronizationInstanceCreate,
Read: resourceAlicloudDtsSynchronizationInstanceRead,
Update: resourceAlicloudDtsSynchronizationInstanceUpdate,
Delete: resourceAlicloudDtsSynchronizationInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"compute_unit": {
Type: schema.TypeInt,
Optional: true,
},
"database_count": {
Type: schema.TypeInt,
Optional: true,
},
"quantity": {
Type: schema.TypeInt,
Optional: true,
},
"sync_architecture": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"bidirectional", "oneway"}, false),
},
"destination_endpoint_engine_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"MySQL", "PolarDB", "polardb_o", "polardb_pg", "Redis", "DRDS", "PostgreSQL", "odps", "oracle", "mongodb", "tidb", "ADS", "ADB30", "Greenplum", "MSSQL", "kafka", "DataHub", "clickhouse", "DB2", "as400", "Tablestore"}, false),
},
"destination_endpoint_region": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"source_endpoint_engine_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"MySQL", "PolarDB", "polardb_o", "polardb_pg", "Redis", "DRDS", "PostgreSQL", "odps", "oracle", "mongodb", "tidb", "ADS", "ADB30", "Greenplum", "MSSQL", "kafka", "DataHub", "clickhouse", "DB2", "as400", "Tablestore"}, false),
},
"source_endpoint_region": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_class": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"xxlarge", "xlarge", "large", "medium", "small", "micro"}, false),
},
"payment_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo", "Subscription"}, false),
},
"payment_duration_unit": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Month", "Year"}, false),
},
"payment_duration": {
Type: schema.TypeInt,
Optional: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudDtsSynchronizationInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateDtsInstance"
request := make(map[string]interface{})
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
request["AutoPay"] = false
request["AutoStart"] = true
request["InstanceClass"] = "small"
if v, ok := d.GetOk("instance_class"); ok {
request["InstanceClass"] = v
}
if v, ok := d.GetOk("compute_unit"); ok {
request["ComputeUnit"] = v
}
if v, ok := d.GetOk("database_count"); ok {
request["DatabaseCount"] = v
}
if v, ok := d.GetOk("destination_endpoint_engine_name"); ok {
request["DestinationEndpointEngineName"] = v
}
if v, ok := d.GetOk("destination_endpoint_region"); ok {
request["DestinationRegion"] = v
}
if v, ok := d.GetOk("payment_type"); ok {
request["PayType"] = convertDtsSyncPaymentTypeRequest(v.(string))
}
if v, ok := d.GetOk("payment_duration_unit"); ok {
request["Period"] = v
}
if v, ok := d.GetOk("quantity"); ok {
request["Quantity"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("source_endpoint_engine_name"); ok {
request["SourceEndpointEngineName"] = v
}
if v, ok := d.GetOk("source_endpoint_region"); ok {
request["SourceRegion"] = v
}
if v, ok := d.GetOk("sync_architecture"); ok {
request["SyncArchitecture"] = v
}
request["Type"] = "SYNC"
if v, ok := d.GetOk("payment_duration"); ok {
request["UsedTime"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_dts_synchronization_instance", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["InstanceId"]))
return resourceAlicloudDtsSynchronizationInstanceRead(d, meta)
}
func resourceAlicloudDtsSynchronizationInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dtsService := DtsService{client}
object, err := dtsService.DescribeDtsSynchronizationInstance(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_dts_synchronization_instance dtsService.DescribeDtsSynchronizationInstance Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_class", object["DtsJobClass"])
d.Set("payment_type", convertDtsSyncPaymentTypeResponse(object["PayType"]))
if v, ok := object["SourceEndpoint"].(map[string]interface{}); ok {
d.Set("source_endpoint_engine_name", v["EngineName"])
d.Set("source_endpoint_region", v["Region"])
}
if v, ok := object["DestinationEndpoint"].(map[string]interface{}); ok {
d.Set("destination_endpoint_engine_name", v["EngineName"])
d.Set("destination_endpoint_region", v["Region"])
}
return nil
}
func resourceAlicloudDtsSynchronizationInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return resourceAlicloudDtsSynchronizationInstanceRead(d, meta)
}
func resourceAlicloudDtsSynchronizationInstanceDelete(d *schema.ResourceData, meta interface{}) error {
if v, ok := d.GetOk("payment_type"); ok {
if v.(string) == "Subscription" {
log.Printf("[WARN] Cannot destroy resource: alicloud_dts_synchronization_job because it's s. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
}
client := meta.(*connectivity.AliyunClient)
action := "DeleteSynchronizationJob"
var response map[string]interface{}
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"SynchronizationJobId": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidJobId"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func convertDtsSyncPaymentTypeResponse(source interface{}) interface{} {
switch source {
case "PostPaid":
return "PayAsYouGo"
case "PrePaid":
return "Subscription"
}
return source
}
func convertDtsSyncPaymentTypeRequest(source interface{}) interface{} {
switch source {
case "PayAsYouGo":
return "PostPaid"
case "Subscription":
return "PrePaid"
}
return source
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudDtsSynchronizationJob() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDtsSynchronizationJobCreate,
Read: resourceAlicloudDtsSynchronizationJobRead,
Update: resourceAlicloudDtsSynchronizationJobUpdate,
Delete: resourceAlicloudDtsSynchronizationJobDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Update: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"dts_instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"dts_job_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"checkpoint": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"instance_class": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"xxlarge", "xlarge", "large", "medium", "small"}, false),
},
"data_initialization": {
Type: schema.TypeBool,
Required: true,
ForceNew: true,
},
"data_synchronization": {
Type: schema.TypeBool,
Required: true,
ForceNew: true,
},
"structure_initialization": {
Type: schema.TypeBool,
Required: true,
ForceNew: true,
},
"synchronization_direction": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Forward", "Reverse"}, false),
},
"db_list": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"reserve": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"source_endpoint_instance_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"CEN", "DG", "DISTRIBUTED_DMSLOGICDB", "ECS", "EXPRESS", "MONGODB", "OTHER", "PolarDB", "POLARDBX20", "RDS"}, false),
},
"source_endpoint_engine_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"AS400", "DB2", "DMSPOLARDB", "HBASE", "MONGODB", "MSSQL", "MySQL", "ORACLE", "PolarDB", "POLARDBX20", "POLARDB_O", "POSTGRESQL", "TERADATA"}, false),
},
"source_endpoint_instance_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"source_endpoint_region": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"source_endpoint_ip": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"source_endpoint_port": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"source_endpoint_oracle_sid": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"source_endpoint_database_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"source_endpoint_user_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"source_endpoint_password": {
Type: schema.TypeString,
Optional: true,
},
"source_endpoint_owner_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"source_endpoint_role": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"destination_endpoint_instance_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ads", "CEN", "DATAHUB", "DG", "ECS", "EXPRESS", "GREENPLUM", "MONGODB", "OTHER", "PolarDB", "POLARDBX20", "RDS"}, false),
},
"destination_endpoint_engine_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ADB20", "ADB30", "AS400", "DATAHUB", "DB2", "GREENPLUM", "KAFKA", "MONGODB", "MSSQL", "MySQL", "ORACLE", "PolarDB", "POLARDBX20", "POLARDB_O", "PostgreSQL"}, false),
},
"destination_endpoint_instance_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"destination_endpoint_region": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"destination_endpoint_ip": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"destination_endpoint_port": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"destination_endpoint_database_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"destination_endpoint_user_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"destination_endpoint_password": {
Type: schema.TypeString,
Optional: true,
},
"destination_endpoint_oracle_sid": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"delay_notice": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"delay_phone": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"delay_rule_time": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"error_notice": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"error_phone": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Synchronizing", "Suspending"}, false),
},
},
}
}
func resourceAlicloudDtsSynchronizationJobCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "ConfigureDtsJob"
request := make(map[string]interface{})
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("dts_instance_id"); ok {
request["DtsInstanceId"] = v
}
request["DtsJobName"] = d.Get("dts_job_name")
if v, ok := d.GetOk("checkpoint"); ok {
request["Checkpoint"] = v
}
request["DataInitialization"] = d.Get("data_initialization")
request["DataSynchronization"] = d.Get("data_synchronization")
request["StructureInitialization"] = d.Get("structure_initialization")
request["SynchronizationDirection"] = d.Get("synchronization_direction")
request["DbList"] = d.Get("db_list")
if v, ok := d.GetOkExists("delay_notice"); ok {
request["DelayNotice"] = v
}
if v, ok := d.GetOk("delay_phone"); ok {
request["DelayPhone"] = v
}
if v, ok := d.GetOk("delay_rule_time"); ok {
request["DelayRuleTime"] = v
}
if v, ok := d.GetOk("destination_endpoint_database_name"); ok {
request["DestinationEndpointDataBaseName"] = v
}
if v, ok := d.GetOk("destination_endpoint_engine_name"); ok {
request["DestinationEndpointEngineName"] = v
}
if v, ok := d.GetOk("destination_endpoint_ip"); ok {
request["DestinationEndpointIP"] = v
}
if v, ok := d.GetOk("destination_endpoint_instance_id"); ok {
request["DestinationEndpointInstanceID"] = v
}
request["DestinationEndpointInstanceType"] = d.Get("destination_endpoint_instance_type")
if v, ok := d.GetOk("destination_endpoint_oracle_sid"); ok {
request["DestinationEndpointOracleSID"] = v
}
if v, ok := d.GetOk("destination_endpoint_password"); ok {
request["DestinationEndpointPassword"] = v
}
if v, ok := d.GetOk("destination_endpoint_port"); ok {
request["DestinationEndpointPort"] = v
}
if v, ok := d.GetOk("destination_endpoint_region"); ok {
request["DestinationEndpointRegion"] = v
}
if v, ok := d.GetOk("destination_endpoint_user_name"); ok {
request["DestinationEndpointUserName"] = v
}
if v, ok := d.GetOkExists("error_notice"); ok {
request["ErrorNotice"] = v
}
if v, ok := d.GetOk("error_phone"); ok {
request["ErrorPhone"] = v
}
request["JobType"] = "SYNC"
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("reserve"); ok {
request["Reserve"] = v
}
if v, ok := d.GetOk("source_endpoint_database_name"); ok {
request["SourceEndpointDatabaseName"] = v
}
if v, ok := d.GetOk("source_endpoint_engine_name"); ok {
request["SourceEndpointEngineName"] = v
}
if v, ok := d.GetOk("source_endpoint_ip"); ok {
request["SourceEndpointIP"] = v
}
if v, ok := d.GetOk("source_endpoint_instance_id"); ok {
request["SourceEndpointInstanceID"] = v
}
request["SourceEndpointInstanceType"] = d.Get("source_endpoint_instance_type")
if v, ok := d.GetOk("source_endpoint_oracle_sid"); ok {
request["SourceEndpointOracleSID"] = v
}
if v, ok := d.GetOk("source_endpoint_owner_id"); ok {
request["SourceEndpointOwnerID"] = v
}
if v, ok := d.GetOk("source_endpoint_password"); ok {
request["SourceEndpointPassword"] = v
}
if v, ok := d.GetOk("source_endpoint_port"); ok {
request["SourceEndpointPort"] = v
}
if v, ok := d.GetOk("source_endpoint_region"); ok {
request["SourceEndpointRegion"] = v
}
if v, ok := d.GetOk("source_endpoint_role"); ok {
request["SourceEndpointRole"] = v
}
if v, ok := d.GetOk("source_endpoint_user_name"); ok {
request["SourceEndpointUserName"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_dts_synchronization_job", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["DtsJobId"]))
d.Set("dts_instance_id", response["DtsInstanceId"])
dtsService := DtsService{client}
stateConf := BuildStateConf([]string{}, []string{"Synchronizing"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, dtsService.DtsSynchronizationJobStateRefreshFunc(d.Id(), []string{"InitializeFailed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudDtsSynchronizationJobUpdate(d, meta)
}
func resourceAlicloudDtsSynchronizationJobRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dtsService := DtsService{client}
object, err := dtsService.DescribeDtsSynchronizationJob(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_dts_synchronization_job dtsService.DescribeDtsSynchronizationJob Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
migrationModeObj := object["MigrationMode"].(map[string]interface{})
destinationEndpointObj := object["DestinationEndpoint"].(map[string]interface{})
sourceEndpointObj := object["SourceEndpoint"].(map[string]interface{})
d.Set("checkpoint", fmt.Sprint(formatInt(object["Checkpoint"])))
d.Set("data_initialization", migrationModeObj["DataInitialization"])
d.Set("data_synchronization", migrationModeObj["DataSynchronization"])
d.Set("db_list", object["DbObject"])
d.Set("destination_endpoint_database_name", destinationEndpointObj["DatabaseName"])
d.Set("destination_endpoint_engine_name", destinationEndpointObj["EngineName"])
d.Set("destination_endpoint_ip", destinationEndpointObj["Ip"])
d.Set("destination_endpoint_instance_id", destinationEndpointObj["InstanceID"])
d.Set("destination_endpoint_instance_type", destinationEndpointObj["InstanceType"])
d.Set("destination_endpoint_oracle_sid", destinationEndpointObj["OracleSID"])
d.Set("destination_endpoint_port", destinationEndpointObj["Port"])
d.Set("destination_endpoint_region", destinationEndpointObj["Region"])
d.Set("destination_endpoint_user_name", destinationEndpointObj["UserName"])
d.Set("dts_instance_id", object["DtsInstanceID"])
d.Set("dts_job_name", object["DtsJobName"])
d.Set("source_endpoint_database_name", sourceEndpointObj["DatabaseName"])
d.Set("source_endpoint_engine_name", sourceEndpointObj["EngineName"])
d.Set("source_endpoint_ip", sourceEndpointObj["Ip"])
d.Set("source_endpoint_instance_id", sourceEndpointObj["InstanceID"])
d.Set("source_endpoint_instance_type", sourceEndpointObj["InstanceType"])
d.Set("source_endpoint_oracle_sid", sourceEndpointObj["OracleSID"])
d.Set("source_endpoint_owner_id", sourceEndpointObj["AliyunUid"])
d.Set("source_endpoint_port", sourceEndpointObj["Port"])
d.Set("source_endpoint_region", sourceEndpointObj["Region"])
d.Set("source_endpoint_role", sourceEndpointObj["RoleName"])
d.Set("source_endpoint_user_name", sourceEndpointObj["UserName"])
d.Set("status", object["Status"])
d.Set("structure_initialization", migrationModeObj["StructureInitialization"])
d.Set("synchronization_direction", object["SynchronizationDirection"])
return nil
}
func resourceAlicloudDtsSynchronizationJobUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"DtsJobId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("dts_job_name") {
update = true
request["DtsJobName"] = d.Get("dts_job_name")
}
request["RegionId"] = client.RegionId
if update {
action := "ModifyDtsJobName"
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetPartial("dts_job_name")
}
modifyDtsJobPasswordReq := map[string]interface{}{
"DtsJobId": d.Id(),
}
modifyDtsJobPasswordReq["RegionId"] = client.RegionId
if !d.IsNewResource() && d.HasChange("source_endpoint_password") {
modifyDtsJobPasswordReq["Endpoint"] = "src"
if v, ok := d.GetOk("source_endpoint_password"); ok {
modifyDtsJobPasswordReq["Password"] = v
}
if v, ok := d.GetOk("source_endpoint_user_name"); ok {
modifyDtsJobPasswordReq["UserName"] = v
}
action := "ModifyDtsJobPassword"
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, modifyDtsJobPasswordReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyDtsJobPasswordReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetPartial("source_endpoint_password")
d.SetPartial("source_endpoint_user_name")
target := d.Get("status").(string)
err = resourceAlicloudDtsSynchronizationJobStatusFlow(d, meta, target)
if err != nil {
return WrapError(Error(FailedToReachTargetStatus, d.Get("status")))
}
}
if !d.IsNewResource() && d.HasChange("destination_endpoint_password") {
modifyDtsJobPasswordReq["Endpoint"] = "src"
if v, ok := d.GetOk("destination_endpoint_password"); ok {
modifyDtsJobPasswordReq["Password"] = v
}
if v, ok := d.GetOk("destination_endpoint_user_name"); ok {
modifyDtsJobPasswordReq["UserName"] = v
}
action := "ModifyDtsJobPassword"
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, modifyDtsJobPasswordReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyDtsJobPasswordReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetPartial("destination_endpoint_password")
d.SetPartial("destination_endpoint_user_name")
target := d.Get("status").(string)
err = resourceAlicloudDtsSynchronizationJobStatusFlow(d, meta, target)
if err != nil {
return WrapError(Error(FailedToReachTargetStatus, d.Get("status")))
}
}
update = false
request = map[string]interface{}{
"DtsJobId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("instance_class") {
if v, ok := d.GetOk("instance_class"); ok {
request["InstanceClass"] = v
}
update = true
}
request["RegionId"] = client.RegionId
request["OrderType"] = "UPGRADE"
if update {
action := "TransferInstanceClass"
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
}
if !d.IsNewResource() && d.HasChange("status") {
target := d.Get("status").(string)
err := resourceAlicloudDtsSynchronizationJobStatusFlow(d, meta, target)
if err != nil {
return WrapError(Error(FailedToReachTargetStatus, d.Get("status")))
}
}
d.Partial(false)
return resourceAlicloudDtsSynchronizationJobRead(d, meta)
}
func resourceAlicloudDtsSynchronizationJobDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteDtsJob"
var response map[string]interface{}
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DtsJobId": d.Id(),
}
if v, ok := d.GetOk("dts_instance_id"); ok {
request["DtsInstanceId"] = v
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Forbidden.InstanceNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func resourceAlicloudDtsSynchronizationJobStatusFlow(d *schema.ResourceData, meta interface{}, target string) error {
client := meta.(*connectivity.AliyunClient)
dtsService := DtsService{client}
var response map[string]interface{}
object, err := dtsService.DescribeDtsSynchronizationJob(d.Id())
if err != nil {
return WrapError(err)
}
if object["Status"].(string) != target {
if target == "Synchronizing" || target == "Suspending" {
request := map[string]interface{}{
"DtsJobId": d.Id(),
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("synchronization_direction"); ok {
request["SynchronizationDirection"] = v
}
action := "StartDtsJob"
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Synchronizing"}, d.Timeout(schema.TimeoutUpdate), 60*time.Second, dtsService.DtsSynchronizationJobStateRefreshFunc(d.Id(), []string{"InitializeFailed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if target == "Suspending" {
request := map[string]interface{}{
"DtsJobId": d.Id(),
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("synchronization_direction"); ok {
request["SynchronizationDirection"] = v
}
action := "SuspendDtsJob"
conn, err := client.NewDtsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Suspending"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, dtsService.DtsSynchronizationJobStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.SetPartial("status")
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudEaisInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEaisInstanceCreate,
Read: resourceAlicloudEaisInstanceRead,
Update: resourceAlicloudEaisInstanceUpdate,
Delete: resourceAlicloudEaisInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"force": {
Type: schema.TypeBool,
Optional: true,
},
"instance_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"instance_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"eais.ei-a6.4xlarge", "eais.ei-a6.2xlarge", "eais.ei-a6.xlarge", "eais.ei-a6.large", "eais.ei-a6.medium"}, false),
},
"security_group_id": {
Type: schema.TypeString,
Required: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Required: true,
},
},
}
}
func resourceAlicloudEaisInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateEai"
request := make(map[string]interface{})
conn, err := client.NewEaisClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("instance_name"); ok {
request["InstanceName"] = v
}
request["InstanceType"] = d.Get("instance_type")
request["RegionId"] = client.RegionId
request["SecurityGroupId"] = d.Get("security_group_id")
request["VSwitchId"] = d.Get("vswitch_id")
request["ClientToken"] = buildClientToken("CreateEai")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-24"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_eais_instance", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["ElasticAcceleratedInstanceId"]))
eaisService := EaisService{client}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, eaisService.EaisInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudEaisInstanceRead(d, meta)
}
func resourceAlicloudEaisInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
eaisService := EaisService{client}
object, err := eaisService.DescribeEaisInstance(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_eais_instance eaisService.DescribeEaisInstance Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_name", object["InstanceName"])
d.Set("instance_type", object["InstanceType"])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudEaisInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return resourceAlicloudEaisInstanceRead(d, meta)
}
func resourceAlicloudEaisInstanceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteEai"
var response map[string]interface{}
conn, err := client.NewEaisClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ElasticAcceleratedInstanceId": d.Id(),
}
if v, ok := d.GetOkExists("force"); ok {
request["Force"] = v
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-24"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"encoding/base64"
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudEcdCommand() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcdCommandCreate,
Read: resourceAlicloudEcdCommandRead,
Update: resourceAlicloudEcdCommandUpdate,
Delete: resourceAlicloudEcdCommandDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"command_content": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"command_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"RunBatScript", "RunPowerShellScript"}, false),
},
"content_encoding": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Base64", "PlainText"}, false),
},
"desktop_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"timeout": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudEcdCommandCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecdService := EcdService{client}
var response map[string]interface{}
action := "RunCommand"
request := make(map[string]interface{})
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
request["CommandContent"] = d.Get("command_content")
request["Type"] = d.Get("command_type")
if v, ok := d.GetOk("content_encoding"); ok {
request["ContentEncoding"] = v
}
request["DesktopId.1"] = d.Get("desktop_id")
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("timeout"); ok {
request["Timeout"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecd_command", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["InvokeId"]))
stateConf := BuildStateConf([]string{}, []string{"Success"}, d.Timeout(schema.TimeoutCreate), 10*time.Second, ecdService.EcdCommandStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudEcdCommandRead(d, meta)
}
func resourceAlicloudEcdCommandRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecdService := EcdService{client}
object, err := ecdService.DescribeEcdCommand(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecd_command ecdService.DescribeEcdCommand Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
commandContent, _ := base64.StdEncoding.DecodeString(object["CommandContent"].(string))
d.Set("command_content", string(commandContent))
d.Set("command_type", object["CommandType"])
d.Set("status", object["InvocationStatus"])
temp1 := map[string]interface{}{}
if invokeDesktopsList, ok := object["InvokeDesktops"].([]interface{}); ok {
for _, v := range invokeDesktopsList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 = map[string]interface{}{
"desktop_id": m1["DesktopId"],
}
}
}
}
d.Set("desktop_id", temp1["desktop_id"])
return nil
}
func resourceAlicloudEcdCommandUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return nil
}
func resourceAlicloudEcdCommandDelete(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not delete operation."))
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudEcdDesktop() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcdDesktopCreate,
Read: resourceAlicloudEcdDesktopRead,
Update: resourceAlicloudEcdDesktopUpdate,
Delete: resourceAlicloudEcdDesktopDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(20 * time.Minute),
},
Schema: map[string]*schema.Schema{
"amount": {
Type: schema.TypeInt,
Optional: true,
},
"auto_pay": {
Type: schema.TypeBool,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("payment_type"); ok && v.(string) == "Subscription" {
return false
}
return true
},
},
"auto_renew": {
Type: schema.TypeBool,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("payment_type"); ok && v.(string) == "Subscription" {
return false
}
return true
},
},
"bundle_id": {
Type: schema.TypeString,
Required: true,
},
"desktop_name": {
Type: schema.TypeString,
Optional: true,
},
"desktop_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"office_site_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"end_user_ids": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"payment_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo", "Subscription"}, false),
},
"period": {
Type: schema.TypeInt,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("payment_type"); ok && v.(string) == "Subscription" {
return false
}
return true
},
},
"period_unit": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("payment_type"); ok && v.(string) == "Subscription" {
return false
}
return true
},
},
"policy_group_id": {
Type: schema.TypeString,
Required: true,
},
"root_disk_size_gib": {
Type: schema.TypeInt,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("status"); ok && v.(string) == "Stopped" {
return false
}
return true
},
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Running", "Stopped", "Pending", "Stopping", "Starting", "Expired", "Deleted"}, false),
},
"stopped_mode": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"StopCharging", "KeepCharging"}, false),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("status"); ok && v.(string) == "Stopped" {
return false
}
return true
},
},
"tags": tagsSchema(),
"user_assign_mode": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"ALL", "PER_USER"}, false),
},
"user_disk_size_gib": {
Type: schema.TypeInt,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("status"); ok && v.(string) == "Stopped" {
return false
}
return true
},
},
"host_name": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudEcdDesktopCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecdService := EcdService{client}
var response map[string]interface{}
action := "CreateDesktops"
request := make(map[string]interface{})
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("amount"); ok {
request["Amount"] = v
}
if v, ok := d.GetOkExists("auto_pay"); ok {
request["AutoPay"] = v
}
if v, ok := d.GetOkExists("auto_renew"); ok {
request["AutoRenew"] = v
}
request["BundleId"] = d.Get("bundle_id")
if v, ok := d.GetOk("desktop_name"); ok {
request["DesktopName"] = v
}
request["OfficeSiteId"] = d.Get("office_site_id")
if m, ok := d.GetOk("end_user_ids"); ok {
for k, v := range m.([]interface{}) {
request[fmt.Sprintf("EndUserId.%d", k+1)] = v.(string)
}
}
if v, ok := d.GetOk("payment_type"); ok {
request["ChargeType"] = convertEcdDesktopPaymentTypeRequest(v.(string))
}
if v, ok := d.GetOk("period"); ok {
request["Period"] = v
}
if v, ok := d.GetOk("period_unit"); ok {
request["PeriodUnit"] = v
}
request["PolicyGroupId"] = d.Get("policy_group_id")
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("tags"); ok {
count := 1
for key, value := range v.(map[string]interface{}) {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
}
if v, ok := d.GetOk("user_assign_mode"); ok {
request["UserAssignMode"] = v
}
if v, ok := d.GetOk("host_name"); ok {
request["HostName"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecd_desktop", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["DesktopId"].([]interface{})[0]))
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 10*time.Second, ecdService.EcdDesktopStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudEcdDesktopUpdate(d, meta)
}
func resourceAlicloudEcdDesktopRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecdService := EcdService{client}
object, err := ecdService.DescribeEcdDesktop(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecd_desktop ecdService.DescribeEcdDesktop Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("desktop_name", object["DesktopName"])
d.Set("desktop_type", object["DesktopType"])
d.Set("office_site_id", object["OfficeSiteId"])
d.Set("end_user_ids", object["EndUserIds"])
d.Set("payment_type", convertEcdDesktopPaymentTypeResponse(object["ChargeType"]))
d.Set("policy_group_id", object["PolicyGroupId"])
d.Set("status", object["DesktopStatus"])
d.Set("tags", tagsToMap(object["Tags"]))
return nil
}
func resourceAlicloudEcdDesktopUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecdService := EcdService{client}
var response map[string]interface{}
d.Partial(true)
if !d.IsNewResource() && d.HasChange("tags") {
if err := ecdService.SetResourceTags(d, "ALIYUN::GWS::INSTANCE"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
request := map[string]interface{}{
"DesktopId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("desktop_name") {
if v, ok := d.GetOk("desktop_name"); ok {
request["NewDesktopName"] = v
}
request["RegionId"] = client.RegionId
action := "ModifyDesktopName"
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("desktop_name")
}
if !d.IsNewResource() && d.HasChange("policy_group_id") {
request := map[string]interface{}{
"DesktopId.1": d.Id(),
}
request["PolicyGroupId"] = d.Get("policy_group_id")
request["RegionId"] = client.RegionId
action := "ModifyDesktopsPolicyGroup"
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("policy_group_id")
}
if !d.IsNewResource() && d.HasChange("end_user_ids") {
request := map[string]interface{}{
"DesktopId": d.Id(),
}
request["RegionId"] = client.RegionId
if m, ok := d.GetOk("end_user_ids"); ok {
for k, v := range m.([]interface{}) {
request[fmt.Sprintf("EndUserId.%d", k+1)] = v.(string)
}
}
action := "ModifyEntitlement"
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("end_user_ids")
}
if d.HasChange("status") {
object, err := ecdService.DescribeEcdDesktop(d.Id())
if err != nil {
return WrapError(err)
}
target := d.Get("status").(string)
if object["DesktopStatus"].(string) != target {
if target == "Running" {
request := map[string]interface{}{
"DesktopId.1": d.Id(),
}
request["RegionId"] = client.RegionId
action := "StartDesktops"
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if target == "Stopped" {
request := map[string]interface{}{
"DesktopId.1": d.Id(),
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("stopped_mode"); ok {
request["StoppedMode"] = v
}
action := "StopDesktops"
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
stateConf := BuildStateConf([]string{"Pending", "Starting", "Stopping"}, []string{"Running", "Stopped"}, d.Timeout(schema.TimeoutUpdate), 10*time.Second, ecdService.EcdDesktopStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("status")
}
}
if d.HasChange("desktop_type") || d.HasChange("root_disk_size_gib") || d.HasChange("user_disk_size_gib") {
request = map[string]interface{}{
"DesktopId": d.Id(),
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("desktop_type"); ok {
request["DesktopType"] = v
}
if v, ok := d.GetOkExists("auto_pay"); ok {
request["AutoPay"] = v
}
if v, ok := d.GetOk("root_disk_size_gib"); ok {
request["RootDiskSizeGib"] = v
}
if v, ok := d.GetOk("user_disk_size_gib"); ok {
request["UserDiskSizeGib"] = v
}
action := "ModifyDesktopSpec"
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{request["DesktopType"].(string)}, d.Timeout(schema.TimeoutUpdate), 10*time.Second, ecdService.EcdDesktopDesktopTypeRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("desktop_type")
}
if !d.IsNewResource() && d.HasChange("payment_type") {
object, err := ecdService.DescribeEcdDesktop(d.Id())
if err != nil {
return WrapError(err)
}
if convertEcdDesktopPaymentTypeResponse(object["ChargeType"]) != "Subscription" {
if object["DesktopStatus"].(string) == "Stopped" || object["DesktopStatus"].(string) == "Running" {
request := map[string]interface{}{
"DesktopId.1": d.Id(),
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("payment_type"); ok {
request["ChargeType"] = convertEcdDesktopPaymentTypeRequest(v.(string))
}
if v, ok := d.GetOk("period"); ok {
request["Period"] = v
}
if v, ok := d.GetOk("period_unit"); ok {
request["PeriodUnit"] = v
}
if v, ok := d.GetOkExists("auto_pay"); ok {
request["AutoPay"] = v
}
action := "ModifyDesktopChargeType"
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Subscription"}, d.Timeout(schema.TimeoutUpdate), 10*time.Second, ecdService.EcdDesktopChargeTypeFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
}
d.SetPartial("payment_type")
}
d.Partial(false)
return resourceAlicloudEcdDesktopRead(d, meta)
}
func resourceAlicloudEcdDesktopDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecdService := EcdService{client}
action := "DeleteDesktops"
var response map[string]interface{}
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DesktopId.1": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidChargeType.Unsupported"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 10*time.Second, ecdService.EcdDesktopStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
func convertEcdDesktopPaymentTypeRequest(source interface{}) interface{} {
switch source {
case "PayAsYouGo":
return "PostPaid"
case "Subscription":
return "PrePaid"
}
return source
}
func convertEcdDesktopPaymentTypeResponse(source interface{}) interface{} {
switch source {
case "PostPaid":
return "PayAsYouGo"
case "PrePaid":
return "Subscription"
}
return source
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEcdImage() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcdImageCreate,
Read: resourceAlicloudEcdImageRead,
Update: resourceAlicloudEcdImageUpdate,
Delete: resourceAlicloudEcdImageDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(15 * time.Minute),
Delete: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
},
"desktop_id": {
Type: schema.TypeString,
Required: true,
},
"image_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateNormalName,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudEcdImageCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateImage"
request := make(map[string]interface{})
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["DesktopId"] = d.Get("desktop_id")
if v, ok := d.GetOk("image_name"); ok {
request["ImageName"] = v
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecd_image", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["ImageId"]))
ecdService := EcdService{client}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, ecdService.EcdImageStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudEcdImageRead(d, meta)
}
func resourceAlicloudEcdImageRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecdService := EcdService{client}
object, err := ecdService.DescribeEcdImage(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecd_image ecdService.DescribeEcdImage Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", object["Description"])
d.Set("image_name", object["Name"])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudEcdImageUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"ImageId": d.Id(),
}
if d.HasChange("description") {
update = true
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["RegionId"] = client.RegionId
if d.HasChange("image_name") {
update = true
if v, ok := d.GetOk("image_name"); ok {
request["Name"] = v
}
}
if update {
action := "ModifyImageAttribute"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
ecdService := EcdService{client}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, ecdService.EcdImageStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudEcdImageRead(d, meta)
}
func resourceAlicloudEcdImageDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecdService := EcdService{client}
action := "DeleteImages"
var response map[string]interface{}
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ImageId": []string{d.Id()},
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, ecdService.EcdImageStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEcdNasFileSystem() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcdNasFileSystemCreate,
Read: resourceAlicloudEcdNasFileSystemRead,
Update: resourceAlicloudEcdNasFileSystemUpdate,
Delete: resourceAlicloudEcdNasFileSystemDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"mount_target_domain": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"file_system_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"nas_file_system_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"office_site_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"reset": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func resourceAlicloudEcdNasFileSystemCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateNASFileSystem"
request := make(map[string]interface{})
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("nas_file_system_name"); ok {
request["Name"] = v
}
request["OfficeSiteId"] = d.Get("office_site_id")
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecd_nas_file_system", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["FileSystemId"]))
ecdService := EcdService{client}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 10*time.Second, ecdService.EcdNasFileSystemStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudEcdNasFileSystemUpdate(d, meta)
}
func resourceAlicloudEcdNasFileSystemRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecdService := EcdService{client}
object, err := ecdService.DescribeEcdNasFileSystem(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecd_nas_file_system ecdService.DescribeEcdNasFileSystem Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", object["Description"])
d.Set("mount_target_domain", object["MountTargetDomain"])
d.Set("nas_file_system_name", object["FileSystemName"])
d.Set("office_site_id", object["OfficeSiteId"])
d.Set("status", object["FileSystemStatus"])
d.Set("file_system_id", object["FileSystemId"])
return nil
}
func resourceAlicloudEcdNasFileSystemUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecdService := EcdService{client}
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
update := false
request := map[string]interface{}{
"FileSystemId": d.Id(),
"RegionId": client.RegionId,
}
if d.HasChange("reset") {
if v, ok := d.GetOk("reset"); ok && v.(bool) {
update = true
}
}
if update {
action := "ResetNASDefaultMountTarget"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, ecdService.EcdNasFileSystemStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudEcdNasFileSystemRead(d, meta)
}
func resourceAlicloudEcdNasFileSystemDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecdService := EcdService{client}
action := "DeleteNASFileSystems"
var response map[string]interface{}
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"FileSystemId": []string{d.Id()},
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, ecdService.EcdNasFileSystemStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEcdNetworkPackage() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcdNetworkPackageCreate,
Read: resourceAlicloudEcdNetworkPackageRead,
Update: resourceAlicloudEcdNetworkPackageUpdate,
Delete: resourceAlicloudEcdNetworkPackageDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"bandwidth": {
Type: schema.TypeInt,
Required: true,
},
"office_site_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"internet_charge_type": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudEcdNetworkPackageCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateNetworkPackage"
request := make(map[string]interface{})
ecdService := EcdService{client}
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
request["Bandwidth"] = d.Get("bandwidth")
request["OfficeSiteId"] = d.Get("office_site_id")
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecd_network_package", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["NetworkPackageId"]))
stateConf := BuildStateConf([]string{"Creating"}, []string{"InUse"}, d.Timeout(schema.TimeoutDelete), 5*time.Second, ecdService.EcdNetworkPackageRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudEcdNetworkPackageRead(d, meta)
}
func resourceAlicloudEcdNetworkPackageRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecdService := EcdService{client}
object, err := ecdService.DescribeEcdNetworkPackage(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecd_network_package ecdService.DescribeEcdNetworkPackage Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
if v, ok := object["Bandwidth"]; ok && fmt.Sprint(v) != "0" {
d.Set("bandwidth", formatInt(v))
}
d.Set("internet_charge_type", object["InternetChargeType"])
d.Set("office_site_id", object["OfficeSiteId"])
d.Set("status", object["NetworkPackageStatus"])
return nil
}
func resourceAlicloudEcdNetworkPackageUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
request := map[string]interface{}{
"RegionId": client.RegionId,
"NetworkPackageId": d.Id(),
}
if d.HasChange("bandwidth") {
request["Bandwidth"] = d.Get("bandwidth")
}
action := "ModifyNetworkPackage"
ecdService := EcdService{client}
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) || IsExpectedErrors(err, []string{"IncorrectNetworkPackageStatus.ModificationNotSupport"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"Creating"}, []string{"InUse"}, d.Timeout(schema.TimeoutDelete), 5*time.Second, ecdService.EcdNetworkPackageRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudEcdNetworkPackageRead(d, meta)
}
func resourceAlicloudEcdNetworkPackageDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteNetworkPackages"
var response map[string]interface{}
ecdService := EcdService{client}
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"NetworkPackageId": []string{d.Id()},
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) || IsExpectedErrors(err, []string{"IncorrectNetworkPackageStatus.DeletionNotSupport"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"Releasing"}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, ecdService.EcdNetworkPackageRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudEcdPolicyGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcdPolicyGroupCreate,
Read: resourceAlicloudEcdPolicyGroupRead,
Update: resourceAlicloudEcdPolicyGroupUpdate,
Delete: resourceAlicloudEcdPolicyGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"authorize_access_policy_rules": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cidr_ip": {
Type: schema.TypeString,
Optional: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"authorize_security_policy_rules": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cidr_ip": {
Type: schema.TypeString,
Optional: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"ip_protocol": {
Type: schema.TypeString,
Optional: true,
},
"policy": {
Type: schema.TypeString,
Optional: true,
},
"port_range": {
Type: schema.TypeString,
Optional: true,
},
"priority": {
Type: schema.TypeString,
Optional: true,
},
"type": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"clipboard": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"off", "read", "readwrite"}, false),
},
"domain_list": {
Type: schema.TypeString,
Optional: true,
},
"html_access": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"off", "on"}, false),
},
"html_file_transfer": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"all", "download", "off", "upload"}, false),
},
"local_drive": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"readwrite", "off", "read"}, false),
},
"policy_group_name": {
Type: schema.TypeString,
Optional: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"usb_redirect": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"off", "on"}, false),
},
"visual_quality": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"high", "lossless", "low", "medium"}, false),
},
"watermark": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"off", "on"}, false),
},
"watermark_transparency": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"DARK", "LIGHT", "MIDDLE"}, false),
},
"watermark_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"EndUserId", "HostName"}, false),
},
},
}
}
func resourceAlicloudEcdPolicyGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreatePolicyGroup"
request := make(map[string]interface{})
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("authorize_access_policy_rules"); ok {
for authorizeAccessPolicyRulesPtr, authorizeAccessPolicyRules := range v.(*schema.Set).List() {
authorizeAccessPolicyRulesArg := authorizeAccessPolicyRules.(map[string]interface{})
request["AuthorizeAccessPolicyRule."+fmt.Sprint(authorizeAccessPolicyRulesPtr+1)+".CidrIp"] = authorizeAccessPolicyRulesArg["cidr_ip"]
request["AuthorizeAccessPolicyRule."+fmt.Sprint(authorizeAccessPolicyRulesPtr+1)+".Description"] = authorizeAccessPolicyRulesArg["description"]
}
}
if v, ok := d.GetOk("authorize_security_policy_rules"); ok {
for authorizeSecurityPolicyRulesPtr, authorizeSecurityPolicyRules := range v.(*schema.Set).List() {
authorizeSecurityPolicyRulesArg := authorizeSecurityPolicyRules.(map[string]interface{})
request["AuthorizeSecurityPolicyRule."+fmt.Sprint(authorizeSecurityPolicyRulesPtr+1)+".CidrIp"] = authorizeSecurityPolicyRulesArg["cidr_ip"]
request["AuthorizeSecurityPolicyRule."+fmt.Sprint(authorizeSecurityPolicyRulesPtr+1)+".Description"] = authorizeSecurityPolicyRulesArg["description"]
request["AuthorizeSecurityPolicyRule."+fmt.Sprint(authorizeSecurityPolicyRulesPtr+1)+".IpProtocol"] = authorizeSecurityPolicyRulesArg["ip_protocol"]
request["AuthorizeSecurityPolicyRule."+fmt.Sprint(authorizeSecurityPolicyRulesPtr+1)+".Policy"] = authorizeSecurityPolicyRulesArg["policy"]
request["AuthorizeSecurityPolicyRule."+fmt.Sprint(authorizeSecurityPolicyRulesPtr+1)+".PortRange"] = authorizeSecurityPolicyRulesArg["port_range"]
request["AuthorizeSecurityPolicyRule."+fmt.Sprint(authorizeSecurityPolicyRulesPtr+1)+".Priority"] = authorizeSecurityPolicyRulesArg["priority"]
request["AuthorizeSecurityPolicyRule."+fmt.Sprint(authorizeSecurityPolicyRulesPtr+1)+".Type"] = authorizeSecurityPolicyRulesArg["type"]
}
}
if v, ok := d.GetOk("clipboard"); ok {
request["Clipboard"] = v
}
if v, ok := d.GetOk("domain_list"); ok {
request["DomainList"] = v
}
if v, ok := d.GetOk("html_access"); ok {
request["Html5Access"] = v
}
if v, ok := d.GetOk("html_file_transfer"); ok {
request["Html5FileTransfer"] = v
}
if v, ok := d.GetOk("local_drive"); ok {
request["LocalDrive"] = v
}
if v, ok := d.GetOk("policy_group_name"); ok {
request["Name"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("usb_redirect"); ok {
request["UsbRedirect"] = v
}
if v, ok := d.GetOk("visual_quality"); ok {
request["VisualQuality"] = v
}
if v, ok := d.GetOk("watermark"); ok {
request["Watermark"] = v
}
if v, ok := d.GetOk("watermark_transparency"); ok {
request["WatermarkTransparency"] = v
}
if v, ok := d.GetOk("watermark_type"); ok {
request["WatermarkType"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecd_policy_group", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["PolicyGroupId"]))
return resourceAlicloudEcdPolicyGroupRead(d, meta)
}
func resourceAlicloudEcdPolicyGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecdService := EcdService{client}
object, err := ecdService.DescribeEcdPolicyGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecd_policy_group ecdService.DescribeEcdPolicyGroup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
if authorizeAccessPolicyRulesList, ok := object["AuthorizeAccessPolicyRules"]; ok && authorizeAccessPolicyRulesList != nil {
authorizeAccessPolicyRulesMaps := make([]map[string]interface{}, 0)
for _, authorizeAccessPolicyRulesListItem := range authorizeAccessPolicyRulesList.([]interface{}) {
if authorizeAccessPolicyRulesListItemMap, ok := authorizeAccessPolicyRulesListItem.(map[string]interface{}); ok {
authorizeAccessPolicyRulesMap := make(map[string]interface{})
authorizeAccessPolicyRulesMap["cidr_ip"] = authorizeAccessPolicyRulesListItemMap["CidrIp"]
authorizeAccessPolicyRulesMap["description"] = authorizeAccessPolicyRulesListItemMap["Description"]
authorizeAccessPolicyRulesMaps = append(authorizeAccessPolicyRulesMaps, authorizeAccessPolicyRulesMap)
}
}
d.Set("authorize_access_policy_rules", authorizeAccessPolicyRulesMaps)
}
if v, ok := object["AuthorizeSecurityPolicyRules"].([]interface{}); ok {
authorizeSecurityPolicyRules := make([]map[string]interface{}, 0)
for _, val := range v {
item := val.(map[string]interface{})
temp := map[string]interface{}{
"cidr_ip": item["CidrIp"],
"description": item["Description"],
"ip_protocol": item["IpProtocol"],
"policy": item["Policy"],
"port_range": item["PortRange"],
"priority": item["Priority"],
"type": item["Type"],
}
authorizeSecurityPolicyRules = append(authorizeSecurityPolicyRules, temp)
}
if err := d.Set("authorize_security_policy_rules", authorizeSecurityPolicyRules); err != nil {
return WrapError(err)
}
}
d.Set("clipboard", object["Clipboard"])
d.Set("domain_list", object["DomainList"])
d.Set("html_access", object["Html5Access"])
d.Set("html_file_transfer", object["Html5FileTransfer"])
d.Set("local_drive", object["LocalDrive"])
d.Set("policy_group_name", object["Name"])
d.Set("status", object["PolicyStatus"])
d.Set("usb_redirect", object["UsbRedirect"])
d.Set("visual_quality", object["VisualQuality"])
d.Set("watermark", object["Watermark"])
d.Set("watermark_transparency", object["WatermarkTransparency"])
d.Set("watermark_type", object["WatermarkType"])
return nil
}
func resourceAlicloudEcdPolicyGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecdService := EcdService{client}
var response map[string]interface{}
update := false
request := map[string]interface{}{
"PolicyGroupId": d.Id(),
}
request["RegionId"] = client.RegionId
if d.HasChange("authorize_access_policy_rules") {
update = true
err := ecdService.setAuthAccessPolicyRules(d, request, "authorize_access_policy_rules")
if err != nil {
return WrapError(err)
}
d.SetPartial("authorize_access_policy_rules")
}
if d.HasChange("authorize_security_policy_rules") {
update = true
err := ecdService.setAuthSecurityPolicyRules(d, request, "authorize_security_policy_rules")
if err != nil {
return WrapError(err)
}
d.SetPartial("authorize_security_policy_rules")
}
if d.HasChange("cidr_ip") {
update = true
if v, ok := d.GetOk("cidr_ip"); ok {
request["AuthorizeSecurityPolicyRule.*.CidrIp"] = v
}
}
if d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
request["AuthorizeSecurityPolicyRule.*.Description"] = v
}
}
if d.HasChange("ip_protocol") {
update = true
if v, ok := d.GetOk("ip_protocol"); ok {
request["AuthorizeSecurityPolicyRule.*.IpProtocol"] = v
}
}
if d.HasChange("policy") {
update = true
if v, ok := d.GetOk("policy"); ok {
request["AuthorizeSecurityPolicyRule.*.Policy"] = v
}
}
if d.HasChange("port_range") {
update = true
if v, ok := d.GetOk("port_range"); ok {
request["AuthorizeSecurityPolicyRule.*.PortRange"] = v
}
}
if d.HasChange("priority") {
update = true
if v, ok := d.GetOk("priority"); ok {
request["AuthorizeSecurityPolicyRule.*.Priority"] = v
}
}
if d.HasChange("type") {
update = true
if v, ok := d.GetOk("type"); ok {
request["AuthorizeSecurityPolicyRule.*.Type"] = v
}
}
if d.HasChange("clipboard") {
update = true
if v, ok := d.GetOk("clipboard"); ok {
request["Clipboard"] = v
}
}
if d.HasChange("domain_list") {
update = true
if v, ok := d.GetOk("domain_list"); ok {
request["DomainList"] = v
}
}
if d.HasChange("html_access") {
update = true
if v, ok := d.GetOk("html_access"); ok {
request["Html5Access"] = v
}
}
if d.HasChange("html_file_transfer") {
update = true
if v, ok := d.GetOk("html_file_transfer"); ok {
request["Html5FileTransfer"] = v
}
}
if d.HasChange("local_drive") {
update = true
if v, ok := d.GetOk("local_drive"); ok {
request["LocalDrive"] = v
}
}
if d.HasChange("policy_group_name") {
update = true
if v, ok := d.GetOk("policy_group_name"); ok {
request["Name"] = v
}
}
if d.HasChange("usb_redirect") {
update = true
if v, ok := d.GetOk("usb_redirect"); ok {
request["UsbRedirect"] = v
}
}
if d.HasChange("visual_quality") {
update = true
}
if v, ok := d.GetOk("visual_quality"); ok {
request["VisualQuality"] = v
}
if d.HasChange("watermark") {
update = true
}
if v, ok := d.GetOk("watermark"); ok {
request["Watermark"] = v
}
if d.HasChange("watermark_transparency") {
update = true
}
if v, ok := d.GetOk("watermark_transparency"); ok {
request["WatermarkTransparency"] = v
}
if d.HasChange("watermark_type") {
update = true
}
if v, ok := d.GetOk("watermark_type"); ok {
request["WatermarkType"] = v
}
if update {
action := "ModifyPolicyGroup"
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudEcdPolicyGroupRead(d, meta)
}
func resourceAlicloudEcdPolicyGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeletePolicyGroups"
var response map[string]interface{}
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"PolicyGroupId": []string{d.Id()},
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudEcdSimpleOfficeSite() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcdSimpleOfficeSiteCreate,
Read: resourceAlicloudEcdSimpleOfficeSiteRead,
Update: resourceAlicloudEcdSimpleOfficeSiteUpdate,
Delete: resourceAlicloudEcdSimpleOfficeSiteDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"bandwidth": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(0, 200),
Deprecated: "Field 'bandwidth' has been deprecated from provider version 1.142.0.",
},
"cen_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"cen_owner_id": {
Type: schema.TypeString,
Optional: true,
},
"cidr_block": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"desktop_access_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Any", "Internet", "VPC"}, false),
},
"enable_admin_access": {
Type: schema.TypeBool,
Computed: true,
Optional: true,
ForceNew: true,
},
"enable_cross_desktop_access": {
Type: schema.TypeBool,
Computed: true,
Optional: true,
},
"enable_internet_access": {
Type: schema.TypeBool,
Computed: true,
Optional: true,
Deprecated: "Field 'enable_internet_access' has been deprecated from provider version 1.142.0.",
},
"mfa_enabled": {
Type: schema.TypeBool,
Computed: true,
Optional: true,
},
"office_site_name": {
Type: schema.TypeString,
Optional: true,
},
"sso_enabled": {
Type: schema.TypeBool,
Computed: true,
Optional: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudEcdSimpleOfficeSiteCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateSimpleOfficeSite"
request := make(map[string]interface{})
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
request["CidrBlock"] = d.Get("cidr_block")
request["RegionId"] = client.RegionId
if v, ok := d.GetOkExists("enable_admin_access"); ok {
request["EnableAdminAccess"] = v
}
if v, ok := d.GetOk("cen_owner_id"); ok {
request["CenOwnerId"] = v
}
if v, ok := d.GetOk("cen_id"); ok {
request["CenId"] = v
}
if v, ok := d.GetOk("office_site_name"); ok {
request["OfficeSiteName"] = v
}
// todo: you can configure it using alicloud_ecd_network_package
if v, ok := d.GetOkExists("enable_internet_access"); ok {
request["EnableInternetAccess"] = v
}
if v, ok := d.GetOk("bandwidth"); ok {
request["Bandwidth"] = v
}
if v, ok := d.GetOk("desktop_access_type"); ok {
request["DesktopAccessType"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecd_simple_office_site", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["OfficeSiteId"]))
ecdService := EcdService{client}
stateConf := BuildStateConf([]string{}, []string{"REGISTERED"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, ecdService.EcdSimpleOfficeSiteStateRefreshFunc(d.Id()))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudEcdSimpleOfficeSiteUpdate(d, meta)
}
func resourceAlicloudEcdSimpleOfficeSiteRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecdService := EcdService{client}
object, err := ecdService.DescribeEcdSimpleOfficeSite(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecd_simple_office_site ecdService.DescribeEcdSimpleOfficeSite Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
// todo: bandwidth depends on network_package resource, you can find it in alicloud_ecd_network_package
if v, ok := object["Bandwidth"]; ok && fmt.Sprint(v) != "0" {
d.Set("bandwidth", formatInt(v))
}
d.Set("cen_id", object["CenId"])
d.Set("cidr_block", object["CidrBlock"])
d.Set("desktop_access_type", convertDesktopAccessType(object["DesktopAccessType"]))
d.Set("enable_admin_access", object["EnableAdminAccess"])
d.Set("enable_cross_desktop_access", object["EnableCrossDesktopAccess"])
d.Set("office_site_name", object["Name"])
d.Set("mfa_enabled", object["MfaEnabled"])
d.Set("enable_internet_access", object["EnableInternetAccess"])
d.Set("sso_enabled", object["SsoEnabled"])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudEcdSimpleOfficeSiteUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"OfficeSiteId": d.Id(),
}
if d.HasChange("enable_cross_desktop_access") {
update = true
if v, ok := d.GetOkExists("enable_cross_desktop_access"); ok {
request["EnableCrossDesktopAccess"] = v
}
}
if update {
request["RegionId"] = client.RegionId
action := "ModifyOfficeSiteCrossDesktopAccess"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) || IsExpectedErrors(err, []string{"DirectoryNotReady"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("enable_cross_desktop_access")
}
update = false
request = map[string]interface{}{
"OfficeSiteId": d.Id(),
}
if d.HasChange("mfa_enabled") {
update = true
if v, ok := d.GetOkExists("mfa_enabled"); ok {
request["MfaEnabled"] = v
}
}
if update {
request["RegionId"] = client.RegionId
action := "ModifyOfficeSiteMfaEnabled"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) || IsExpectedErrors(err, []string{"DirectoryNotReady"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("mfa_enabled")
}
update = false
request = map[string]interface{}{
"OfficeSiteId": d.Id(),
}
if d.HasChange("sso_enabled") {
update = true
request["RegionId"] = client.RegionId
if v, ok := d.GetOkExists("sso_enabled"); ok {
request["EnableSso"] = v
}
}
if update {
action := "SetOfficeSiteSsoStatus"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) || IsExpectedErrors(err, []string{"DirectoryNotReady"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("sso_enabled")
}
update = false
request = map[string]interface{}{
"OfficeSiteId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("desktop_access_type") {
update = true
}
if v, ok := d.GetOk("desktop_access_type"); ok {
request["DesktopAccessType"] = v
}
if !d.IsNewResource() && d.HasChange("office_site_name") {
update = true
}
if v, ok := d.GetOk("office_site_name"); ok {
request["OfficeSiteName"] = v
}
if update {
request["RegionId"] = client.RegionId
action := "ModifyOfficeSiteAttribute"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) || IsExpectedErrors(err, []string{"DirectoryNotReady"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("desktop_access_type")
d.SetPartial("office_site_name")
}
d.Partial(false)
return resourceAlicloudEcdSimpleOfficeSiteRead(d, meta)
}
func resourceAlicloudEcdSimpleOfficeSiteDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecdService := EcdService{client}
object, err := ecdService.DescribeEcdSimpleOfficeSite(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecd_simple_office_site ecdService.DescribeEcdSimpleOfficeSite Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
if object["EnableInternetAccess"] == true {
log.Printf("[WARN] Cannot destroy resource EcdSimpleOfficeSite. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
action := "DeleteOfficeSites"
var response map[string]interface{}
conn, err := client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"OfficeSiteId": []string{d.Id()},
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func convertDesktopAccessType(source interface{}) interface{} {
switch source.(string) {
case "ANY":
return "Any"
case "INTERNET":
return "Internet"
case "VPC":
return "VPC"
default:
return source
}
}
package alicloud
import (
"fmt"
"log"
"strconv"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudEcdUser() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcdUserCreate,
Read: resourceAlicloudEcdUserRead,
Update: resourceAlicloudEcdUserUpdate,
Delete: resourceAlicloudEcdUserDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"email": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"end_user_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"password": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Sensitive: true,
},
"phone": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Unlocked", "Locked"}, false),
},
},
}
}
func resourceAlicloudEcdUserCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateUsers"
request := make(map[string]interface{})
conn, err := client.NewEdsuserClient()
if err != nil {
return WrapError(err)
}
requestUsers := make(map[string]interface{})
requestUsersMap := make([]interface{}, 0)
requestUsers["Email"] = d.Get("email")
requestUsers["EndUserId"] = d.Get("end_user_id")
if v, ok := d.GetOk("password"); ok {
requestUsers["Password"] = v
}
if v, ok := d.GetOk("phone"); ok {
requestUsers["Phone"] = v
}
requestUsersMap = append(requestUsersMap, requestUsers)
request["Users"] = requestUsersMap
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-03-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"Forbidden"}) {
conn.Endpoint = String(connectivity.EcdOpenAPIEndpointUser)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecd_user", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(requestUsers["EndUserId"]))
edsUserService := EdsUserService{client}
stateConf := BuildStateConf([]string{}, []string{"Unlocked", "Locked"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, edsUserService.EcdUserStateRefreshFunc(d.Id()))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudEcdUserUpdate(d, meta)
}
func resourceAlicloudEcdUserRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edsUserService := EdsUserService{client}
object, err := edsUserService.DescribeEcdUser(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecd_user edsUserService.DescribeEcdUser Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("end_user_id", d.Id())
d.Set("email", object["Email"])
d.Set("phone", object["Phone"])
d.Set("status", convertEcdUserStatusResponse(fmt.Sprint(formatInt(object["Status"]))))
return nil
}
func resourceAlicloudEcdUserUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewEdsuserClient()
if err != nil {
return WrapError(err)
}
edsUserService := EdsUserService{client}
var response map[string]interface{}
d.Partial(true)
if d.HasChange("status") {
object, err := edsUserService.DescribeEcdUser(d.Id())
if err != nil {
return WrapError(err)
}
if target, ok := d.GetOk("status"); ok {
if convertEcdUserStatusRequest(strconv.Itoa(formatInt(object["Status"]))) != target {
if target == "Unlocked" {
request := map[string]interface{}{
"Users": []string{d.Id()},
}
action := "UnlockUsers"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-03-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"Forbidden"}) {
conn.Endpoint = String(connectivity.EcdOpenAPIEndpointUser)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if target == "Locked" {
request := map[string]interface{}{
"Users": []string{d.Id()},
}
action := "LockUsers"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-03-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"Forbidden"}) {
conn.Endpoint = String(connectivity.EcdOpenAPIEndpointUser)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("status")
}
}
}
d.Partial(false)
return resourceAlicloudEcdUserRead(d, meta)
}
func resourceAlicloudEcdUserDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "RemoveUsers"
var response map[string]interface{}
conn, err := client.NewEdsuserClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"Users": []string{d.Id()},
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-03-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"Forbidden"}) {
conn.Endpoint = String(connectivity.EcdOpenAPIEndpointUser)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func convertEcdUserStatusResponse(source string) string {
switch source {
case "0":
return "Unlocked"
case "9":
return "Locked"
}
return source
}
func convertEcdUserStatusRequest(source string) string {
switch source {
case "Unlocked":
return "0"
case "Locked":
return "9"
}
return source
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEciContainerGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEciContainerGroupCreate,
Read: resourceAlicloudEciContainerGroupRead,
Update: resourceAlicloudEciContainerGroupUpdate,
Delete: resourceAlicloudEciContainerGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(20 * time.Minute),
Update: schema.DefaultTimeout(20 * time.Minute),
},
Schema: map[string]*schema.Schema{
"container_group_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"containers": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"args": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"commands": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"cpu": {
Type: schema.TypeFloat,
Optional: true,
Default: 0,
},
"environment_vars": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Optional: true,
},
"value": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"gpu": {
Type: schema.TypeInt,
Optional: true,
Default: 0,
},
"image": {
Type: schema.TypeString,
Required: true,
},
"image_pull_policy": {
Type: schema.TypeString,
Optional: true,
Default: "IfNotPresent",
},
"memory": {
Type: schema.TypeFloat,
Optional: true,
Default: 0,
},
"name": {
Type: schema.TypeString,
Required: true,
},
"ports": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"port": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"protocol": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
},
ForceNew: true,
},
"ready": {
Type: schema.TypeBool,
Computed: true,
},
"restart_count": {
Type: schema.TypeInt,
Computed: true,
},
"volume_mounts": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"mount_path": {
Type: schema.TypeString,
Optional: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
},
"read_only": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
},
},
"working_dir": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"cpu": {
Type: schema.TypeFloat,
Optional: true,
Default: 2,
},
"dns_config": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name_servers": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"options": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
},
"value": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"searches": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
},
},
"eci_security_context": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"sysctls": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"value": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
},
ForceNew: true,
},
},
},
ForceNew: true,
},
"host_aliases": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"hostnames": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
ForceNew: true,
},
"ip": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
},
ForceNew: true,
},
"init_containers": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"args": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"commands": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"cpu": {
Type: schema.TypeFloat,
Optional: true,
Default: 0,
},
"environment_vars": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Optional: true,
},
"value": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"gpu": {
Type: schema.TypeInt,
Optional: true,
Default: 0,
},
"image": {
Type: schema.TypeString,
Optional: true,
},
"image_pull_policy": {
Type: schema.TypeString,
Optional: true,
Default: "IfNotPresent",
},
"memory": {
Type: schema.TypeFloat,
Optional: true,
Default: 0,
},
"name": {
Type: schema.TypeString,
Optional: true,
},
"ports": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"port": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"protocol": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
},
ForceNew: true,
},
"ready": {
Type: schema.TypeBool,
Computed: true,
},
"restart_count": {
Type: schema.TypeInt,
Computed: true,
},
"volume_mounts": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"mount_path": {
Type: schema.TypeString,
Optional: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
},
"read_only": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
},
},
"working_dir": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"instance_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"memory": {
Type: schema.TypeFloat,
Optional: true,
Default: 4,
},
"ram_role_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"restart_policy": {
Type: schema.TypeString,
Optional: true,
Default: "Always",
},
"security_group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
"vswitch_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"volumes": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"config_file_volume_config_file_to_paths": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"content": {
Type: schema.TypeString,
Optional: true,
},
"path": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"disk_volume_disk_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"disk_volume_fs_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"flex_volume_driver": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"flex_volume_fs_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"flex_volume_options": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"nfs_volume_path": {
Type: schema.TypeString,
Optional: true,
},
"nfs_volume_read_only": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"nfs_volume_server": {
Type: schema.TypeString,
Optional: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
},
"type": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"image_registry_credential": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"password": {
Type: schema.TypeString,
Required: true,
},
"server": {
Type: schema.TypeString,
Required: true,
},
"user_name": {
Type: schema.TypeString,
Required: true,
},
},
},
},
},
}
}
func resourceAlicloudEciContainerGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
eciService := EciService{client}
var response map[string]interface{}
action := "CreateContainerGroup"
request := make(map[string]interface{})
conn, err := client.NewEciClient()
if err != nil {
return WrapError(err)
}
request["ContainerGroupName"] = d.Get("container_group_name")
Containers := make([]map[string]interface{}, len(d.Get("containers").(*schema.Set).List()))
for i, ContainersValue := range d.Get("containers").(*schema.Set).List() {
ContainersMap := ContainersValue.(map[string]interface{})
Containers[i] = make(map[string]interface{})
Containers[i]["Arg"] = ContainersMap["args"]
Containers[i]["Command"] = ContainersMap["commands"]
Containers[i]["Cpu"] = ContainersMap["cpu"]
EnvironmentVars := make([]map[string]interface{}, len(ContainersMap["environment_vars"].([]interface{})))
for i, EnvironmentVarsValue := range ContainersMap["environment_vars"].([]interface{}) {
EnvironmentVarsMap := EnvironmentVarsValue.(map[string]interface{})
EnvironmentVars[i] = make(map[string]interface{})
EnvironmentVars[i]["Key"] = EnvironmentVarsMap["key"]
EnvironmentVars[i]["Value"] = EnvironmentVarsMap["value"]
}
Containers[i]["EnvironmentVar"] = EnvironmentVars
Containers[i]["Gpu"] = ContainersMap["gpu"]
Containers[i]["Image"] = ContainersMap["image"]
Containers[i]["ImagePullPolicy"] = ContainersMap["image_pull_policy"]
Containers[i]["Memory"] = ContainersMap["memory"]
Containers[i]["Name"] = ContainersMap["name"]
Ports := make([]map[string]interface{}, len(ContainersMap["ports"].([]interface{})))
for i, PortsValue := range ContainersMap["ports"].([]interface{}) {
PortsMap := PortsValue.(map[string]interface{})
Ports[i] = make(map[string]interface{})
Ports[i]["Port"] = PortsMap["port"]
Ports[i]["Protocol"] = PortsMap["protocol"]
}
Containers[i]["Port"] = Ports
VolumeMounts := make([]map[string]interface{}, len(ContainersMap["volume_mounts"].([]interface{})))
for i, VolumeMountsValue := range ContainersMap["volume_mounts"].([]interface{}) {
VolumeMountsMap := VolumeMountsValue.(map[string]interface{})
VolumeMounts[i] = make(map[string]interface{})
VolumeMounts[i]["MountPath"] = VolumeMountsMap["mount_path"]
VolumeMounts[i]["Name"] = VolumeMountsMap["name"]
}
Containers[i]["VolumeMount"] = VolumeMounts
Containers[i]["WorkingDir"] = ContainersMap["working_dir"]
}
request["Container"] = Containers
if v, ok := d.GetOk("cpu"); ok {
request["Cpu"] = v
}
if v, ok := d.GetOk("dns_config"); ok {
if v != nil {
dnsConfigMap := make(map[string]interface{})
for _, dnsConfig := range v.(*schema.Set).List() {
dnsConfigArg := dnsConfig.(map[string]interface{})
dnsConfigMap["NameServers"] = dnsConfigArg["name_servers"]
if dnsConfigArg["options"] != nil {
optionsMaps := make([]map[string]interface{}, 0)
for _, options := range dnsConfigArg["options"].([]interface{}) {
optionsMap := make(map[string]interface{})
optionsArg := options.(map[string]interface{})
optionsMap["Name"] = optionsArg["name"]
optionsMap["Value"] = optionsArg["value"]
optionsMaps = append(optionsMaps, optionsMap)
}
dnsConfigMap["Options"] = optionsMaps
}
dnsConfigMap["Searches"] = dnsConfigArg["searches"]
}
request["DnsConfig"] = dnsConfigMap
}
}
if v, ok := d.GetOk("eci_security_context"); ok {
if v != nil {
eciSecurityContextMap := make(map[string]interface{})
for _, eciSecurityContext := range v.(*schema.Set).List() {
eciSecurityContextArg := eciSecurityContext.(map[string]interface{})
if eciSecurityContextArg["sysctls"] != nil {
sysctlsMaps := make([]map[string]interface{}, 0)
for _, sysctls := range eciSecurityContextArg["sysctls"].([]interface{}) {
sysctlsMap := make(map[string]interface{})
sysctlsArg := sysctls.(map[string]interface{})
sysctlsMap["Name"] = sysctlsArg["name"]
sysctlsMap["Value"] = sysctlsArg["value"]
sysctlsMaps = append(sysctlsMaps, sysctlsMap)
}
eciSecurityContextMap["Sysctls"] = sysctlsMaps
}
}
request["EciSecurityContext"] = eciSecurityContextMap
}
}
if v, ok := d.GetOk("host_aliases"); ok {
HostAliases := make([]map[string]interface{}, len(v.([]interface{})))
for i, HostAliasesValue := range v.([]interface{}) {
HostAliasesMap := HostAliasesValue.(map[string]interface{})
HostAliases[i] = make(map[string]interface{})
HostAliases[i]["Hostname"] = HostAliasesMap["hostnames"]
HostAliases[i]["Ip"] = HostAliasesMap["ip"]
}
request["HostAliase"] = HostAliases
}
if v, ok := d.GetOk("init_containers"); ok {
InitContainers := make([]map[string]interface{}, len(v.([]interface{})))
for i, InitContainersValue := range v.([]interface{}) {
InitContainersMap := InitContainersValue.(map[string]interface{})
InitContainers[i] = make(map[string]interface{})
InitContainers[i]["Arg"] = InitContainersMap["args"]
InitContainers[i]["Command"] = InitContainersMap["commands"]
InitContainers[i]["Cpu"] = InitContainersMap["cpu"]
EnvironmentVars := make([]map[string]interface{}, len(InitContainersMap["environment_vars"].([]interface{})))
for i, EnvironmentVarsValue := range InitContainersMap["environment_vars"].([]interface{}) {
EnvironmentVarsMap := EnvironmentVarsValue.(map[string]interface{})
EnvironmentVars[i] = make(map[string]interface{})
EnvironmentVars[i]["Key"] = EnvironmentVarsMap["key"]
EnvironmentVars[i]["Value"] = EnvironmentVarsMap["value"]
}
InitContainers[i]["EnvironmentVar"] = EnvironmentVars
InitContainers[i]["Gpu"] = InitContainersMap["gpu"]
InitContainers[i]["Image"] = InitContainersMap["image"]
InitContainers[i]["ImagePullPolicy"] = InitContainersMap["image_pull_policy"]
InitContainers[i]["Memory"] = InitContainersMap["memory"]
InitContainers[i]["Name"] = InitContainersMap["name"]
Ports := make([]map[string]interface{}, len(InitContainersMap["ports"].([]interface{})))
for i, PortsValue := range InitContainersMap["ports"].([]interface{}) {
PortsMap := PortsValue.(map[string]interface{})
Ports[i] = make(map[string]interface{})
Ports[i]["Port"] = PortsMap["port"]
Ports[i]["Protocol"] = PortsMap["protocol"]
}
InitContainers[i]["Port"] = Ports
VolumeMounts := make([]map[string]interface{}, len(InitContainersMap["volume_mounts"].([]interface{})))
for i, VolumeMountsValue := range InitContainersMap["volume_mounts"].([]interface{}) {
VolumeMountsMap := VolumeMountsValue.(map[string]interface{})
VolumeMounts[i] = make(map[string]interface{})
VolumeMounts[i]["MountPath"] = VolumeMountsMap["mount_path"]
VolumeMounts[i]["Name"] = VolumeMountsMap["name"]
}
InitContainers[i]["VolumeMount"] = VolumeMounts
InitContainers[i]["WorkingDir"] = InitContainersMap["working_dir"]
}
request["InitContainer"] = InitContainers
}
if v, ok := d.GetOk("instance_type"); ok {
request["InstanceType"] = v
}
if v, ok := d.GetOk("memory"); ok {
request["Memory"] = v
}
if v, ok := d.GetOk("ram_role_name"); ok {
request["RamRoleName"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("restart_policy"); ok {
request["RestartPolicy"] = v
}
request["SecurityGroupId"] = d.Get("security_group_id")
if v, ok := d.GetOk("tags"); ok {
count := 1
for key, value := range v.(map[string]interface{}) {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
}
if v, ok := d.GetOk("volumes"); ok {
Volumes := make([]map[string]interface{}, len(v.([]interface{})))
for i, VolumesValue := range v.([]interface{}) {
VolumesMap := VolumesValue.(map[string]interface{})
Volumes[i] = make(map[string]interface{})
ConfigFileVolumeConfigFileToPaths := make([]map[string]interface{}, len(VolumesMap["config_file_volume_config_file_to_paths"].([]interface{})))
for i, ConfigFileVolumeConfigFileToPathsValue := range VolumesMap["config_file_volume_config_file_to_paths"].([]interface{}) {
ConfigFileVolumeConfigFileToPathsMap := ConfigFileVolumeConfigFileToPathsValue.(map[string]interface{})
ConfigFileVolumeConfigFileToPaths[i] = make(map[string]interface{})
ConfigFileVolumeConfigFileToPaths[i]["Content"] = ConfigFileVolumeConfigFileToPathsMap["content"]
ConfigFileVolumeConfigFileToPaths[i]["Path"] = ConfigFileVolumeConfigFileToPathsMap["path"]
}
Volumes[i]["ConfigFileVolume.ConfigFileToPath"] = ConfigFileVolumeConfigFileToPaths
Volumes[i]["DiskVolume.DiskId"] = VolumesMap["disk_volume_disk_id"]
Volumes[i]["DiskVolume.FsType"] = VolumesMap["disk_volume_fs_type"]
Volumes[i]["FlexVolume.Driver"] = VolumesMap["flex_volume_driver"]
Volumes[i]["FlexVolume.FsType"] = VolumesMap["flex_volume_fs_type"]
Volumes[i]["FlexVolume.Options"] = VolumesMap["flex_volume_options"]
Volumes[i]["NFSVolume.Path"] = VolumesMap["nfs_volume_path"]
Volumes[i]["NFSVolume.Server"] = VolumesMap["nfs_volume_server"]
Volumes[i]["Name"] = VolumesMap["name"]
Volumes[i]["Type"] = VolumesMap["type"]
}
request["Volume"] = Volumes
}
if v, ok := d.GetOk("zone_id"); ok {
request["ZoneId"] = v
}
vswitchId := Trim(d.Get("vswitch_id").(string))
if vswitchId != "" {
vpcService := VpcService{client}
vsw, err := vpcService.DescribeVSwitch(vswitchId)
if err != nil {
return WrapError(err)
}
request["VSwitchId"] = vswitchId
if request["ZoneId"] == nil {
request["ZoneId"] = vsw.ZoneId
}
}
if v, ok := d.GetOk("image_registry_credential"); ok {
imageRegisryCredentialMaps := make([]map[string]interface{}, 0)
for _, raw := range v.(*schema.Set).List() {
obj := raw.(map[string]interface{})
imageRegisryCredentialMaps = append(imageRegisryCredentialMaps, map[string]interface{}{
"Password": obj["password"],
"Server": obj["server"],
"UserName": obj["user_name"],
})
}
request["ImageRegistryCredential"] = imageRegisryCredentialMaps
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("CreateContainerGroup")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-08-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_eci_container_group", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetId(fmt.Sprint(response["ContainerGroupId"]))
stateConf := BuildStateConf([]string{}, []string{"Running", "Succeeded"}, d.Timeout(schema.TimeoutCreate), 10*time.Second, eciService.EciContainerGroupStateRefreshFunc(d.Id(), []string{"Failed", "ScheduleFailed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudEciContainerGroupRead(d, meta)
}
func resourceAlicloudEciContainerGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
eciService := EciService{client}
object, err := eciService.DescribeEciContainerGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_eci_openapi_container_group eciService.DescribeEciContainerGroup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("container_group_name", object["ContainerGroupName"])
containers := make([]map[string]interface{}, 0)
if containersList, ok := object["Containers"].([]interface{}); ok {
for _, v := range containersList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"args": m1["Args"],
"commands": m1["Commands"],
"cpu": m1["Cpu"],
"gpu": m1["Gpu"],
"image": m1["Image"],
"image_pull_policy": m1["ImagePullPolicy"],
"memory": m1["Memory"],
"name": m1["Name"],
"ready": m1["Ready"],
"restart_count": m1["RestartCount"],
"working_dir": m1["WorkingDir"],
}
if m1["EnvironmentVars"] != nil {
environmentVarsMaps := make([]map[string]interface{}, 0)
for _, environmentVarsValue := range m1["EnvironmentVars"].([]interface{}) {
environmentVars := environmentVarsValue.(map[string]interface{})
environmentVarsMap := map[string]interface{}{
"key": environmentVars["Key"],
"value": environmentVars["Value"],
}
environmentVarsMaps = append(environmentVarsMaps, environmentVarsMap)
}
temp1["environment_vars"] = environmentVarsMaps
}
if m1["Ports"] != nil {
portsMaps := make([]map[string]interface{}, 0)
for _, portsValue := range m1["Ports"].([]interface{}) {
ports := portsValue.(map[string]interface{})
portsMap := map[string]interface{}{
"port": ports["Port"],
"protocol": ports["Protocol"],
}
portsMaps = append(portsMaps, portsMap)
}
temp1["ports"] = portsMaps
}
if m1["VolumeMounts"] != nil {
volumeMountsMaps := make([]map[string]interface{}, 0)
for _, volumeMountsValue := range m1["VolumeMounts"].([]interface{}) {
volumeMounts := volumeMountsValue.(map[string]interface{})
volumeMountsMap := map[string]interface{}{
"mount_path": volumeMounts["MountPath"],
"name": volumeMounts["Name"],
"read_only": volumeMounts["ReadOnly"],
}
volumeMountsMaps = append(volumeMountsMaps, volumeMountsMap)
}
temp1["volume_mounts"] = volumeMountsMaps
}
containers = append(containers, temp1)
}
}
}
if err := d.Set("containers", containers); err != nil {
return WrapError(err)
}
d.Set("cpu", object["Cpu"])
dnsConfigSli := make([]map[string]interface{}, 0)
if len(object["DnsConfig"].(map[string]interface{})) > 0 {
dnsConfig := object["DnsConfig"]
dnsConfigMap := make(map[string]interface{})
dnsConfigMap["name_servers"] = dnsConfig.(map[string]interface{})["NameServers"]
optionsSli := make([]map[string]interface{}, 0)
if len(dnsConfig.(map[string]interface{})["Options"].([]interface{})) > 0 {
for _, options := range dnsConfig.(map[string]interface{})["Options"].([]interface{}) {
optionsMap := make(map[string]interface{})
optionsMap["name"] = options.(map[string]interface{})["Name"]
optionsMap["value"] = options.(map[string]interface{})["Value"]
optionsSli = append(optionsSli, optionsMap)
}
}
dnsConfigMap["options"] = optionsSli
dnsConfigMap["searches"] = dnsConfig.(map[string]interface{})["Searches"]
dnsConfigSli = append(dnsConfigSli, dnsConfigMap)
}
d.Set("dns_config", dnsConfigSli)
eciSecurityContextSli := make([]map[string]interface{}, 0)
if len(object["EciSecurityContext"].(map[string]interface{})) > 0 {
eciSecurityContext := object["EciSecurityContext"]
eciSecurityContextMap := make(map[string]interface{})
sysctlsSli := make([]map[string]interface{}, 0)
if len(eciSecurityContext.(map[string]interface{})["Sysctls"].([]interface{})) > 0 {
for _, sysctls := range eciSecurityContext.(map[string]interface{})["Sysctls"].([]interface{}) {
sysctlsMap := make(map[string]interface{})
sysctlsMap["name"] = sysctls.(map[string]interface{})["Name"]
sysctlsMap["value"] = sysctls.(map[string]interface{})["Value"]
sysctlsSli = append(sysctlsSli, sysctlsMap)
}
}
eciSecurityContextMap["sysctls"] = sysctlsSli
eciSecurityContextSli = append(eciSecurityContextSli, eciSecurityContextMap)
}
d.Set("eci_security_context", eciSecurityContextSli)
hostAliases := make([]map[string]interface{}, 0)
if hostAliasesList, ok := object["HostAliases"].([]interface{}); ok {
for _, v := range hostAliasesList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"hostnames": m1["Hostnames"],
"ip": m1["Ip"],
}
hostAliases = append(hostAliases, temp1)
}
}
}
if err := d.Set("host_aliases", hostAliases); err != nil {
return WrapError(err)
}
initContainers := make([]map[string]interface{}, 0)
if initContainersList, ok := object["InitContainers"].([]interface{}); ok {
for _, v := range initContainersList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"args": m1["Args"],
"commands": m1["Command"],
"cpu": m1["Cpu"],
"gpu": m1["Gpu"],
"image": m1["Image"],
"image_pull_policy": m1["ImagePullPolicy"],
"memory": m1["Memory"],
"name": m1["Name"],
"ready": m1["Ready"],
"restart_count": m1["RestartCount"],
"working_dir": m1["WorkingDir"],
}
if m1["EnvironmentVars"] != nil {
environmentVarsMaps := make([]map[string]interface{}, 0)
for _, environmentVarsValue := range m1["EnvironmentVars"].([]interface{}) {
environmentVars := environmentVarsValue.(map[string]interface{})
environmentVarsMap := map[string]interface{}{
"key": environmentVars["Key"],
"value": environmentVars["Value"],
}
environmentVarsMaps = append(environmentVarsMaps, environmentVarsMap)
}
temp1["environment_vars"] = environmentVarsMaps
}
if m1["Ports"] != nil {
portsMaps := make([]map[string]interface{}, 0)
for _, portsValue := range m1["Ports"].([]interface{}) {
ports := portsValue.(map[string]interface{})
portsMap := map[string]interface{}{
"port": ports["Port"],
"protocol": ports["Protocol"],
}
portsMaps = append(portsMaps, portsMap)
}
temp1["ports"] = portsMaps
}
if m1["VolumeMounts"] != nil {
volumeMountsMaps := make([]map[string]interface{}, 0)
for _, volumeMountsValue := range m1["VolumeMounts"].([]interface{}) {
volumeMounts := volumeMountsValue.(map[string]interface{})
volumeMountsMap := map[string]interface{}{
"mount_path": volumeMounts["MountPath"],
"name": volumeMounts["Name"],
"read_only": volumeMounts["ReadOnly"],
}
volumeMountsMaps = append(volumeMountsMaps, volumeMountsMap)
}
temp1["volume_mounts"] = volumeMountsMaps
}
initContainers = append(initContainers, temp1)
}
}
}
if err := d.Set("init_containers", initContainers); err != nil {
return WrapError(err)
}
d.Set("instance_type", object["InstanceType"])
d.Set("memory", object["Memory"])
d.Set("ram_role_name", object["RamRoleName"])
d.Set("resource_group_id", object["ResourceGroupId"])
d.Set("restart_policy", object["RestartPolicy"])
d.Set("security_group_id", object["SecurityGroupId"])
d.Set("status", object["Status"])
d.Set("tags", tagsToMap(object["Tags"]))
d.Set("vswitch_id", object["VSwitchId"])
volumes := make([]map[string]interface{}, 0)
if volumesList, ok := object["Volumes"].([]interface{}); ok {
for _, v := range volumesList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"disk_volume_disk_id": m1["DiskVolumeDiskId"],
"disk_volume_fs_type": m1["DiskVolumeFsType"],
"flex_volume_driver": m1["FlexVolumeDriver"],
"flex_volume_fs_type": m1["FlexVolumeFsType"],
"flex_volume_options": m1["FlexVolumeOptions"],
"nfs_volume_path": m1["NFSVolumePath"],
"nfs_volume_read_only": m1["NFSVolumeReadOnly"],
"nfs_volume_server": m1["NFSVolumeServer"],
"name": m1["Name"],
"type": m1["Type"],
}
if m1["ConfigFileVolumeConfigFileToPaths"] != nil {
configFileVolumeConfigFileToPathsMaps := make([]map[string]interface{}, 0)
for _, configFileVolumeConfigFileToPathsValue := range m1["ConfigFileVolumeConfigFileToPaths"].([]interface{}) {
configFileVolumeConfigFileToPaths := configFileVolumeConfigFileToPathsValue.(map[string]interface{})
configFileVolumeConfigFileToPathsMap := map[string]interface{}{
"content": configFileVolumeConfigFileToPaths["Content"],
"path": configFileVolumeConfigFileToPaths["Path"],
}
configFileVolumeConfigFileToPathsMaps = append(configFileVolumeConfigFileToPathsMaps, configFileVolumeConfigFileToPathsMap)
}
temp1["config_file_volume_config_file_to_paths"] = configFileVolumeConfigFileToPathsMaps
}
volumes = append(volumes, temp1)
}
}
}
if err := d.Set("volumes", volumes); err != nil {
return WrapError(err)
}
d.Set("zone_id", object["ZoneId"])
return nil
}
func resourceAlicloudEciContainerGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
eciService := EciService{client}
var response map[string]interface{}
update := false
request := map[string]interface{}{
"ContainerGroupId": d.Id(),
}
request["RegionId"] = client.RegionId
if d.HasChange("containers") {
update = true
Containers := make([]map[string]interface{}, len(d.Get("containers").(*schema.Set).List()))
for i, ContainersValue := range d.Get("containers").(*schema.Set).List() {
ContainersMap := ContainersValue.(map[string]interface{})
Containers[i] = make(map[string]interface{})
Containers[i]["Arg"] = ContainersMap["args"]
Containers[i]["Command"] = ContainersMap["commands"]
Containers[i]["Cpu"] = ContainersMap["cpu"]
EnvironmentVars := make([]map[string]interface{}, len(ContainersMap["environment_vars"].([]interface{})))
for i, EnvironmentVarsValue := range ContainersMap["environment_vars"].([]interface{}) {
EnvironmentVarsMap := EnvironmentVarsValue.(map[string]interface{})
EnvironmentVars[i] = make(map[string]interface{})
EnvironmentVars[i]["Key"] = EnvironmentVarsMap["key"]
EnvironmentVars[i]["Value"] = EnvironmentVarsMap["value"]
}
Containers[i]["EnvironmentVar"] = EnvironmentVars
Containers[i]["Gpu"] = ContainersMap["gpu"]
Containers[i]["Image"] = ContainersMap["image"]
Containers[i]["ImagePullPolicy"] = ContainersMap["image_pull_policy"]
Containers[i]["Memory"] = ContainersMap["memory"]
Containers[i]["Name"] = ContainersMap["name"]
Ports := make([]map[string]interface{}, len(ContainersMap["ports"].([]interface{})))
for i, PortsValue := range ContainersMap["ports"].([]interface{}) {
PortsMap := PortsValue.(map[string]interface{})
Ports[i] = make(map[string]interface{})
Ports[i]["Port"] = PortsMap["port"]
Ports[i]["Protocol"] = PortsMap["protocol"]
}
Containers[i]["Port"] = Ports
VolumeMounts := make([]map[string]interface{}, len(ContainersMap["volume_mounts"].([]interface{})))
for i, VolumeMountsValue := range ContainersMap["volume_mounts"].([]interface{}) {
VolumeMountsMap := VolumeMountsValue.(map[string]interface{})
VolumeMounts[i] = make(map[string]interface{})
VolumeMounts[i]["MountPath"] = VolumeMountsMap["mount_path"]
VolumeMounts[i]["Name"] = VolumeMountsMap["name"]
}
Containers[i]["VolumeMount"] = VolumeMounts
Containers[i]["WorkingDir"] = ContainersMap["working_dir"]
}
request["Container"] = Containers
}
if d.HasChange("cpu") {
update = true
request["Cpu"] = d.Get("cpu")
}
if d.HasChange("dns_config") {
update = true
if d.Get("dns_config") != nil {
dnsConfigMap := make(map[string]interface{})
for _, dnsConfig := range d.Get("dns_config").(*schema.Set).List() {
dnsConfigArg := dnsConfig.(map[string]interface{})
dnsConfigMap["NameServers"] = dnsConfigArg["name_servers"]
if dnsConfigArg["options"] != nil {
optionsMaps := make([]map[string]interface{}, 0)
for _, options := range dnsConfigArg["options"].([]interface{}) {
optionsMap := make(map[string]interface{})
optionsArg := options.(map[string]interface{})
optionsMap["Name"] = optionsArg["name"]
optionsMap["Value"] = optionsArg["value"]
optionsMaps = append(optionsMaps, optionsMap)
}
dnsConfigMap["Options"] = optionsMaps
}
dnsConfigMap["Searches"] = dnsConfigArg["searches"]
}
request["DnsConfig"] = dnsConfigMap
}
}
if d.HasChange("init_containers") {
update = true
InitContainers := make([]map[string]interface{}, len(d.Get("init_containers").([]interface{})))
for i, InitContainersValue := range d.Get("init_containers").([]interface{}) {
InitContainersMap := InitContainersValue.(map[string]interface{})
InitContainers[i] = make(map[string]interface{})
InitContainers[i]["Arg"] = InitContainersMap["args"]
InitContainers[i]["Command"] = InitContainersMap["commands"]
InitContainers[i]["Cpu"] = InitContainersMap["cpu"]
EnvironmentVars := make([]map[string]interface{}, len(InitContainersMap["environment_vars"].([]interface{})))
for i, EnvironmentVarsValue := range InitContainersMap["environment_vars"].([]interface{}) {
EnvironmentVarsMap := EnvironmentVarsValue.(map[string]interface{})
EnvironmentVars[i] = make(map[string]interface{})
EnvironmentVars[i]["Key"] = EnvironmentVarsMap["key"]
EnvironmentVars[i]["Value"] = EnvironmentVarsMap["value"]
}
InitContainers[i]["EnvironmentVar"] = EnvironmentVars
InitContainers[i]["Gpu"] = InitContainersMap["gpu"]
InitContainers[i]["Image"] = InitContainersMap["image"]
InitContainers[i]["ImagePullPolicy"] = InitContainersMap["image_pull_policy"]
InitContainers[i]["Memory"] = InitContainersMap["memory"]
InitContainers[i]["Name"] = InitContainersMap["name"]
Ports := make([]map[string]interface{}, len(InitContainersMap["ports"].([]interface{})))
for i, PortsValue := range InitContainersMap["ports"].([]interface{}) {
PortsMap := PortsValue.(map[string]interface{})
Ports[i] = make(map[string]interface{})
Ports[i]["Port"] = PortsMap["port"]
Ports[i]["Protocol"] = PortsMap["protocol"]
}
InitContainers[i]["Port"] = Ports
VolumeMounts := make([]map[string]interface{}, len(InitContainersMap["volume_mounts"].([]interface{})))
for i, VolumeMountsValue := range InitContainersMap["volume_mounts"].([]interface{}) {
VolumeMountsMap := VolumeMountsValue.(map[string]interface{})
VolumeMounts[i] = make(map[string]interface{})
VolumeMounts[i]["MountPath"] = VolumeMountsMap["mount_path"]
VolumeMounts[i]["Name"] = VolumeMountsMap["name"]
}
InitContainers[i]["VolumeMount"] = VolumeMounts
InitContainers[i]["WorkingDir"] = InitContainersMap["working_dir"]
}
request["InitContainer"] = InitContainers
}
if d.HasChange("memory") {
update = true
request["Memory"] = d.Get("memory")
}
if d.HasChange("restart_policy") {
update = true
request["RestartPolicy"] = d.Get("restart_policy")
}
if d.HasChange("tags") {
update = true
count := 1
for key, value := range d.Get("tags").(map[string]interface{}) {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
}
if d.HasChange("volumes") {
update = true
Volumes := make([]map[string]interface{}, len(d.Get("volumes").([]interface{})))
for i, VolumesValue := range d.Get("volumes").([]interface{}) {
VolumesMap := VolumesValue.(map[string]interface{})
Volumes[i] = make(map[string]interface{})
ConfigFileVolumeConfigFileToPaths := make([]map[string]interface{}, len(VolumesMap["config_file_volume_config_file_to_paths"].([]interface{})))
for i, ConfigFileVolumeConfigFileToPathsValue := range VolumesMap["config_file_volume_config_file_to_paths"].([]interface{}) {
ConfigFileVolumeConfigFileToPathsMap := ConfigFileVolumeConfigFileToPathsValue.(map[string]interface{})
ConfigFileVolumeConfigFileToPaths[i] = make(map[string]interface{})
ConfigFileVolumeConfigFileToPaths[i]["Content"] = ConfigFileVolumeConfigFileToPathsMap["content"]
ConfigFileVolumeConfigFileToPaths[i]["Path"] = ConfigFileVolumeConfigFileToPathsMap["path"]
}
Volumes[i]["ConfigFileVolume.ConfigFileToPath"] = ConfigFileVolumeConfigFileToPaths
Volumes[i]["NFSVolume.Path"] = VolumesMap["nfs_volume_path"]
Volumes[i]["NFSVolume.Server"] = VolumesMap["nfs_volume_server"]
Volumes[i]["Name"] = VolumesMap["name"]
Volumes[i]["Type"] = VolumesMap["type"]
}
request["Volume"] = Volumes
}
if d.HasChange("image_registry_credential") {
update = true
if v, ok := d.GetOk("image_registry_credential"); ok {
imageRegisryCredentialMaps := make([]map[string]interface{}, 0)
for _, raw := range v.(*schema.Set).List() {
obj := raw.(map[string]interface{})
imageRegisryCredentialMaps = append(imageRegisryCredentialMaps, map[string]interface{}{
"Password": obj["password"],
"Server": obj["server"],
"UserName": obj["user_name"],
})
}
request["ImageRegistryCredential"] = imageRegisryCredentialMaps
}
}
if update {
action := "UpdateContainerGroup"
conn, err := client.NewEciClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-08-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running", "Succeeded"}, d.Timeout(schema.TimeoutUpdate), 10*time.Second, eciService.EciContainerGroupStateRefreshFunc(d.Id(), []string{"Failed", "ScheduleFailed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudEciContainerGroupRead(d, meta)
}
func resourceAlicloudEciContainerGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteContainerGroup"
var response map[string]interface{}
conn, err := client.NewEciClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ContainerGroupId": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-08-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/eci"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEciImageCache() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEciImageCacheCreate,
Read: resourceAlicloudEciImageCacheRead,
Delete: resourceAlicloudEciImageCacheDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(60 * time.Minute),
},
Schema: map[string]*schema.Schema{
"container_group_id": {
Type: schema.TypeString,
Computed: true,
},
"eip_instance_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"image_cache_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"image_cache_size": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"image_registry_credential": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"password": {
Type: schema.TypeString,
Optional: true,
},
"server": {
Type: schema.TypeString,
Optional: true,
},
"user_name": {
Type: schema.TypeString,
Optional: true,
},
},
},
ForceNew: true,
},
"images": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
ForceNew: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"retention_days": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"security_group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudEciImageCacheCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
eciService := EciService{client}
request := eci.CreateCreateImageCacheRequest()
if v, ok := d.GetOk("eip_instance_id"); ok {
request.EipInstanceId = v.(string)
}
request.ImageCacheName = d.Get("image_cache_name").(string)
if v, ok := d.GetOk("image_cache_size"); ok {
request.ImageCacheSize = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("image_registry_credential"); ok {
imageRegistryCredential := []eci.CreateImageCacheImageRegistryCredential{}
for _, e := range v.(*schema.Set).List() {
password := e.(map[string]interface{})["password"]
server := e.(map[string]interface{})["server"]
userName := e.(map[string]interface{})["user_name"]
imageRegistryCredential = append(imageRegistryCredential, eci.CreateImageCacheImageRegistryCredential{
Password: password.(string),
Server: server.(string),
UserName: userName.(string),
})
}
request.ImageRegistryCredential = &imageRegistryCredential
}
image := expandStringList(d.Get("images").(*schema.Set).List())
request.Image = image
request.RegionId = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request.ResourceGroupId = v.(string)
}
if v, ok := d.GetOk("retention_days"); ok {
request.RetentionDays = requests.NewInteger(v.(int))
}
request.SecurityGroupId = d.Get("security_group_id").(string)
request.VSwitchId = d.Get("vswitch_id").(string)
if v, ok := d.GetOk("zone_id"); ok {
request.ZoneId = v.(string)
}
raw, err := client.WithEciClient(func(eciClient *eci.Client) (interface{}, error) {
return eciClient.CreateImageCache(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_eci_image_cache", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ := raw.(*eci.CreateImageCacheResponse)
d.SetId(fmt.Sprintf("%v", response.ImageCacheId))
stateConf := BuildStateConf([]string{"Preparing", "Creating"}, []string{"Ready"}, d.Timeout(schema.TimeoutCreate), 10*time.Second, eciService.EciImageCacheStateRefreshFunc(d.Id(), []string{"Failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudEciImageCacheRead(d, meta)
}
func resourceAlicloudEciImageCacheRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
eciService := EciService{client}
object, err := eciService.DescribeEciImageCache(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("container_group_id", object.ContainerGroupId)
d.Set("image_cache_name", object.ImageCacheName)
d.Set("images", object.Images)
d.Set("status", object.Status)
return nil
}
func resourceAlicloudEciImageCacheDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := eci.CreateDeleteImageCacheRequest()
request.ImageCacheId = d.Id()
request.RegionId = client.RegionId
raw, err := client.WithEciClient(func(eciClient *eci.Client) (interface{}, error) {
return eciClient.DeleteImageCache(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEciVirtualNode() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEciVirtualNodeCreate,
Read: resourceAlicloudEciVirtualNodeRead,
Update: resourceAlicloudEciVirtualNodeUpdate,
Delete: resourceAlicloudEciVirtualNodeDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"eip_instance_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"enable_public_network": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"kube_config": {
Type: schema.TypeString,
Required: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"security_group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": {
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
},
"taints": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"effect": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"NoSchedule", "NoExecute", "PreferNoSchedule"}, false),
},
"key": {
Type: schema.TypeString,
Optional: true,
},
"value": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"vswitch_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"virtual_node_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile("^[\u4e00-\u9fa5a-zA-Z][\u4e00-\u9fa5a-zA-Z0-9-_:]{1,127}$"), "The length of the name is limited to `2` to `128` characters. It can contain uppercase and lowercase letters, Chinese characters, numbers, half-width colon (:), underscores (_), or hyphens (-), and must start with letters."),
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudEciVirtualNodeCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateVirtualNode"
request := make(map[string]interface{})
conn, err := client.NewEciClient()
if err != nil {
return WrapError(err)
}
request["RegionId"] = client.RegionId
request["VSwitchId"] = d.Get("vswitch_id")
request["KubeConfig"] = d.Get("kube_config")
request["SecurityGroupId"] = d.Get("security_group_id")
if v, ok := d.GetOk("eip_instance_id"); ok {
request["EipInstanceId"] = v
}
if v, ok := d.GetOkExists("enable_public_network"); ok {
request["EnablePublicNetwork"] = v
}
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("tags"); ok {
index := 1
for key, value := range v.(map[string]interface{}) {
request[fmt.Sprintf("Tag.%d.Key", index)] = key
request[fmt.Sprintf("Tag.%d.Value", index)] = value.(string)
index = index + 1
}
}
if m, ok := d.GetOk("taints"); ok {
for k, v := range m.(*schema.Set).List() {
taint := v.(map[string]interface{})
request[fmt.Sprintf("Taint.%d.Key", k+1)] = taint["key"].(string)
request[fmt.Sprintf("Taint.%d.Value", k+1)] = taint["value"].(string)
request[fmt.Sprintf("Taint.%d.Effect", k+1)] = taint["effect"].(string)
}
}
if v, ok := d.GetOk("virtual_node_name"); ok {
request["VirtualNodeName"] = v
}
if v, ok := d.GetOk("zone_id"); ok {
request["ZoneId"] = v
}
request["ClientToken"] = buildClientToken("CreateVirtualNode")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-08-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_eci_virtual_node", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["VirtualNodeId"]))
eciService := EciService{client}
stateConf := BuildStateConf([]string{}, []string{"Ready"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, eciService.EciVirtualNodeStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudEciVirtualNodeRead(d, meta)
}
func resourceAlicloudEciVirtualNodeRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
eciService := EciService{client}
object, err := eciService.DescribeEciVirtualNode(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_eci_virtual_node eciService.DescribeEciVirtualNode Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("resource_group_id", object["ResourceGroupId"])
d.Set("security_group_id", object["SecurityGroupId"])
d.Set("status", object["Status"])
d.Set("vswitch_id", object["VSwitchId"])
d.Set("virtual_node_name", object["VirtualNodeName"])
d.Set("zone_id", object["ZoneId"])
d.Set("tags", tagsToMap(object["Tags"]))
return nil
}
func resourceAlicloudEciVirtualNodeUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return resourceAlicloudEciVirtualNodeRead(d, meta)
}
func resourceAlicloudEciVirtualNodeDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteVirtualNode"
var response map[string]interface{}
conn, err := client.NewEciClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"VirtualNodeId": d.Id(),
}
request["RegionId"] = client.RegionId
request["ClientToken"] = buildClientToken("DeleteVirtualNode")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-08-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEcpKeyPair() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcpKeyPairCreate,
Read: resourceAlicloudEcpKeyPairRead,
Update: resourceAlicloudEcpKeyPairUpdate,
Delete: resourceAlicloudEcpKeyPairDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"key_pair_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"public_key_body": {
Type: schema.TypeString,
Required: true,
},
},
}
}
func resourceAlicloudEcpKeyPairCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "ImportKeyPair"
request := make(map[string]interface{})
conn, err := client.NewCloudphoneClient()
if err != nil {
return WrapError(err)
}
request["KeyPairName"] = d.Get("key_pair_name")
request["PublicKeyBody"] = d.Get("public_key_body")
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-12-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecp_key_pair", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["KeyPairName"]))
return resourceAlicloudEcpKeyPairRead(d, meta)
}
func resourceAlicloudEcpKeyPairRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
cloudphoneService := CloudphoneService{client}
_, err := cloudphoneService.DescribeEcpKeyPair(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecp_key_pair cloudphoneService.DescribeEcpKeyPair Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("key_pair_name", d.Id())
return nil
}
func resourceAlicloudEcpKeyPairUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return resourceAlicloudEcpKeyPairRead(d, meta)
}
func resourceAlicloudEcpKeyPairDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteKeyPairs"
var response map[string]interface{}
conn, err := client.NewCloudphoneClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"KeyPairName": []string{d.Id()},
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-12-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"KeyPairsNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEcsAutoSnapshotPolicy() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcsAutoSnapshotPolicyCreate,
Read: resourceAlicloudEcsAutoSnapshotPolicyRead,
Update: resourceAlicloudEcsAutoSnapshotPolicyUpdate,
Delete: resourceAlicloudEcsAutoSnapshotPolicyDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(2 * time.Minute),
Delete: schema.DefaultTimeout(3 * time.Minute),
},
Schema: map[string]*schema.Schema{
"copied_snapshots_retention_days": {
Type: schema.TypeInt,
Optional: true,
Default: -1,
},
"enable_cross_region_copy": {
Type: schema.TypeBool,
Optional: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
},
"repeat_weekdays": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"retention_days": {
Type: schema.TypeInt,
Required: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
"target_copy_regions": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"time_points": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
}
}
func resourceAlicloudEcsAutoSnapshotPolicyCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
var response map[string]interface{}
action := "CreateAutoSnapshotPolicy"
request := make(map[string]interface{})
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("copied_snapshots_retention_days"); ok {
request["CopiedSnapshotsRetentionDays"] = v
}
if v, ok := d.GetOkExists("enable_cross_region_copy"); ok {
request["EnableCrossRegionCopy"] = v
}
if v, ok := d.GetOk("name"); ok {
request["autoSnapshotPolicyName"] = v
}
request["regionId"] = client.RegionId
request["repeatWeekdays"] = convertListToJsonString(d.Get("repeat_weekdays").(*schema.Set).List())
request["retentionDays"] = d.Get("retention_days")
if v, ok := d.GetOk("tags"); ok {
count := 1
for key, value := range v.(map[string]interface{}) {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
}
if v, ok := d.GetOk("target_copy_regions"); ok {
request["TargetCopyRegions"] = convertListToJsonString(v.(*schema.Set).List())
}
request["timePoints"] = convertListToJsonString(d.Get("time_points").(*schema.Set).List())
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecs_auto_snapshot_policy", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["AutoSnapshotPolicyId"]))
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutCreate), 10*time.Second, ecsService.EcsAutoSnapshotPolicyStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudEcsAutoSnapshotPolicyRead(d, meta)
}
func resourceAlicloudEcsAutoSnapshotPolicyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
object, err := ecsService.DescribeEcsAutoSnapshotPolicy(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecs_auto_snapshot_policy ecsService.DescribeEcsAutoSnapshotPolicy Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("copied_snapshots_retention_days", formatInt(object["CopiedSnapshotsRetentionDays"]))
d.Set("enable_cross_region_copy", object["EnableCrossRegionCopy"])
d.Set("name", object["AutoSnapshotPolicyName"])
if object["RepeatWeekdays"] != nil {
if repeatWeekdays, err := convertJsonStringToList(object["RepeatWeekdays"].(string)); err != nil {
return WrapError(err)
} else {
d.Set("repeat_weekdays", repeatWeekdays)
}
}
d.Set("retention_days", formatInt(object["RetentionDays"]))
d.Set("status", object["Status"])
d.Set("tags", tagsToMap(object["Tags"].(map[string]interface{})["Tag"]))
if object["TargetCopyRegions"] != nil {
if targetCopyRegions, err := convertJsonStringToList(object["TargetCopyRegions"].(string)); err != nil {
return WrapError(err)
} else {
d.Set("target_copy_regions", targetCopyRegions)
}
}
if object["TimePoints"] != nil {
if timePoints, err := convertJsonStringToList(object["TimePoints"].(string)); err != nil {
return WrapError(err)
} else {
d.Set("time_points", timePoints)
}
}
return nil
}
func resourceAlicloudEcsAutoSnapshotPolicyUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
var response map[string]interface{}
d.Partial(true)
if !d.IsNewResource() && d.HasChange("tags") {
if err := ecsService.SetResourceTags(d, "snapshotpolicy"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
update := false
request := map[string]interface{}{
"autoSnapshotPolicyId": d.Id(),
}
request["RegionId"] = client.RegionId
if !d.IsNewResource() && d.HasChange("copied_snapshots_retention_days") {
update = true
request["CopiedSnapshotsRetentionDays"] = d.Get("copied_snapshots_retention_days")
}
if !d.IsNewResource() && d.HasChange("enable_cross_region_copy") {
update = true
request["EnableCrossRegionCopy"] = d.Get("enable_cross_region_copy")
}
if !d.IsNewResource() && d.HasChange("name") {
update = true
request["autoSnapshotPolicyName"] = d.Get("name")
}
if !d.IsNewResource() && d.HasChange("repeat_weekdays") {
update = true
request["repeatWeekdays"] = convertListToJsonString(d.Get("repeat_weekdays").(*schema.Set).List())
}
if !d.IsNewResource() && d.HasChange("retention_days") {
update = true
request["retentionDays"] = d.Get("retention_days")
}
if !d.IsNewResource() && d.HasChange("target_copy_regions") {
update = true
request["TargetCopyRegions"] = convertListToJsonString(d.Get("target_copy_regions").(*schema.Set).List())
}
if !d.IsNewResource() && d.HasChange("time_points") {
update = true
request["timePoints"] = convertListToJsonString(d.Get("time_points").(*schema.Set).List())
}
if update {
action := "ModifyAutoSnapshotPolicyEx"
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("copied_snapshots_retention_days")
d.SetPartial("enable_cross_region_copy")
d.SetPartial("name")
d.SetPartial("repeat_weekdays")
d.SetPartial("retention_days")
d.SetPartial("target_copy_regions")
d.SetPartial("time_points")
}
d.Partial(false)
return resourceAlicloudEcsAutoSnapshotPolicyRead(d, meta)
}
func resourceAlicloudEcsAutoSnapshotPolicyDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteAutoSnapshotPolicy"
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"autoSnapshotPolicyId": d.Id(),
}
request["regionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"InternalError", "OperationConflict", "ServiceUnavailable", "SnapshotCreatedDisk", "SnapshotCreatedImage"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ParameterInvalid"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEcsAutoSnapshotPolicyAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcsAutoSnapshotPolicyAttachmentCreate,
Read: resourceAlicloudEcsAutoSnapshotPolicyAttachmentRead,
Delete: resourceAlicloudEcsAutoSnapshotPolicyAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"auto_snapshot_policy_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"disk_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudEcsAutoSnapshotPolicyAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "ApplyAutoSnapshotPolicy"
request := make(map[string]interface{})
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
request["autoSnapshotPolicyId"] = d.Get("auto_snapshot_policy_id")
request["diskIds"] = convertListToJsonString([]interface{}{d.Get("disk_id")})
request["regionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecs_auto_snapshot_policy_attachment", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["autoSnapshotPolicyId"], ":", d.Get("disk_id")))
return resourceAlicloudEcsAutoSnapshotPolicyAttachmentRead(d, meta)
}
func resourceAlicloudEcsAutoSnapshotPolicyAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
_, err := ecsService.DescribeEcsAutoSnapshotPolicyAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecs_auto_snapshot_policy_attachment ecsService.DescribeEcsAutoSnapshotPolicyAttachment Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
d.Set("auto_snapshot_policy_id", parts[0])
d.Set("disk_id", parts[1])
return nil
}
func resourceAlicloudEcsAutoSnapshotPolicyAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "CancelAutoSnapshotPolicy"
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"diskIds": convertListToJsonString([]interface{}{parts[1]}),
}
request["regionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDiskId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudEcsCommand() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcsCommandCreate,
Read: resourceAlicloudEcsCommandRead,
Delete: resourceAlicloudEcsCommandDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"command_content": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"enable_parameter": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: false,
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"timeout": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Default: 60,
},
"type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"RunBatScript", "RunPowerShellScript", "RunShellScript"}, false),
},
"working_dir": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudEcsCommandCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateCommand"
request := make(map[string]interface{})
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
request["CommandContent"] = d.Get("command_content")
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOkExists("enable_parameter"); ok {
request["EnableParameter"] = v
}
request["Name"] = d.Get("name")
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("timeout"); ok {
request["Timeout"] = v
}
request["Type"] = d.Get("type")
if v, ok := d.GetOk("working_dir"); ok {
request["WorkingDir"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecs_command", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["CommandId"]))
return resourceAlicloudEcsCommandRead(d, meta)
}
func resourceAlicloudEcsCommandRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
object, err := ecsService.DescribeEcsCommand(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecs_command ecsService.DescribeEcsCommand Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("command_content", object["CommandContent"])
d.Set("description", object["Description"])
d.Set("enable_parameter", object["EnableParameter"])
d.Set("name", object["Name"])
d.Set("timeout", object["Timeout"])
d.Set("type", object["Type"])
d.Set("working_dir", object["WorkingDir"])
return nil
}
func resourceAlicloudEcsCommandDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteCommand"
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"CommandId": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidCmdId.NotFound", "InvalidRegionId.NotFound", "Operation.Forbidden"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudEcsDedicatedHost() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcsDedicatedHostCreate,
Read: resourceAlicloudEcsDedicatedHostRead,
Update: resourceAlicloudEcsDedicatedHostUpdate,
Delete: resourceAlicloudEcsDedicatedHostDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(11 * time.Minute),
Delete: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(11 * time.Minute),
},
Schema: map[string]*schema.Schema{
"action_on_maintenance": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Stop", "Migrate"}, false),
Default: "Stop",
},
"auto_placement": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"off", "on"}, false),
Default: "on",
},
"auto_release_time": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"auto_renew": {
Type: schema.TypeBool,
Optional: true,
},
"auto_renew_period": {
Type: schema.TypeInt,
Optional: true,
},
"cpu_over_commit_ratio": {
Type: schema.TypeFloat,
Optional: true,
},
"dedicated_host_cluster_id": {
Type: schema.TypeString,
Optional: true,
},
"dedicated_host_name": {
Type: schema.TypeString,
Optional: true,
},
"dedicated_host_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"detail_fee": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"expired_time": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"min_quantity": {
Type: schema.TypeInt,
Optional: true,
},
"network_attributes": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"udp_timeout": {
Type: schema.TypeInt,
Optional: true,
},
"slb_udp_timeout": {
Type: schema.TypeInt,
Optional: true,
},
},
},
},
"payment_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"PostPaid", "PrePaid"}, false),
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"sale_cycle": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
"zone_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudEcsDedicatedHostCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
var response map[string]interface{}
action := "AllocateDedicatedHosts"
request := make(map[string]interface{})
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("action_on_maintenance"); ok {
request["ActionOnMaintenance"] = v
}
if v, ok := d.GetOk("auto_placement"); ok {
request["AutoPlacement"] = v
}
if v, ok := d.GetOk("auto_release_time"); ok {
request["AutoReleaseTime"] = v
}
if v, ok := d.GetOkExists("auto_renew"); ok {
request["AutoRenew"] = v
}
if v, ok := d.GetOk("auto_renew_period"); ok {
request["AutoRenewPeriod"] = v
}
if v, ok := d.GetOk("cpu_over_commit_ratio"); ok {
request["CpuOverCommitRatio"] = v
}
if v, ok := d.GetOk("dedicated_host_cluster_id"); ok {
request["DedicatedHostClusterId"] = v
}
if v, ok := d.GetOk("dedicated_host_name"); ok {
request["DedicatedHostName"] = v
}
request["DedicatedHostType"] = d.Get("dedicated_host_type")
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("expired_time"); ok {
request["Period"] = v
}
if v, ok := d.GetOk("min_quantity"); ok {
request["MinQuantity"] = v
}
if v, ok := d.GetOk("network_attributes"); ok {
networkAttributesMap := make(map[string]interface{})
for _, networkAttributes := range v.(*schema.Set).List() {
networkAttributesArg := networkAttributes.(map[string]interface{})
networkAttributesMap["SlbUdpTimeout"] = requests.NewInteger(networkAttributesArg["slb_udp_timeout"].(int))
networkAttributesMap["UdpTimeout"] = requests.NewInteger(networkAttributesArg["udp_timeout"].(int))
}
request["NetworkAttributes"] = networkAttributesMap
}
if v, ok := d.GetOk("payment_type"); ok {
request["ChargeType"] = v
}
request["Quantity"] = 1
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("sale_cycle"); ok {
request["PeriodUnit"] = v
}
if v, ok := d.GetOk("tags"); ok {
count := 1
for key, value := range v.(map[string]interface{}) {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
}
if v, ok := d.GetOk("zone_id"); ok {
request["ZoneId"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecs_dedicated_host", action, AlibabaCloudSdkGoERROR)
}
responseDedicatedHostIdSets := response["DedicatedHostIdSets"].(map[string]interface{})
d.SetId(fmt.Sprint(responseDedicatedHostIdSets["DedicatedHostId"].([]interface{})[0]))
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 15*time.Second, ecsService.EcsDedicatedHostStateRefreshFunc(d.Id(), []string{"PermanentFailure"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudEcsDedicatedHostRead(d, meta)
}
func resourceAlicloudEcsDedicatedHostRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
object, err := ecsService.DescribeEcsDedicatedHost(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecs_dedicated_host ecsService.DescribeEcsDedicatedHost Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("action_on_maintenance", object["ActionOnMaintenance"])
d.Set("auto_placement", object["AutoPlacement"])
d.Set("auto_release_time", object["AutoReleaseTime"])
d.Set("cpu_over_commit_ratio", object["CpuOverCommitRatio"])
d.Set("dedicated_host_name", object["DedicatedHostName"])
d.Set("dedicated_host_type", object["DedicatedHostType"])
d.Set("description", object["Description"])
networkAttributesSli := make([]map[string]interface{}, 0)
if len(object["NetworkAttributes"].(map[string]interface{})) > 0 {
networkAttributes := object["NetworkAttributes"]
networkAttributesMap := make(map[string]interface{})
networkAttributesMap["slb_udp_timeout"] = networkAttributes.(map[string]interface{})["SlbUdpTimeout"]
networkAttributesMap["udp_timeout"] = networkAttributes.(map[string]interface{})["UdpTimeout"]
networkAttributesSli = append(networkAttributesSli, networkAttributesMap)
}
d.Set("network_attributes", networkAttributesSli)
d.Set("payment_type", object["ChargeType"])
d.Set("resource_group_id", object["ResourceGroupId"])
d.Set("sale_cycle", object["SaleCycle"])
d.Set("status", object["Status"])
if v, ok := object["Tags"].(map[string]interface{}); ok {
d.Set("tags", tagsToMap(v["Tag"]))
}
d.Set("zone_id", object["ZoneId"])
return nil
}
func resourceAlicloudEcsDedicatedHostUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
var response map[string]interface{}
d.Partial(true)
if !d.IsNewResource() && d.HasChange("tags") {
if err := ecsService.SetResourceTags(d, "ddh"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
if !d.IsNewResource() && d.HasChange("auto_release_time") {
request := map[string]interface{}{
"DedicatedHostId": d.Id(),
}
request["RegionId"] = client.RegionId
request["AutoReleaseTime"] = d.Get("auto_release_time")
action := "ModifyDedicatedHostAutoReleaseTime"
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, ecsService.EcsDedicatedHostStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("auto_release_time")
}
if !d.IsNewResource() && d.HasChange("resource_group_id") {
request := map[string]interface{}{
"ResourceId": d.Id(),
}
request["RegionId"] = client.RegionId
request["ResourceGroupId"] = d.Get("resource_group_id")
request["ResourceType"] = "ddh"
action := "JoinResourceGroup"
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, ecsService.EcsDedicatedHostStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("resource_group_id")
}
update := false
request := map[string]interface{}{
"DedicatedHostIds": convertListToJsonString(convertListStringToListInterface([]string{d.Id()})),
}
if !d.IsNewResource() && d.HasChange("expired_time") {
update = true
request["Period"] = d.Get("expired_time")
}
request["RegionId"] = client.RegionId
if !d.IsNewResource() && d.HasChange("sale_cycle") {
update = true
request["PeriodUnit"] = d.Get("sale_cycle")
}
if update {
action := "RenewDedicatedHosts"
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, ecsService.EcsDedicatedHostStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("expired_time")
d.SetPartial("sale_cycle")
}
update = false
modifyDedicatedHostsChargeTypeReq := map[string]interface{}{
"DedicatedHostIds": convertListToJsonString(convertListStringToListInterface([]string{d.Id()})),
}
modifyDedicatedHostsChargeTypeReq["RegionId"] = client.RegionId
modifyDedicatedHostsChargeTypeReq["AutoPay"] = true
modifyDedicatedHostsChargeTypeReq["Period"] = d.Get("expired_time")
if !d.IsNewResource() && d.HasChange("payment_type") {
update = true
modifyDedicatedHostsChargeTypeReq["DedicatedHostChargeType"] = d.Get("payment_type")
}
modifyDedicatedHostsChargeTypeReq["PeriodUnit"] = d.Get("sale_cycle")
if update {
if _, ok := d.GetOkExists("detail_fee"); ok {
modifyDedicatedHostsChargeTypeReq["DetailFee"] = d.Get("detail_fee")
}
if _, ok := d.GetOkExists("dry_run"); ok {
modifyDedicatedHostsChargeTypeReq["DryRun"] = d.Get("dry_run")
}
action := "ModifyDedicatedHostsChargeType"
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, modifyDedicatedHostsChargeTypeReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, modifyDedicatedHostsChargeTypeReq)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 10*time.Second, ecsService.EcsDedicatedHostStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("detail_fee")
d.SetPartial("dry_run")
d.SetPartial("expired_time")
d.SetPartial("payment_type")
d.SetPartial("sale_cycle")
}
update = false
modifyDedicatedHostAttributeReq := map[string]interface{}{
"DedicatedHostId": d.Id(),
}
modifyDedicatedHostAttributeReq["RegionId"] = client.RegionId
if !d.IsNewResource() && d.HasChange("action_on_maintenance") {
update = true
modifyDedicatedHostAttributeReq["ActionOnMaintenance"] = d.Get("action_on_maintenance")
}
if !d.IsNewResource() && d.HasChange("auto_placement") {
update = true
modifyDedicatedHostAttributeReq["AutoPlacement"] = d.Get("auto_placement")
}
if !d.IsNewResource() && d.HasChange("cpu_over_commit_ratio") {
update = true
modifyDedicatedHostAttributeReq["CpuOverCommitRatio"] = d.Get("cpu_over_commit_ratio")
}
if !d.IsNewResource() && d.HasChange("dedicated_host_name") {
update = true
modifyDedicatedHostAttributeReq["DedicatedHostName"] = d.Get("dedicated_host_name")
}
if !d.IsNewResource() && d.HasChange("description") {
update = true
modifyDedicatedHostAttributeReq["Description"] = d.Get("description")
}
if !d.IsNewResource() && d.HasChange("network_attributes") {
update = true
if d.Get("network_attributes") != nil {
networkAttributesMap := make(map[string]interface{})
for _, networkAttributes := range d.Get("network_attributes").(*schema.Set).List() {
networkAttributesArg := networkAttributes.(map[string]interface{})
networkAttributesMap["SlbUdpTimeout"] = requests.NewInteger(networkAttributesArg["slb_udp_timeout"].(int))
networkAttributesMap["UdpTimeout"] = requests.NewInteger(networkAttributesArg["udp_timeout"].(int))
}
modifyDedicatedHostAttributeReq["NetworkAttributes"] = networkAttributesMap
}
}
if update {
if _, ok := d.GetOk("dedicated_host_cluster_id"); ok {
modifyDedicatedHostAttributeReq["DedicatedHostClusterId"] = d.Get("dedicated_host_cluster_id")
}
action := "ModifyDedicatedHostAttribute"
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, modifyDedicatedHostAttributeReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, modifyDedicatedHostAttributeReq)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, ecsService.EcsDedicatedHostStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("action_on_maintenance")
d.SetPartial("auto_placement")
d.SetPartial("cpu_over_commit_ratio")
d.SetPartial("dedicated_host_cluster_id")
d.SetPartial("dedicated_host_name")
d.SetPartial("description")
d.SetPartial("network_attributes")
}
d.Partial(false)
return resourceAlicloudEcsDedicatedHostRead(d, meta)
}
func resourceAlicloudEcsDedicatedHostDelete(d *schema.ResourceData, meta interface{}) error {
if d.Get("payment_type").(string) == "PrePaid" {
log.Printf("[WARN] Cannot destroy Subscription resource: alicloud_ecs_dedicated_host. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
client := meta.(*connectivity.AliyunClient)
action := "ReleaseDedicatedHost"
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DedicatedHostId": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectHostStatus.Initializing"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDedicatedHostId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEcsDedicatedHostCluster() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcsDedicatedHostClusterCreate,
Read: resourceAlicloudEcsDedicatedHostClusterRead,
Update: resourceAlicloudEcsDedicatedHostClusterUpdate,
Delete: resourceAlicloudEcsDedicatedHostClusterDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"dedicated_host_cluster_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9_\-.]{1,127}$`), "The reason must be 2 to 128 characters in length, and must start with a letter. It can contain digits, periods (.), underscores (_), and hyphens (-)."),
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"tags": tagsSchema(),
"zone_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudEcsDedicatedHostClusterCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateDedicatedHostCluster"
request := make(map[string]interface{})
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("dedicated_host_cluster_name"); ok {
request["DedicatedHostClusterName"] = v
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("tags"); ok {
count := 1
for key, value := range v.(map[string]interface{}) {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
}
request["ZoneId"] = d.Get("zone_id")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecs_dedicated_host_cluster", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["DedicatedHostClusterId"]))
return resourceAlicloudEcsDedicatedHostClusterRead(d, meta)
}
func resourceAlicloudEcsDedicatedHostClusterRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
object, err := ecsService.DescribeEcsDedicatedHostCluster(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecs_dedicated_host_cluster ecsService.DescribeEcsDedicatedHostCluster Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("dedicated_host_cluster_name", object["DedicatedHostClusterName"])
d.Set("description", object["Description"])
if v, ok := object["Tags"].(map[string]interface{}); ok {
d.Set("tags", tagsToMap(v["Tag"]))
}
d.Set("zone_id", object["ZoneId"])
return nil
}
func resourceAlicloudEcsDedicatedHostClusterUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
update := false
request := map[string]interface{}{
"DedicatedHostClusterId": d.Id(),
}
request["RegionId"] = client.RegionId
if d.HasChange("tags") {
if err := ecsService.SetResourceTags(d, "ddhcluster"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
if d.HasChange("dedicated_host_cluster_name") {
update = true
if v, ok := d.GetOk("dedicated_host_cluster_name"); ok {
request["DedicatedHostClusterName"] = v
}
}
if d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
}
if update {
action := "ModifyDedicatedHostClusterAttribute"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudEcsDedicatedHostClusterRead(d, meta)
}
func resourceAlicloudEcsDedicatedHostClusterDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteDedicatedHostCluster"
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DedicatedHostClusterId": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudEcsDeploymentSet() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcsDeploymentSetCreate,
Read: resourceAlicloudEcsDeploymentSetRead,
Update: resourceAlicloudEcsDeploymentSetUpdate,
Delete: resourceAlicloudEcsDeploymentSetDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"deployment_set_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^([\w\\:\-]){2,128}$`), "\t\nThe name of the deployment set.\n\nThe name must be 2 to 128 characters in length and can contain letters, digits, colons (:), underscores (_), and hyphens (-)."),
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"domain": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Default"}, false),
},
"granularity": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Host"}, false),
},
"on_unable_to_redeploy_failed_instance": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"CancelMembershipAndStart", "KeepStopped"}, false),
},
"strategy": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Availability"}, false),
},
},
}
}
func resourceAlicloudEcsDeploymentSetCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateDeploymentSet"
request := make(map[string]interface{})
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("deployment_set_name"); ok {
request["DeploymentSetName"] = v
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("domain"); ok {
request["Domain"] = v
}
if v, ok := d.GetOk("granularity"); ok {
request["Granularity"] = v
}
if v, ok := d.GetOk("on_unable_to_redeploy_failed_instance"); ok {
request["OnUnableToRedeployFailedInstance"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("strategy"); ok {
request["Strategy"] = v
}
request["ClientToken"] = buildClientToken("CreateDeploymentSet")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecs_deployment_set", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["DeploymentSetId"]))
return resourceAlicloudEcsDeploymentSetRead(d, meta)
}
func resourceAlicloudEcsDeploymentSetRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
object, err := ecsService.DescribeEcsDeploymentSet(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecs_deployment_set ecsService.DescribeEcsDeploymentSet Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("domain", convertEcsDeploymentSetDomainResponse(object["Domain"]))
d.Set("granularity", convertEcsDeploymentSetGranularityResponse(object["Granularity"]))
d.Set("deployment_set_name", object["DeploymentSetName"])
d.Set("description", object["DeploymentSetDescription"])
d.Set("strategy", object["DeploymentStrategy"])
return nil
}
func resourceAlicloudEcsDeploymentSetUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
update := false
request := map[string]interface{}{
"DeploymentSetId": d.Id(),
}
request["RegionId"] = client.RegionId
if d.HasChange("deployment_set_name") {
update = true
if v, ok := d.GetOk("deployment_set_name"); ok {
request["DeploymentSetName"] = v
}
}
if d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
}
if update {
action := "ModifyDeploymentSetAttribute"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudEcsDeploymentSetRead(d, meta)
}
func resourceAlicloudEcsDeploymentSetDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteDeploymentSet"
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DeploymentSetId": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func convertEcsDeploymentSetDomainResponse(source interface{}) interface{} {
switch source {
case "default":
return "Default"
}
return source
}
func convertEcsDeploymentSetGranularityResponse(source interface{}) interface{} {
switch source {
case "host":
return "Host"
}
return source
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudEcsDisk() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcsDiskCreate,
Read: resourceAlicloudEcsDiskRead,
Update: resourceAlicloudEcsDiskUpdate,
Delete: resourceAlicloudEcsDiskDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(2 * time.Minute),
Delete: schema.DefaultTimeout(2 * time.Minute),
Update: schema.DefaultTimeout(6 * time.Minute),
},
Schema: map[string]*schema.Schema{
"advanced_features": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"category": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"cloud", "cloud_efficiency", "cloud_essd", "cloud_ssd"}, false),
Default: "cloud_efficiency",
},
"dedicated_block_storage_cluster_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"delete_auto_snapshot": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"delete_with_instance": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"disk_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringLenBetween(2, 128),
ConflictsWith: []string{"name"},
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringLenBetween(2, 128),
Deprecated: "Field 'name' has been deprecated from provider version 1.122.0. New field 'disk_name' instead.",
ConflictsWith: []string{"disk_name"},
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"enable_auto_snapshot": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"encrypt_algorithm": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"encrypted": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
ConflictsWith: []string{"snapshot_id"},
},
"instance_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"kms_key_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"payment_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo", "Subscription"}, false),
},
"performance_level": {
Type: schema.TypeString,
Optional: true,
Computed: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("category").(string) != "cloud_essd"
},
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
},
"size": {
Type: schema.TypeInt,
Optional: true,
},
"snapshot_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ConflictsWith: []string{"encrypted"},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"storage_set_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"storage_set_partition_number": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"tags": tagsSchema(),
"type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"offline", "online"}, false),
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"availability_zone"},
},
"availability_zone": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Deprecated: "Field 'availability_zone' has been deprecated from provider version 1.122.0. New field 'zone_id' instead",
ConflictsWith: []string{"zone_id"},
},
},
}
}
func resourceAlicloudEcsDiskCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
var response map[string]interface{}
action := "CreateDisk"
request := make(map[string]interface{})
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("advanced_features"); ok {
request["AdvancedFeatures"] = v
}
if v, ok := d.GetOk("category"); ok {
request["DiskCategory"] = v
}
if v, ok := d.GetOk("dedicated_block_storage_cluster_id"); ok {
request["DedicatedBlockStorageClusterId"] = v
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("disk_name"); ok {
request["DiskName"] = v
} else if v, ok := d.GetOk("name"); ok {
request["DiskName"] = v
}
if v, ok := d.GetOk("encrypt_algorithm"); ok {
request["EncryptAlgorithm"] = v
}
if v, ok := d.GetOkExists("encrypted"); ok {
request["Encrypted"] = v
}
if v, ok := d.GetOk("instance_id"); ok {
request["InstanceId"] = v
}
if v, ok := d.GetOk("kms_key_id"); ok {
request["KMSKeyId"] = v
}
if v, ok := d.GetOk("performance_level"); ok {
request["PerformanceLevel"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("size"); ok {
request["Size"] = v
}
if v, ok := d.GetOk("snapshot_id"); ok {
request["SnapshotId"] = v
}
if v, ok := d.GetOk("storage_set_id"); ok {
request["StorageSetId"] = v
}
if v, ok := d.GetOk("storage_set_partition_number"); ok {
request["StorageSetPartitionNumber"] = v
}
if v, ok := d.GetOk("tags"); ok {
count := 1
for key, value := range v.(map[string]interface{}) {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
}
if v, ok := d.GetOk("zone_id"); ok {
request["ZoneId"] = v
} else if v, ok := d.GetOk("availability_zone"); ok {
request["ZoneId"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecs_disk", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["DiskId"]))
stateConf := BuildStateConf([]string{}, []string{"Available", "In_use"}, d.Timeout(schema.TimeoutCreate), 10*time.Second, ecsService.EcsDiskStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudEcsDiskUpdate(d, meta)
}
func resourceAlicloudEcsDiskRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
object, err := ecsService.DescribeEcsDisk(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecs_disk ecsService.DescribeEcsDisk Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("category", object["Category"])
d.Set("delete_auto_snapshot", object["DeleteAutoSnapshot"])
d.Set("delete_with_instance", object["DeleteWithInstance"])
d.Set("description", object["Description"])
d.Set("disk_name", object["DiskName"])
d.Set("name", object["DiskName"])
d.Set("enable_auto_snapshot", object["EnableAutoSnapshot"])
d.Set("encrypted", object["Encrypted"])
d.Set("instance_id", object["InstanceId"])
d.Set("kms_key_id", object["KMSKeyId"])
d.Set("payment_type", convertEcsDiskPaymentTypeResponse(object["DiskChargeType"]))
d.Set("performance_level", object["PerformanceLevel"])
d.Set("resource_group_id", object["ResourceGroupId"])
d.Set("size", formatInt(object["Size"]))
d.Set("snapshot_id", object["SourceSnapshotId"])
d.Set("status", object["Status"])
if v, ok := object["Tags"].(map[string]interface{}); ok {
d.Set("tags", tagsToMap(v["Tag"]))
}
d.Set("zone_id", object["ZoneId"])
d.Set("availability_zone", object["ZoneId"])
return nil
}
func resourceAlicloudEcsDiskUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
var response map[string]interface{}
d.Partial(true)
if !d.IsNewResource() && d.HasChange("tags") {
if err := ecsService.SetResourceTags(d, "disk"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
if !d.IsNewResource() && d.HasChange("size") {
request := map[string]interface{}{
"DiskId": d.Id(),
}
request["NewSize"] = d.Get("size")
if _, ok := d.GetOk("type"); ok {
request["Type"] = d.Get("type")
}
action := "ResizeDisk"
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("ResizeDisk")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("size")
d.SetPartial("type")
}
if !d.IsNewResource() && d.HasChange("resource_group_id") {
request := map[string]interface{}{
"ResourceId": d.Id(),
}
request["RegionId"] = client.RegionId
request["ResourceGroupId"] = d.Get("resource_group_id")
request["ResourceType"] = "disk"
action := "JoinResourceGroup"
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("resource_group_id")
}
update := false
request := map[string]interface{}{
"DiskId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("category") {
update = true
request["DiskCategory"] = d.Get("category")
}
if !d.IsNewResource() && d.HasChange("performance_level") {
update = true
request["PerformanceLevel"] = d.Get("performance_level")
}
if update {
if _, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = d.Get("dry_run")
}
action := "ModifyDiskSpec"
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available", "In_use"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, ecsService.EcsDiskStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("category")
d.SetPartial("dry_run")
d.SetPartial("performance_level")
}
update = false
modifyDiskChargeTypeReq := map[string]interface{}{
"DiskIds": convertListToJsonString([]interface{}{d.Id()}),
}
if !d.IsNewResource() && d.HasChange("instance_id") {
update = true
}
modifyDiskChargeTypeReq["ClientToken"] = buildClientToken("ModifyDiskChargeType")
modifyDiskChargeTypeReq["InstanceId"] = d.Get("instance_id")
modifyDiskChargeTypeReq["RegionId"] = client.RegionId
modifyDiskChargeTypeReq["AutoPay"] = true
if d.HasChange("payment_type") && (d.Get("payment_type").(string) == "Subscription" || !d.IsNewResource()) {
update = true
modifyDiskChargeTypeReq["DiskChargeType"] = convertEcsDiskPaymentTypeRequest(d.Get("payment_type").(string))
}
if update {
action := "ModifyDiskChargeType"
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, modifyDiskChargeTypeReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, modifyDiskChargeTypeReq)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("instance_id")
d.SetPartial("payment_type")
}
update = false
modifyDiskAttributeReq := map[string]interface{}{
"DiskId": d.Id(),
}
if d.HasChange("delete_auto_snapshot") || d.IsNewResource() {
update = true
modifyDiskAttributeReq["DeleteAutoSnapshot"] = d.Get("delete_auto_snapshot")
}
if d.HasChange("delete_with_instance") || d.IsNewResource() {
update = true
modifyDiskAttributeReq["DeleteWithInstance"] = d.Get("delete_with_instance")
}
if !d.IsNewResource() && d.HasChange("description") {
update = true
modifyDiskAttributeReq["Description"] = d.Get("description")
}
if !d.IsNewResource() && d.HasChange("disk_name") {
update = true
modifyDiskAttributeReq["DiskName"] = d.Get("disk_name")
}
if !d.IsNewResource() && d.HasChange("name") {
update = true
modifyDiskAttributeReq["DiskName"] = d.Get("name")
}
if d.HasChange("enable_auto_snapshot") || d.IsNewResource() {
update = true
modifyDiskAttributeReq["EnableAutoSnapshot"] = d.Get("enable_auto_snapshot")
}
if update {
action := "ModifyDiskAttribute"
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, modifyDiskAttributeReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, modifyDiskAttributeReq)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("delete_auto_snapshot")
d.SetPartial("delete_with_instance")
d.SetPartial("description")
d.SetPartial("name")
d.SetPartial("disk_name")
d.SetPartial("enable_auto_snapshot")
}
d.Partial(false)
return resourceAlicloudEcsDiskRead(d, meta)
}
func resourceAlicloudEcsDiskDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteDisk"
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DiskId": d.Id(),
}
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectDiskStatus.Initializing"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDiskId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func convertEcsDiskPaymentTypeResponse(source interface{}) interface{} {
switch source {
case "PostPaid":
return "PayAsYouGo"
case "PrePaid":
return "Subscription"
}
return source
}
func convertEcsDiskPaymentTypeRequest(source interface{}) interface{} {
switch source {
case "PayAsYouGo":
return "PostPaid"
case "Subscription":
return "PrePaid"
}
return source
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEcsDiskAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcsDiskAttachmentCreate,
Read: resourceAlicloudEcsDiskAttachmentRead,
Update: resourceAlicloudEcsDiskAttachmentUpdate,
Delete: resourceAlicloudEcsDiskAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(2 * time.Minute),
Delete: schema.DefaultTimeout(2 * time.Minute),
},
Schema: map[string]*schema.Schema{
"bootable": {
Type: schema.TypeBool,
Optional: true,
Default: false,
ForceNew: true,
},
"delete_with_instance": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"device": {
Type: schema.TypeString,
Computed: true,
},
"disk_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"key_pair_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"password": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudEcsDiskAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AttachDisk"
request := make(map[string]interface{})
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("bootable"); ok {
request["Bootable"] = v
}
if v, ok := d.GetOkExists("delete_with_instance"); ok {
request["DeleteWithInstance"] = v
}
request["DiskId"] = d.Get("disk_id")
request["InstanceId"] = d.Get("instance_id")
if v, ok := d.GetOk("key_pair_name"); ok {
request["KeyPairName"] = v
}
if v, ok := d.GetOk("password"); ok {
request["Password"] = v
}
ecsService := EcsService{client}
oldDisk, err := ecsService.DescribeEcsDisk(d.Get("disk_id").(string))
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) || IsExpectedErrors(err, DiskInvalidOperation) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecs_disk_attachment", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["DiskId"], ":", request["InstanceId"]))
parts, err := ParseResourceId(d.Id(), 2)
stateConf := BuildStateConf([]string{}, []string{"In_use"}, d.Timeout(schema.TimeoutCreate), 10*time.Second, ecsService.EcsDiskStateRefreshFunc(parts[0], []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
newDisk, err := ecsService.DescribeEcsDisk(d.Get("disk_id").(string))
if err != nil {
return WrapError(err)
}
if newDisk["DeleteAutoSnapshot"].(bool) != oldDisk["DeleteAutoSnapshot"].(bool) {
action := "ModifyDiskAttribute"
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DiskId": d.Get("disk_id"),
}
request["RegionId"] = client.RegionId
request["DeleteAutoSnapshot"] = oldDisk["DeleteAutoSnapshot"]
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudEcsDiskAttachmentRead(d, meta)
}
func resourceAlicloudEcsDiskAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
disk, err := ecsService.DescribeEcsDiskAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_id", disk["InstanceId"])
d.Set("disk_id", disk["DiskId"])
d.Set("device", disk["Device"])
return nil
}
func resourceAlicloudEcsDiskAttachmentUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return resourceAlicloudEcsDiskAttachmentRead(d, meta)
}
func resourceAlicloudEcsDiskAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DetachDisk"
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DiskId": parts[0],
"InstanceId": parts[1],
}
if v, ok := d.GetOkExists("delete_with_instance"); ok {
request["DeleteWithInstance"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) || IsExpectedErrors(err, DiskInvalidOperation) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDisk.AlreadyDetached", "InvalidDiskId.NotFound", "InvalidDiskId.OperationNotSupported", "InvalidInstanceId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
ecsService := EcsService{client}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutDelete), 10*time.Second, ecsService.EcsDiskStateRefreshFunc(parts[0], []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEcsHpcCluster() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcsHpcClusterCreate,
Read: resourceAlicloudEcsHpcClusterRead,
Update: resourceAlicloudEcsHpcClusterUpdate,
Delete: resourceAlicloudEcsHpcClusterDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
},
"name": {
Type: schema.TypeString,
Required: true,
},
},
}
}
func resourceAlicloudEcsHpcClusterCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateHpcCluster"
request := make(map[string]interface{})
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["Name"] = d.Get("name")
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("CreateHpcCluster")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecs_hpc_cluster", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetId(fmt.Sprint(response["HpcClusterId"]))
return resourceAlicloudEcsHpcClusterRead(d, meta)
}
func resourceAlicloudEcsHpcClusterRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
object, err := ecsService.DescribeEcsHpcCluster(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecs_hpc_cluster ecsService.DescribeEcsHpcCluster Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", object["Description"])
d.Set("name", object["Name"])
return nil
}
func resourceAlicloudEcsHpcClusterUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
update := false
request := map[string]interface{}{
"HpcClusterId": d.Id(),
}
request["RegionId"] = client.RegionId
if d.HasChange("description") {
update = true
request["Description"] = d.Get("description")
}
if d.HasChange("name") {
update = true
request["Name"] = d.Get("name")
}
if update {
action := "ModifyHpcClusterAttribute"
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("ModifyHpcClusterAttribute")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudEcsHpcClusterRead(d, meta)
}
func resourceAlicloudEcsHpcClusterDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteHpcCluster"
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"HpcClusterId": d.Id(),
}
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("DeleteHpcCluster")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudEcsKeyPair() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcsKeyPairCreate,
Read: resourceAlicloudEcsKeyPairRead,
Update: resourceAlicloudEcsKeyPairUpdate,
Delete: resourceAlicloudEcsKeyPairDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Delete: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"finger_print": {
Type: schema.TypeString,
Computed: true,
},
"key_pair_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"key_name"},
ValidateFunc: validation.StringLenBetween(2, 128),
},
"key_name_prefix": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ConflictsWith: []string{"key_pair_name", "key_name"},
ValidateFunc: validation.StringLenBetween(0, 100),
},
"public_key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
StateFunc: func(v interface{}) string {
switch v.(type) {
case string:
return strings.TrimSpace(v.(string))
default:
return ""
}
},
},
"key_file": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"key_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Deprecated: "Field 'key_name' has been deprecated from provider version 1.121.0. New field 'key_pair_name' instead.",
ConflictsWith: []string{"key_pair_name"},
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
},
"tags": tagsSchema(),
},
}
}
func resourceAlicloudEcsKeyPairCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateKeyPair"
request := make(map[string]interface{})
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("key_pair_name"); ok {
request["KeyPairName"] = v
} else if v, ok := d.GetOk("key_name"); ok {
request["KeyPairName"] = v
} else if v, ok := d.GetOk("key_name_prefix"); ok {
request["KeyPairName"] = resource.PrefixedUniqueId(v.(string))
} else {
request["KeyPairName"] = resource.UniqueId()
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("tags"); ok {
count := 1
for key, value := range v.(map[string]interface{}) {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
}
if publicKey, ok := d.GetOk("public_key"); ok {
action = "ImportKeyPair"
request["PublicKeyBody"] = publicKey
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecs_key_pair", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["KeyPairName"]))
if file, ok := d.GetOk("key_file"); ok {
if v, exist := response["PrivateKeyBody"]; exist {
err := ioutil.WriteFile(file.(string), []byte(v.(string)), 0600)
if err != nil {
return WrapError(err)
}
err = os.Chmod(file.(string), 0400)
if err != nil {
return WrapError(err)
}
}
}
return resourceAlicloudEcsKeyPairRead(d, meta)
}
func resourceAlicloudEcsKeyPairRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
object, err := ecsService.DescribeEcsKeyPair(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecs_key_pair ecsService.DescribeEcsKeyPair Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("key_pair_name", d.Id())
d.Set("key_name", d.Id())
d.Set("finger_print", object["KeyPairFingerPrint"])
d.Set("resource_group_id", object["ResourceGroupId"])
tags, err := ecsService.ListTagResources(d.Id(), "keypair")
if err != nil {
return WrapError(err)
} else {
d.Set("tags", tagsToMap(tags))
}
return nil
}
func resourceAlicloudEcsKeyPairUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
d.Partial(true)
if d.HasChange("tags") {
if err := ecsService.SetResourceTags(d, "keypair"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
update := false
request := map[string]interface{}{
"ResourceId": d.Id(),
}
request["RegionId"] = client.RegionId
if d.HasChange("resource_group_id") {
update = true
request["ResourceGroupId"] = d.Get("resource_group_id")
}
request["ResourceType"] = "keypair"
if update {
action := "JoinResourceGroup"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("resource_group_id")
}
d.Partial(false)
return resourceAlicloudEcsKeyPairRead(d, meta)
}
func resourceAlicloudEcsKeyPairDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteKeyPairs"
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"KeyPairNames": convertListToJsonString(convertListStringToListInterface([]string{d.Id()})),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidParameter.KeypairAlreadyAttachedInstance", "ServiceUnavailable"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidKeyPair.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudEcsKeyPairAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcsKeyPairAttachmentCreate,
Read: resourceAlicloudEcsKeyPairAttachmentRead,
Delete: resourceAlicloudEcsKeyPairAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"instance_ids": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
ForceNew: true,
},
"key_pair_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(2, 128),
ConflictsWith: []string{"key_name"},
},
"key_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(2, 128),
Deprecated: "Field 'key_name' has been deprecated from provider version 1.121.0. New field 'key_pair_name' instead.",
ConflictsWith: []string{"key_pair_name"},
},
"force": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudEcsKeyPairAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AttachKeyPair"
request := make(map[string]interface{})
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
request["InstanceIds"] = convertListToJsonString(d.Get("instance_ids").(*schema.Set).List())
if v, ok := d.GetOk("key_pair_name"); ok {
request["KeyPairName"] = v
} else if v, ok := d.GetOk("key_name"); ok {
request["KeyPairName"] = v
} else {
return WrapError(Error(`[ERROR] Argument "key_name" or "key_pair_name" must be set one!`))
}
request["RegionId"] = client.RegionId
ecsService := EcsService{client}
force := d.Get("force").(bool)
idsMap := make(map[string]string)
var newIds []string
if force {
ids, err := ecsService.QueryInstancesWithKeyPair("", d.Get("key_pair_name").(string))
if err != nil {
return WrapError(err)
}
for _, id := range ids {
idsMap[id] = id
}
for _, id := range d.Get("instance_ids").(*schema.Set).List() {
if _, ok := idsMap[id.(string)]; !ok {
newIds = append(newIds, id.(string))
}
}
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecs_key_pair_attachment", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["KeyPairName"], ":", request["InstanceIds"]))
if force {
requestReboot := make(map[string]interface{})
requestReboot["RegionId"] = client.RegionId
requestReboot["ForceStop"] = requests.NewBoolean(true)
action = "RebootInstance"
for _, id := range newIds {
requestReboot["InstanceId"] = id
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2014-05-26"), StringPointer("AK"), requestReboot, nil, &util.RuntimeOptions{})
if err != nil {
return WrapError(err)
}
addDebug(action, response, request)
}
for _, id := range newIds {
if err := ecsService.WaitForEcsInstance(id, Running, DefaultLongTimeout); err != nil {
return WrapError(err)
}
}
}
return resourceAlicloudEcsKeyPairAttachmentRead(d, meta)
}
func resourceAlicloudEcsKeyPairAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
object, err := ecsService.DescribeEcsKeyPairAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("key_name", object.KeyPairName)
d.Set("instance_ids", d.Get("instance_ids"))
return nil
}
func resourceAlicloudEcsKeyPairAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DetachKeyPair"
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
separatorIndex := strings.LastIndexByte(d.Id(), ':')
KeyName := d.Id()[:separatorIndex]
request := map[string]interface{}{
"KeyPairName": KeyName,
}
request["RegionId"] = client.RegionId
InstanceIds := d.Id()[separatorIndex+1:]
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
request["InstanceIds"] = InstanceIds
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
ecsService := EcsService{client}
instance_ids, err := ecsService.QueryInstancesWithKeyPair(InstanceIds, KeyName)
if err != nil {
return resource.NonRetryableError(WrapError(err))
}
if len(instance_ids) > 0 {
var ids []interface{}
for _, id := range instance_ids {
ids = append(ids, id)
}
InstanceIds = convertListToJsonString(ids)
return resource.RetryableError(WrapError(fmt.Errorf("detach Key Pair timeout and the instances including %s has not yet been detached. ", InstanceIds)))
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"strconv"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudEcsLaunchTemplate() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcsLaunchTemplateCreate,
Read: resourceAlicloudEcsLaunchTemplateRead,
Update: resourceAlicloudEcsLaunchTemplateUpdate,
Delete: resourceAlicloudEcsLaunchTemplateDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"auto_release_time": {
Type: schema.TypeString,
Optional: true,
},
"data_disks": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"category": {
Type: schema.TypeString,
Optional: true,
},
"delete_with_instance": {
Type: schema.TypeBool,
Optional: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.All(validation.StringLenBetween(2, 256), validation.StringDoesNotMatch(regexp.MustCompile(`(^http://.*)|(^https://.*)`), "It cannot begin with \"http://\", \"https://\".")),
},
"encrypted": {
Type: schema.TypeBool,
Optional: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.All(validation.StringDoesNotMatch(regexp.MustCompile(`(^http://.*)|(^https://.*)`), "It cannot begin with \"http://\", \"https://\"."), validation.StringMatch(regexp.MustCompile(`^[a-zA-Z\p{Han}][a-zA-Z\p{Han}_0-9\-\.\:]{1,127}$`), `It can contain A-Z, a-z, Chinese characters, numbers, periods (.), colons (:), underscores (_), and hyphens (-).`)),
},
"performance_level": {
Type: schema.TypeString,
Optional: true,
},
"size": {
Type: schema.TypeInt,
Optional: true,
},
"snapshot_id": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"deployment_set_id": {
Type: schema.TypeString,
Optional: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.All(validation.StringLenBetween(2, 256), validation.StringDoesNotMatch(regexp.MustCompile(`(^http://.*)|(^https://.*)`), "It cannot begin with \"http://\", \"https://\".")),
},
"enable_vm_os_config": {
Type: schema.TypeBool,
Optional: true,
},
"host_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.All(validation.StringDoesNotMatch(regexp.MustCompile(`(^\..*)|(^\-.*)|(.*\-$)|(.*\.$)`), "It cannot begin or end with period (.), hyphen (-).")),
},
"image_id": {
Type: schema.TypeString,
Optional: true,
},
"image_owner_alias": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"system", "self", "others", "marketplace", ""}, false),
Default: "",
},
"instance_charge_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"PostPaid", "PrePaid"}, false),
},
"instance_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.All(validation.StringDoesNotMatch(regexp.MustCompile(`(^http://.*)|(^https://.*)`), "It cannot begin with \"http://\", \"https://\"."), validation.StringMatch(regexp.MustCompile(`^[a-zA-Z\p{Han}][a-zA-Z\p{Han}_0-9\-\.\:]{1,127}$`), `It must begin with an English or a Chinese character. It can contain A-Z, a-z, Chinese characters, numbers, periods (.), colons (:), underscores (_), and hyphens (-).`)),
},
"instance_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^ecs\..*`), "prefix must be 'ecs.'"),
},
"internet_charge_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"PayByBandwidth", "PayByTraffic"}, false),
},
"internet_max_bandwidth_in": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(1, 200),
},
"internet_max_bandwidth_out": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(0, 100),
},
"io_optimized": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"none", "optimized"}, false),
},
"key_pair_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 128),
},
"launch_template_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"name"},
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Deprecated: "Field 'name' has been deprecated from provider version 1.120.0. New field 'launch_template_name' instead.",
ConflictsWith: []string{"launch_template_name"},
},
"network_interfaces": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.All(validation.StringLenBetween(2, 256), validation.StringDoesNotMatch(regexp.MustCompile(`(^http://.*)|(^https://.*)`), "It cannot begin with \"http://\", \"https://\".")),
},
"name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.All(validation.StringDoesNotMatch(regexp.MustCompile(`(^http://.*)|(^https://.*)`), "It cannot begin with \"http://\", \"https://\"."), validation.StringMatch(regexp.MustCompile(`^[a-zA-Z\p{Han}][a-zA-Z\p{Han}_0-9\-\.\:]{1,127}$`), `It can contain A-Z, a-z, Chinese characters, numbers, periods (.), colons (:), underscores (_), and hyphens (-).`)),
},
"primary_ip": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.SingleIP(),
},
"security_group_id": {
Type: schema.TypeString,
Optional: true,
},
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
},
},
},
MaxItems: 1,
},
"network_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"classic", "vpc"}, false),
},
"password_inherit": {
Type: schema.TypeBool,
Optional: true,
},
"period": {
Type: schema.TypeInt,
Optional: true,
},
"private_ip_address": {
Type: schema.TypeString,
Optional: true,
},
"ram_role_name": {
Type: schema.TypeString,
Optional: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
},
"security_enhancement_strategy": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Deactive"}, false),
},
"security_group_id": {
Type: schema.TypeString,
Optional: true,
},
"security_group_ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"spot_duration": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"0", "1", "2", "3", "4", "5", "6"}, false),
Default: "1",
},
"spot_price_limit": {
Type: schema.TypeFloat,
Optional: true,
},
"spot_strategy": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"NoSpot", "SpotAsPriceGo", "SpotWithPriceLimit"}, false),
},
"system_disk": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"category": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"all", "cloud", "ephemeral_ssd", "cloud_essd", "cloud_efficiency", "cloud_ssd", "local_disk"}, false),
ConflictsWith: []string{"system_disk_category"},
},
"delete_with_instance": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.All(validation.StringLenBetween(2, 256), validation.StringDoesNotMatch(regexp.MustCompile(`(^http://.*)|(^https://.*)`), "It cannot begin with \"http://\", \"https://\".")),
ConflictsWith: []string{"system_disk_description"},
},
"iops": {
Type: schema.TypeString,
Optional: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.All(validation.StringDoesNotMatch(regexp.MustCompile(`(^http://.*)|(^https://.*)`), "It cannot begin with \"http://\", \"https://\"."), validation.StringMatch(regexp.MustCompile(`^[a-zA-Z\p{Han}][a-zA-Z\p{Han}_0-9\-\.\:]{1,127}$`), `It can contain A-Z, a-z, Chinese characters, numbers, periods (.), colons (:), underscores (_), and hyphens (-).`)),
ConflictsWith: []string{"system_disk_name"},
},
"performance_level": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"PL0", "PL1", "PL2", "PL3"}, false),
Default: "PL0",
},
"size": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(20, 500),
ConflictsWith: []string{"system_disk_size"},
},
},
},
},
"tags": tagsSchema(),
"template_tags": tagsSchema(),
"template_resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"user_data": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"userdata"},
},
"userdata": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Field 'userdata' has been deprecated from provider version 1.120.0. New field 'user_data' instead.",
ConflictsWith: []string{"user_data"},
},
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
},
"version_description": {
Type: schema.TypeString,
Optional: true,
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"system_disk_category": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"all", "cloud", "ephemeral_ssd", "cloud_essd", "cloud_efficiency", "cloud_ssd", "local_disk"}, false),
Deprecated: "Field 'system_disk_category' has been deprecated from provider version 1.120.0. New field 'system_disk' instead.",
ConflictsWith: []string{"system_disk"},
},
"system_disk_description": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.All(validation.StringLenBetween(2, 256), validation.StringDoesNotMatch(regexp.MustCompile(`(^http://.*)|(^https://.*)`), "It cannot begin with \"http://\", \"https://\".")),
Deprecated: "Field 'system_disk_description' has been deprecated from provider version 1.120.0. New field 'system_disk' instead.",
ConflictsWith: []string{"system_disk"},
},
"system_disk_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.All(validation.StringDoesNotMatch(regexp.MustCompile(`(^http://.*)|(^https://.*)`), "It cannot begin with \"http://\", \"https://\"."), validation.StringMatch(regexp.MustCompile(`^[a-zA-Z\p{Han}][a-zA-Z\p{Han}_0-9\-\.\:]{1,127}$`), `It can contain A-Z, a-z, Chinese characters, numbers, periods (.), colons (:), underscores (_), and hyphens (-).`)),
Deprecated: "Field 'system_disk_name' has been deprecated from provider version 1.120.0. New field 'system_disk' instead.",
ConflictsWith: []string{"system_disk"},
},
"system_disk_size": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(20, 500),
Deprecated: "Field 'system_disk_size' has been deprecated from provider version 1.120.0. New field 'system_disk' instead.",
ConflictsWith: []string{"system_disk"},
},
},
}
}
func resourceAlicloudEcsLaunchTemplateCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateLaunchTemplate"
request := make(map[string]interface{})
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("auto_release_time"); ok {
request["AutoReleaseTime"] = v
}
if v, ok := d.GetOk("data_disks"); ok {
dataDisksMaps := make([]map[string]interface{}, 0)
for _, dataDisks := range v.(*schema.Set).List() {
dataDisksMap := make(map[string]interface{})
dataDisksArg := dataDisks.(map[string]interface{})
dataDisksMap["Category"] = dataDisksArg["category"]
dataDisksMap["DeleteWithInstance"] = requests.NewBoolean(dataDisksArg["delete_with_instance"].(bool))
dataDisksMap["Description"] = dataDisksArg["description"]
dataDisksMap["Encrypted"] = fmt.Sprintf("%v", dataDisksArg["encrypted"].(bool))
dataDisksMap["DiskName"] = dataDisksArg["name"]
dataDisksMap["PerformanceLevel"] = dataDisksArg["performance_level"]
dataDisksMap["Size"] = requests.NewInteger(dataDisksArg["size"].(int))
dataDisksMap["SnapshotId"] = dataDisksArg["snapshot_id"]
dataDisksMaps = append(dataDisksMaps, dataDisksMap)
}
request["DataDisk"] = dataDisksMaps
}
if v, ok := d.GetOk("deployment_set_id"); ok {
request["DeploymentSetId"] = v
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOkExists("enable_vm_os_config"); ok {
request["EnableVmOsConfig"] = v
}
if v, ok := d.GetOk("host_name"); ok {
request["HostName"] = v
}
if v, ok := d.GetOk("image_id"); ok {
request["ImageId"] = v
}
if v, ok := d.GetOk("image_owner_alias"); ok {
request["ImageOwnerAlias"] = v
}
if v, ok := d.GetOk("instance_charge_type"); ok {
request["InstanceChargeType"] = v
}
if v, ok := d.GetOk("instance_name"); ok {
request["InstanceName"] = v
}
if v, ok := d.GetOk("instance_type"); ok {
request["InstanceType"] = v
}
if v, ok := d.GetOk("internet_charge_type"); ok {
request["InternetChargeType"] = v
}
if v, ok := d.GetOk("internet_max_bandwidth_in"); ok {
request["InternetMaxBandwidthIn"] = v
}
if v, ok := d.GetOk("internet_max_bandwidth_out"); ok {
request["InternetMaxBandwidthOut"] = v
}
if v, ok := d.GetOk("io_optimized"); ok {
request["IoOptimized"] = v
}
if v, ok := d.GetOk("key_pair_name"); ok {
request["KeyPairName"] = v
}
if v, ok := d.GetOk("launch_template_name"); ok {
request["LaunchTemplateName"] = v
} else if v, ok := d.GetOk("name"); ok {
request["LaunchTemplateName"] = v
} else {
return WrapError(Error(`[ERROR] Argument "name" or "launch_template_name" must be set one!`))
}
if v, ok := d.GetOk("network_interfaces"); ok {
networkInterfacesMaps := make([]map[string]interface{}, 0)
for _, networkInterfaces := range v.(*schema.Set).List() {
networkInterfacesMap := make(map[string]interface{})
networkInterfacesArg := networkInterfaces.(map[string]interface{})
networkInterfacesMap["Description"] = networkInterfacesArg["description"]
networkInterfacesMap["NetworkInterfaceName"] = networkInterfacesArg["name"]
networkInterfacesMap["PrimaryIpAddress"] = networkInterfacesArg["primary_ip"]
networkInterfacesMap["SecurityGroupId"] = networkInterfacesArg["security_group_id"]
networkInterfacesMap["VSwitchId"] = networkInterfacesArg["vswitch_id"]
networkInterfacesMaps = append(networkInterfacesMaps, networkInterfacesMap)
}
request["NetworkInterface"] = networkInterfacesMaps
}
if v, ok := d.GetOk("network_type"); ok {
request["NetworkType"] = v
}
if v, ok := d.GetOkExists("password_inherit"); ok {
request["PasswordInherit"] = v
}
if v, ok := d.GetOk("period"); ok {
request["Period"] = v
}
if v, ok := d.GetOk("private_ip_address"); ok {
request["PrivateIpAddress"] = v
}
if v, ok := d.GetOk("ram_role_name"); ok {
request["RamRoleName"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("security_enhancement_strategy"); ok {
request["SecurityEnhancementStrategy"] = v
}
if v, ok := d.GetOk("security_group_id"); ok {
request["SecurityGroupId"] = v
}
if v, ok := d.GetOk("security_group_ids"); ok {
request["SecurityGroupIds"] = v
}
if v, ok := d.GetOk("spot_duration"); ok {
request["SpotDuration"] = v
}
if v, ok := d.GetOk("spot_price_limit"); ok {
request["SpotPriceLimit"] = v
}
if v, ok := d.GetOk("spot_strategy"); ok {
request["SpotStrategy"] = v
}
if v, ok := d.GetOk("system_disk"); ok {
systemDiskMap := make(map[string]interface{})
for _, systemDisk := range v.(*schema.Set).List() {
systemDiskArg := systemDisk.(map[string]interface{})
systemDiskMap["Category"] = systemDiskArg["category"]
systemDiskMap["DeleteWithInstance"] = requests.NewBoolean(systemDiskArg["delete_with_instance"].(bool))
systemDiskMap["Description"] = systemDiskArg["description"]
systemDiskMap["Iops"] = systemDiskArg["iops"]
systemDiskMap["DiskName"] = systemDiskArg["name"]
systemDiskMap["PerformanceLevel"] = systemDiskArg["performance_level"]
systemDiskMap["Size"] = requests.NewInteger(systemDiskArg["size"].(int))
}
request["SystemDisk"] = systemDiskMap
} else {
systemDiskMap := make(map[string]interface{})
if v, ok := d.GetOk("system_disk_category"); ok {
systemDiskMap["Category"] = v
}
if v, ok := d.GetOk("system_disk_description"); ok {
systemDiskMap["Description"] = v
}
if v, ok := d.GetOk("system_disk_name"); ok {
systemDiskMap["DiskName"] = v
}
if v, ok := d.GetOk("system_disk_size"); ok {
systemDiskMap["Size"] = v
}
if len(systemDiskMap) > 0 {
request["SystemDisk"] = systemDiskMap
}
}
if v, ok := d.GetOk("tags"); ok {
count := 1
for key, value := range v.(map[string]interface{}) {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
}
if v, ok := d.GetOk("template_tags"); ok {
count := 1
for key, value := range v.(map[string]interface{}) {
request[fmt.Sprintf("TemplateTag.%d.Key", count)] = key
request[fmt.Sprintf("TemplateTag.%d.Value", count)] = value
count++
}
}
if v, ok := d.GetOk("template_resource_group_id"); ok {
request["TemplateResourceGroupId"] = v
}
if v, ok := d.GetOk("user_data"); ok {
request["UserData"] = v
} else if v, ok := d.GetOk("userdata"); ok {
request["UserData"] = v
}
if v, ok := d.GetOk("version_description"); ok {
request["VersionDescription"] = v
}
if v, ok := d.GetOk("vpc_id"); ok {
request["VpcId"] = v
}
if v, ok := d.GetOk("zone_id"); ok {
request["ZoneId"] = v
}
vswitchId := Trim(d.Get("vswitch_id").(string))
if vswitchId != "" {
vpcService := VpcService{client}
vsw, err := vpcService.DescribeVSwitchWithTeadsl(vswitchId)
if err != nil {
return WrapError(err)
}
if v, ok := request["VpcId"].(string); !ok || v == "" {
request["VpcId"] = vsw["VpcId"]
}
request["VSwitchId"] = vswitchId
if v, ok := request["ZoneId"].(string); !ok || v == "" {
request["ZoneId"] = vsw["ZoneId"]
}
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecs_launch_template", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["LaunchTemplateId"]))
return resourceAlicloudEcsLaunchTemplateRead(d, meta)
}
func resourceAlicloudEcsLaunchTemplateRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
object, err := ecsService.DescribeEcsLaunchTemplate(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecs_launch_template ecsService.DescribeEcsLaunchTemplate Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("launch_template_name", object["LaunchTemplateName"])
d.Set("name", object["LaunchTemplateName"])
describeLaunchTemplateVersions, err := ecsService.DescribeLaunchTemplateVersions(d.Id())
if err != nil {
return WrapError(err)
}
describeLaunchTemplateVersionsObject := make(map[string]interface{})
for _, version := range describeLaunchTemplateVersions {
if version.(map[string]interface{})["VersionNumber"] == object["LatestVersionNumber"] {
describeLaunchTemplateVersionsObject = version.(map[string]interface{})
}
}
d.Set("auto_release_time", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["AutoReleaseTime"])
dataDisk := make([]map[string]interface{}, 0)
if dataDiskList, ok := describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["DataDisks"].(map[string]interface{})["DataDisk"].([]interface{}); ok {
for _, v := range dataDiskList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"category": m1["Category"],
"delete_with_instance": m1["DeleteWithInstance"],
"description": m1["Description"],
"encrypted": m1["Encrypted"],
"name": m1["DiskName"],
"performance_level": m1["PerformanceLevel"],
"size": m1["Size"],
"snapshot_id": m1["SnapshotId"],
}
dataDisk = append(dataDisk, temp1)
}
}
}
if err := d.Set("data_disks", dataDisk); err != nil {
return WrapError(err)
}
d.Set("deployment_set_id", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["DeploymentSetId"])
d.Set("description", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["Description"])
d.Set("enable_vm_os_config", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["EnableVmOsConfig"])
d.Set("host_name", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["HostName"])
d.Set("image_id", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["ImageId"])
d.Set("image_owner_alias", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["ImageOwnerAlias"])
d.Set("instance_charge_type", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["InstanceChargeType"])
d.Set("instance_name", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["InstanceName"])
d.Set("instance_type", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["InstanceType"])
d.Set("internet_charge_type", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["InternetChargeType"])
d.Set("internet_max_bandwidth_in", formatInt(describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["InternetMaxBandwidthIn"]))
d.Set("internet_max_bandwidth_out", formatInt(describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["InternetMaxBandwidthOut"]))
d.Set("io_optimized", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["IoOptimized"])
d.Set("key_pair_name", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["KeyPairName"])
networkInterface := make([]map[string]interface{}, 0)
if networkInterfaceList, ok := describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["NetworkInterfaces"].(map[string]interface{})["NetworkInterface"].([]interface{}); ok {
for _, v := range networkInterfaceList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"description": m1["Description"],
"name": m1["NetworkInterfaceName"],
"primary_ip": m1["PrimaryIpAddress"],
"security_group_id": m1["SecurityGroupId"],
"vswitch_id": m1["VSwitchId"],
}
networkInterface = append(networkInterface, temp1)
}
}
}
if err := d.Set("network_interfaces", networkInterface); err != nil {
return WrapError(err)
}
d.Set("network_type", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["NetworkType"])
d.Set("password_inherit", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["PasswordInherit"])
d.Set("period", formatInt(describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["Period"]))
d.Set("private_ip_address", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["PrivateIpAddress"])
d.Set("ram_role_name", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["RamRoleName"])
d.Set("security_enhancement_strategy", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SecurityEnhancementStrategy"])
d.Set("security_group_id", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SecurityGroupId"])
if describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SecurityGroupIds"] != nil {
d.Set("security_group_ids", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SecurityGroupIds"].(map[string]interface{})["SecurityGroupId"])
}
d.Set("spot_duration", fmt.Sprint(formatInt(describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SpotDuration"])))
d.Set("spot_price_limit", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SpotPriceLimit"])
d.Set("spot_strategy", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SpotStrategy"])
d.Set("system_disk_category", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SystemDisk.Category"])
d.Set("system_disk_size", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SystemDisk.Size"])
d.Set("system_disk_description", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SystemDisk.Description"])
d.Set("system_disk_name", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SystemDisk.DiskName"])
systemDiskSli := make([]map[string]interface{}, 0)
systemDiskMap := make(map[string]interface{})
systemDiskMap["category"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SystemDisk.Category"]
systemDiskMap["delete_with_instance"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SystemDisk.DeleteWithInstance"]
systemDiskMap["description"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SystemDisk.Description"]
systemDiskMap["iops"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SystemDisk.Iops"]
systemDiskMap["name"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SystemDisk.DiskName"]
systemDiskMap["performance_level"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SystemDisk.PerformanceLevel"]
systemDiskMap["size"] = describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["SystemDisk.Size"]
systemDiskSli = append(systemDiskSli, systemDiskMap)
d.Set("system_disk", systemDiskSli)
d.Set("vpc_id", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["VpcId"])
d.Set("resource_group_id", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["ResourceGroupId"])
if object["Tags"] != nil {
d.Set("template_tags", tagsToMap(object["Tags"].(map[string]interface{})["Tag"]))
}
d.Set("user_data", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["UserData"])
d.Set("userdata", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["UserData"])
d.Set("vswitch_id", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["VSwitchId"])
d.Set("version_description", describeLaunchTemplateVersionsObject["VersionDescription"])
d.Set("vpc_id", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["VpcId"])
d.Set("zone_id", describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["ZoneId"])
d.Set("tags", tagsToMap(describeLaunchTemplateVersionsObject["LaunchTemplateData"].(map[string]interface{})["Tags"].(map[string]interface{})["InstanceTag"]))
return nil
}
func resourceAlicloudEcsLaunchTemplateUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
var response map[string]interface{}
d.Partial(true)
if d.HasChange("template_tags") {
if err := ecsService.SetResourceTemplateTags(d, "launchtemplate"); err != nil {
return WrapError(err)
}
d.SetPartial("template_tags")
}
versions, err := getLaunchTemplateVersions(d.Id(), meta)
if err != nil {
return WrapError(err)
}
// Remove one of the oldest and non-default version when the total number reach 30
if len(versions) > 29 {
var oldestVersion int64
for _, version := range versions {
if !version.(map[string]interface{})["DefaultVersion"].(bool) && (oldestVersion == 0 || version.(map[string]interface{})["VersionNumber"].(int64) < oldestVersion) {
oldestVersion = version.(map[string]interface{})["VersionNumber"].(int64)
}
}
err = deleteLaunchTemplateVersion(d.Id(), int(oldestVersion), meta)
if err != nil {
return WrapError(err)
}
}
update := false
request := map[string]interface{}{
"LaunchTemplateId": d.Id(),
}
request["RegionId"] = client.RegionId
if d.HasChange("auto_release_time") {
update = true
}
if v, ok := d.GetOk("auto_release_time"); ok {
request["AutoReleaseTime"] = v
}
if d.HasChange("data_disks") {
update = true
}
if v, ok := d.GetOk("data_disks"); ok {
DataDisks := make([]map[string]interface{}, len(v.(*schema.Set).List()))
for i, DataDisksValue := range v.(*schema.Set).List() {
DataDisksMap := DataDisksValue.(map[string]interface{})
DataDisks[i] = make(map[string]interface{})
DataDisks[i]["Category"] = DataDisksMap["category"]
DataDisks[i]["DeleteWithInstance"] = DataDisksMap["delete_with_instance"]
DataDisks[i]["Description"] = DataDisksMap["description"]
DataDisks[i]["Encrypted"] = fmt.Sprintf("%v", DataDisksMap["encrypted"].(bool))
DataDisks[i]["DiskName"] = DataDisksMap["name"]
DataDisks[i]["PerformanceLevel"] = DataDisksMap["performance_level"]
DataDisks[i]["Size"] = DataDisksMap["size"]
DataDisks[i]["SnapshotId"] = DataDisksMap["snapshot_id"]
}
request["DataDisk"] = DataDisks
}
if d.HasChange("deployment_set_id") {
update = true
}
if v, ok := d.GetOk("deployment_set_id"); ok {
request["DeploymentSetId"] = v
}
if d.HasChange("description") {
update = true
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if d.HasChange("enable_vm_os_config") {
update = true
}
if v, ok := d.GetOkExists("enable_vm_os_config"); ok {
request["EnableVmOsConfig"] = v
}
if d.HasChange("host_name") {
update = true
}
if v, ok := d.GetOk("host_name"); ok {
request["HostName"] = v
}
if d.HasChange("image_id") {
update = true
}
if v, ok := d.GetOk("image_id"); ok {
request["ImageId"] = v
}
if d.HasChange("image_owner_alias") {
update = true
}
if v, ok := d.GetOk("image_owner_alias"); ok {
request["ImageOwnerAlias"] = v
}
if d.HasChange("instance_charge_type") {
update = true
}
if v, ok := d.GetOk("instance_charge_type"); ok {
request["InstanceChargeType"] = v
}
if d.HasChange("instance_name") {
update = true
}
if v, ok := d.GetOk("instance_name"); ok {
request["InstanceName"] = v
}
if d.HasChange("instance_type") {
update = true
}
if v, ok := d.GetOk("instance_type"); ok {
request["InstanceType"] = v
}
if d.HasChange("internet_charge_type") {
update = true
}
if v, ok := d.GetOk("internet_charge_type"); ok {
request["InternetChargeType"] = v
}
if d.HasChange("internet_max_bandwidth_in") {
update = true
}
if v, ok := d.GetOk("internet_max_bandwidth_in"); ok {
request["InternetMaxBandwidthIn"] = v
}
if d.HasChange("internet_max_bandwidth_out") {
update = true
}
if v, ok := d.GetOk("internet_max_bandwidth_out"); ok {
request["InternetMaxBandwidthOut"] = v
}
if d.HasChange("io_optimized") {
update = true
}
if v, ok := d.GetOk("io_optimized"); ok {
request["IoOptimized"] = v
}
if d.HasChange("key_pair_name") {
update = true
}
if v, ok := d.GetOk("key_pair_name"); ok {
request["KeyPairName"] = v
}
if d.HasChange("launch_template_name") {
update = true
request["LaunchTemplateName"] = d.Get("launch_template_name")
} else if d.HasChange("name") {
update = true
request["LaunchTemplateName"] = d.Get("name")
} else {
if v, ok := d.GetOk("launch_template_name"); ok {
request["LaunchTemplateName"] = v
} else if v, ok := d.GetOk("name"); ok {
request["LaunchTemplateName"] = v
}
}
if d.HasChange("network_interfaces") {
update = true
}
if v, ok := d.GetOk("network_interfaces"); ok {
NetworkInterfaces := make([]map[string]interface{}, len(v.(*schema.Set).List()))
for i, NetworkInterfacesValue := range v.(*schema.Set).List() {
NetworkInterfacesMap := NetworkInterfacesValue.(map[string]interface{})
NetworkInterfaces[i] = make(map[string]interface{})
NetworkInterfaces[i]["Description"] = NetworkInterfacesMap["description"]
NetworkInterfaces[i]["NetworkInterfaceName"] = NetworkInterfacesMap["name"]
NetworkInterfaces[i]["PrimaryIpAddress"] = NetworkInterfacesMap["primary_ip"]
NetworkInterfaces[i]["SecurityGroupId"] = NetworkInterfacesMap["security_group_id"]
NetworkInterfaces[i]["VSwitchId"] = NetworkInterfacesMap["vswitch_id"]
}
request["NetworkInterface"] = NetworkInterfaces
}
if d.HasChange("network_type") {
update = true
}
if v, ok := d.GetOk("network_type"); ok {
request["NetworkType"] = v
}
if d.HasChange("password_inherit") {
update = true
}
if v, ok := d.GetOkExists("password_inherit"); ok {
request["PasswordInherit"] = v
}
if d.HasChange("period") {
update = true
}
if v, ok := d.GetOk("period"); ok {
request["Period"] = v
}
if d.HasChange("private_ip_address") {
update = true
}
if v, ok := d.GetOk("private_ip_address"); ok {
request["PrivateIpAddress"] = v
}
if d.HasChange("ram_role_name") {
update = true
}
if v, ok := d.GetOk("ram_role_name"); ok {
request["RamRoleName"] = v
}
if d.HasChange("resource_group_id") {
update = true
}
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if d.HasChange("security_enhancement_strategy") {
update = true
}
if v, ok := d.GetOk("security_enhancement_strategy"); ok {
request["SecurityEnhancementStrategy"] = v
}
if d.HasChange("security_group_id") {
update = true
}
if v, ok := d.GetOk("security_group_id"); ok {
request["SecurityGroupId"] = v
}
if d.HasChange("security_group_ids") {
update = true
}
if v, ok := d.GetOk("security_group_ids"); ok {
request["SecurityGroupIds"] = v
}
if d.HasChange("spot_duration") {
update = true
}
if v, ok := d.GetOk("spot_duration"); ok {
request["SpotDuration"] = v
}
if d.HasChange("spot_price_limit") {
update = true
}
if v, ok := d.GetOk("spot_price_limit"); ok {
request["SpotPriceLimit"] = v
}
if d.HasChange("spot_strategy") {
update = true
}
if v, ok := d.GetOk("spot_strategy"); ok {
request["SpotStrategy"] = v
}
if d.HasChange("system_disk") {
update = true
systemDiskMap := make(map[string]interface{})
for _, systemDisk := range d.Get("system_disk").(*schema.Set).List() {
systemDiskArg := systemDisk.(map[string]interface{})
systemDiskMap["Category"] = systemDiskArg["category"]
systemDiskMap["DeleteWithInstance"] = requests.NewBoolean(systemDiskArg["delete_with_instance"].(bool))
systemDiskMap["Description"] = systemDiskArg["description"]
systemDiskMap["Iops"] = systemDiskArg["iops"]
systemDiskMap["DiskName"] = systemDiskArg["name"]
systemDiskMap["PerformanceLevel"] = systemDiskArg["performance_level"]
systemDiskMap["Size"] = requests.NewInteger(systemDiskArg["size"].(int))
}
request["SystemDisk"] = systemDiskMap
} else {
systemDiskMap := make(map[string]interface{})
if d.HasChange("system_disk_category") {
update = true
}
if v, ok := d.GetOk("system_disk_category"); ok {
systemDiskMap["Category"] = v
}
if d.HasChange("system_disk_description") {
update = true
}
if v, ok := d.GetOk("system_disk_description"); ok {
systemDiskMap["Description"] = v
}
if d.HasChange("system_disk_name") {
update = true
}
if v, ok := d.GetOk("system_disk_name"); ok {
systemDiskMap["DiskName"] = v
}
if d.HasChange("system_disk_size") {
update = true
}
if v, ok := d.GetOk("system_disk_size"); ok {
systemDiskMap["Size"] = v
}
diskMap := d.Get("system_disk").(*schema.Set).List()[0].(map[string]interface{})
systemDiskMap["DeleteWithInstance"] = diskMap["delete_with_instance"]
systemDiskMap["Iops"] = diskMap["iops"]
systemDiskMap["PerformanceLevel"] = diskMap["performance_level"]
request["SystemDisk"] = systemDiskMap
}
if d.HasChange("tags") {
update = true
}
if v, ok := d.GetOk("tags"); ok {
count := 1
for key, value := range v.(map[string]interface{}) {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
}
if d.HasChange("user_data") {
update = true
request["UserData"] = d.Get("user_data")
} else if d.HasChange("userdata") {
update = true
request["UserData"] = d.Get("userdata")
} else {
if v, ok := d.GetOk("user_data"); ok {
request["UserData"] = v
} else if v, ok := d.GetOk("userdata"); ok {
request["UserData"] = v
}
}
if d.HasChange("vswitch_id") {
update = true
}
if v, ok := d.GetOk("vswitch_id"); ok {
request["VSwitchId"] = v
}
if d.HasChange("version_description") {
update = true
}
if v, ok := d.GetOk("version_description"); ok {
request["VersionDescription"] = v
}
if d.HasChange("vpc_id") {
update = true
}
if v, ok := d.GetOk("vpc_id"); ok {
request["VpcId"] = v
}
if d.HasChange("zone_id") {
update = true
}
if v, ok := d.GetOk("zone_id"); ok {
request["ZoneId"] = v
}
if update {
action := "CreateLaunchTemplateVersion"
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("auto_release_time")
d.SetPartial("data_disks")
d.SetPartial("deployment_set_id")
d.SetPartial("description")
d.SetPartial("enable_vm_os_config")
d.SetPartial("host_name")
d.SetPartial("image_id")
d.SetPartial("image_owner_alias")
d.SetPartial("instance_charge_type")
d.SetPartial("instance_name")
d.SetPartial("instance_type")
d.SetPartial("internet_charge_type")
d.SetPartial("internet_max_bandwidth_in")
d.SetPartial("internet_max_bandwidth_out")
d.SetPartial("io_optimized")
d.SetPartial("key_pair_name")
d.SetPartial("launch_template_name")
d.SetPartial("name")
d.SetPartial("network_interfaces")
d.SetPartial("network_type")
d.SetPartial("password_inherit")
d.SetPartial("period")
d.SetPartial("private_ip_address")
d.SetPartial("ram_role_name")
d.SetPartial("resource_group_id")
d.SetPartial("security_enhancement_strategy")
d.SetPartial("security_group_id")
d.SetPartial("security_group_ids")
d.SetPartial("spot_duration")
d.SetPartial("spot_price_limit")
d.SetPartial("spot_strategy")
d.SetPartial("system_disk")
d.SetPartial("system_disk_category")
d.SetPartial("system_disk_description")
d.SetPartial("system_disk_name")
d.SetPartial("system_disk_size")
d.SetPartial("tags")
d.SetPartial("user_data")
d.SetPartial("userdata")
d.SetPartial("vswitch_id")
d.SetPartial("version_description")
d.SetPartial("vpc_id")
d.SetPartial("zone_id")
}
d.Partial(false)
return resourceAlicloudEcsLaunchTemplateRead(d, meta)
}
func resourceAlicloudEcsLaunchTemplateDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteLaunchTemplate"
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"LaunchTemplateId": d.Id(),
}
if v, ok := d.GetOk("launch_template_name"); ok {
request["LaunchTemplateName"] = v
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func getLaunchTemplateVersions(id string, meta interface{}) ([]interface{}, error) {
client := meta.(*connectivity.AliyunClient)
action := "DescribeLaunchTemplateVersions"
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return nil, WrapError(err)
}
request := map[string]interface{}{
"LaunchTemplateId": id,
}
request["PageSize"] = requests.NewInteger(50)
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return nil, WrapError(err)
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.LaunchTemplateVersionSets.LaunchTemplateVersionSet", response)
if err != nil {
return nil, WrapErrorf(err, FailedGetAttributeMsg, id, "$.LaunchTemplateVersionSets.LaunchTemplateVersionSet", response)
}
if len(v.([]interface{})) < 1 {
return nil, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
}
return v.([]interface{}), nil
}
func deleteLaunchTemplateVersion(id string, version int, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteLaunchTemplateVersion"
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"LaunchTemplateId": id,
}
request["DeleteVersion"] = &[]string{strconv.FormatInt(int64(version), 10)}
request["RegionId"] = client.RegionId
_, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudEcsNetworkInterface() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcsNetworkInterfaceCreate,
Read: resourceAlicloudEcsNetworkInterfaceRead,
Update: resourceAlicloudEcsNetworkInterfaceUpdate,
Delete: resourceAlicloudEcsNetworkInterfaceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(2 * time.Minute),
Delete: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
},
"mac": {
Type: schema.TypeString,
Computed: true,
},
"network_interface_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"name"},
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Field 'name' has been deprecated from provider version 1.123.1. New field 'network_interface_name' instead",
ConflictsWith: []string{"network_interface_name"},
},
"primary_ip_address": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"private_ip"},
},
"private_ip": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Deprecated: "Field 'private_ip' has been deprecated from provider version 1.123.1. New field 'primary_ip_address' instead",
ConflictsWith: []string{"primary_ip_address"},
},
"private_ip_addresses": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
MaxItems: 10,
ConflictsWith: []string{"private_ips", "secondary_private_ip_address_count", "private_ips_count"},
},
"private_ips": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
MaxItems: 10,
Deprecated: "Field 'private_ips' has been deprecated from provider version 1.123.1. New field 'private_ip_addresses' instead",
ConflictsWith: []string{"private_ip_addresses", "secondary_private_ip_address_count", "private_ips_count"},
},
"queue_number": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"secondary_private_ip_address_count": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(0, 10),
ConflictsWith: []string{"private_ips_count", "private_ip_addresses", "private_ips"},
},
"private_ips_count": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(0, 10),
Deprecated: "Field 'private_ips_count' has been deprecated from provider version 1.123.1. New field 'secondary_private_ip_address_count' instead",
ConflictsWith: []string{"secondary_private_ip_address_count", "private_ip_addresses", "private_ips"},
},
"security_group_ids": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
MinItems: 1,
ConflictsWith: []string{"security_groups"},
},
"security_groups": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
MinItems: 1,
Deprecated: "Field 'security_groups' has been deprecated from provider version 1.123.1. New field 'security_group_ids' instead",
ConflictsWith: []string{"security_group_ids"},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
"vswitch_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudEcsNetworkInterfaceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
var response map[string]interface{}
action := "CreateNetworkInterface"
request := make(map[string]interface{})
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("network_interface_name"); ok {
request["NetworkInterfaceName"] = v
} else if v, ok := d.GetOk("name"); ok {
request["NetworkInterfaceName"] = v
}
if v, ok := d.GetOk("primary_ip_address"); ok {
request["PrimaryIpAddress"] = v
} else if v, ok := d.GetOk("private_ip"); ok {
request["PrimaryIpAddress"] = v
}
if v, ok := d.GetOk("private_ip_addresses"); ok {
request["PrivateIpAddress"] = v.(*schema.Set).List()
} else if v, ok := d.GetOk("private_ips"); ok {
request["PrivateIpAddress"] = v.(*schema.Set).List()
}
if v, ok := d.GetOk("queue_number"); ok {
request["QueueNumber"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("secondary_private_ip_address_count"); ok {
request["SecondaryPrivateIpAddressCount"] = v
} else if v, ok := d.GetOk("private_ips_count"); ok {
request["SecondaryPrivateIpAddressCount"] = v
}
if v, ok := d.GetOk("security_group_ids"); ok {
request["SecurityGroupIds"] = v
} else if v, ok := d.GetOk("security_groups"); ok {
request["SecurityGroupIds"] = v
}
if v, ok := d.GetOk("tags"); ok {
count := 1
for key, value := range v.(map[string]interface{}) {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
}
request["VSwitchId"] = d.Get("vswitch_id")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecs_network_interface", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["NetworkInterfaceId"]))
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, ecsService.EcsNetworkInterfaceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudEcsNetworkInterfaceRead(d, meta)
}
func resourceAlicloudEcsNetworkInterfaceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
object, err := ecsService.DescribeEcsNetworkInterface(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecs_network_interface ecsService.DescribeEcsNetworkInterface Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", object["Description"])
d.Set("mac", object["MacAddress"])
d.Set("network_interface_name", object["NetworkInterfaceName"])
d.Set("name", object["NetworkInterfaceName"])
d.Set("primary_ip_address", object["PrivateIpAddress"])
d.Set("private_ip", object["PrivateIpAddress"])
privateIps := make([]interface{}, 0, len(object["PrivateIpSets"].(map[string]interface{})["PrivateIpSet"].([]interface{})))
for _, v := range object["PrivateIpSets"].(map[string]interface{})["PrivateIpSet"].([]interface{}) {
if !v.(map[string]interface{})["Primary"].(bool) {
privateIps = append(privateIps, v.(map[string]interface{})["PrivateIpAddress"])
}
}
d.Set("private_ips", privateIps)
d.Set("private_ip_addresses", privateIps)
d.Set("private_ips_count", len(privateIps))
d.Set("secondary_private_ip_address_count", len(privateIps))
d.Set("queue_number", formatInt(object["QueueNumber"]))
d.Set("resource_group_id", object["ResourceGroupId"])
d.Set("security_group_ids", object["SecurityGroupIds"].(map[string]interface{})["SecurityGroupId"])
d.Set("security_groups", object["SecurityGroupIds"].(map[string]interface{})["SecurityGroupId"])
d.Set("status", object["Status"])
tags, err := ecsService.ListTagResources(d.Id(), "eni")
if err != nil {
return WrapError(err)
} else {
d.Set("tags", tagsToMap(tags))
}
d.Set("vswitch_id", object["VSwitchId"])
return nil
}
func resourceAlicloudEcsNetworkInterfaceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
ecsService := EcsService{client}
var response map[string]interface{}
d.Partial(true)
if d.HasChange("tags") {
if err := ecsService.SetResourceTags(d, "eni"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
update := false
request := map[string]interface{}{
"NetworkInterfaceId": d.Id(),
}
request["RegionId"] = client.RegionId
if d.HasChange("description") {
update = true
request["Description"] = d.Get("description")
}
if d.HasChange("network_interface_name") {
update = true
request["NetworkInterfaceName"] = d.Get("network_interface_name")
}
if d.HasChange("name") {
update = true
request["Name"] = d.Get("name")
}
if d.HasChange("queue_number") {
update = true
request["QueueNumber"] = d.Get("queue_number")
}
if d.HasChange("security_group_ids") {
update = true
request["SecurityGroupId"] = d.Get("security_group_ids")
}
if d.HasChange("security_groups") {
update = true
request["SecurityGroupId"] = d.Get("security_groups")
}
if update {
action := "ModifyNetworkInterfaceAttribute"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("description")
d.SetPartial("name")
d.SetPartial("network_interface_name")
d.SetPartial("queue_number")
d.SetPartial("security_groups")
d.SetPartial("security_group_ids")
}
d.Partial(false)
if d.HasChange("private_ip_addresses") {
oldPrivateIpAddresses, newPrivateIpAddresses := d.GetChange("private_ip_addresses")
oldPrivateIpAddressesSet := oldPrivateIpAddresses.(*schema.Set)
newPrivateIpAddressesSet := newPrivateIpAddresses.(*schema.Set)
removed := oldPrivateIpAddressesSet.Difference(newPrivateIpAddressesSet)
added := newPrivateIpAddressesSet.Difference(oldPrivateIpAddressesSet)
if removed.Len() > 0 {
unassignprivateipaddressesrequest := map[string]interface{}{
"NetworkInterfaceId": d.Id(),
}
unassignprivateipaddressesrequest["PrivateIpAddress"] = removed.List()
unassignprivateipaddressesrequest["RegionId"] = client.RegionId
action := "UnassignPrivateIpAddresses"
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, unassignprivateipaddressesrequest, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"InternalError", "InvalidOperation.InvalidEcsState", "InvalidOperation.InvalidEniState", "OperationConflict", "ServiceUnavailable"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, unassignprivateipaddressesrequest)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("private_ip_addresses")
}
if added.Len() > 0 {
assignprivateipaddressesrequest := map[string]interface{}{
"NetworkInterfaceId": d.Id(),
}
assignprivateipaddressesrequest["PrivateIpAddress"] = added.List()
assignprivateipaddressesrequest["RegionId"] = client.RegionId
action := "AssignPrivateIpAddresses"
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, assignprivateipaddressesrequest, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"InternalError", "InvalidOperation.InvalidEcsState", "InvalidOperation.InvalidEniState", "OperationConflict", "ServiceUnavailable"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, assignprivateipaddressesrequest)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("private_ip_addresses")
}
if err := ecsService.WaitForPrivateIpsListChanged(d.Id(), expandStringList(newPrivateIpAddressesSet.List())); err != nil {
return WrapError(err)
}
}
if d.HasChange("private_ips") {
oldPrivateIps, newPrivateIps := d.GetChange("private_ips")
oldPrivateIpsSet := oldPrivateIps.(*schema.Set)
newPrivateIpsSet := newPrivateIps.(*schema.Set)
removed := oldPrivateIpsSet.Difference(newPrivateIpsSet)
added := newPrivateIpsSet.Difference(oldPrivateIpsSet)
if removed.Len() > 0 {
unassignprivateipaddressesrequest := map[string]interface{}{
"NetworkInterfaceId": d.Id(),
}
unassignprivateipaddressesrequest["PrivateIpAddress"] = removed.List()
unassignprivateipaddressesrequest["RegionId"] = client.RegionId
action := "UnassignPrivateIpAddresses"
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, unassignprivateipaddressesrequest, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"InternalError", "InvalidOperation.InvalidEcsState", "InvalidOperation.InvalidEniState", "OperationConflict", "ServiceUnavailable"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, unassignprivateipaddressesrequest)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("private_ips")
}
if added.Len() > 0 {
assignprivateipaddressesrequest := map[string]interface{}{
"NetworkInterfaceId": d.Id(),
}
assignprivateipaddressesrequest["PrivateIpAddress"] = added.List()
assignprivateipaddressesrequest["RegionId"] = client.RegionId
action := "AssignPrivateIpAddresses"
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, assignprivateipaddressesrequest, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"InternalError", "InvalidOperation.InvalidEcsState", "InvalidOperation.InvalidEniState", "OperationConflict", "ServiceUnavailable"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, assignprivateipaddressesrequest)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("private_ips")
}
if err := ecsService.WaitForPrivateIpsListChanged(d.Id(), expandStringList(newPrivateIpsSet.List())); err != nil {
return WrapError(err)
}
}
if d.HasChange("private_ips_count") {
privateIpList := expandStringList(d.Get("private_ips").(*schema.Set).List())
oldIpsCount, newIpsCount := d.GetChange("private_ips_count")
if oldIpsCount != nil && newIpsCount != nil && newIpsCount != len(privateIpList) {
diff := newIpsCount.(int) - oldIpsCount.(int)
if diff > 0 {
assignPrivateIpsCountrequest := map[string]interface{}{
"NetworkInterfaceId": d.Id(),
}
assignPrivateIpsCountrequest["RegionId"] = client.RegionId
assignPrivateIpsCountrequest["SecondaryPrivateIpAddressCount"] = requests.NewInteger(diff)
action := "AssignPrivateIpAddresses"
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, assignPrivateIpsCountrequest, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"InternalError", "InvalidOperation.InvalidEcsState", "InvalidOperation.InvalidEniState", "OperationConflict", "ServiceUnavailable"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, assignPrivateIpsCountrequest)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if diff < 0 {
diff *= -1
unAssignIps := privateIpList[:diff]
unAssignPrivateIpsCountRequest := map[string]interface{}{
"NetworkInterfaceId": d.Id(),
}
unAssignPrivateIpsCountRequest["RegionId"] = client.RegionId
unAssignPrivateIpsCountRequest["PrivateIpAddress"] = &unAssignIps
action := "UnassignPrivateIpAddresses"
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, unAssignPrivateIpsCountRequest, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"InternalError", "InvalidOperation.InvalidEcsState", "InvalidOperation.InvalidEniState", "OperationConflict", "ServiceUnavailable"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, unAssignPrivateIpsCountRequest)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
err := ecsService.WaitForPrivateIpsCountChanged(d.Id(), newIpsCount.(int))
if err != nil {
return WrapError(err)
}
d.SetPartial("private_ips_count")
}
}
if d.HasChange("secondary_private_ip_address_count") {
privateIpList := expandStringList(d.Get("private_ip_addresses").(*schema.Set).List())
oldIpsCount, newIpsCount := d.GetChange("secondary_private_ip_address_count")
if oldIpsCount != nil && newIpsCount != nil && newIpsCount != len(privateIpList) {
diff := newIpsCount.(int) - oldIpsCount.(int)
if diff > 0 {
assignSecondaryPrivateIpAddressCountrequest := map[string]interface{}{
"NetworkInterfaceId": d.Id(),
}
assignSecondaryPrivateIpAddressCountrequest["RegionId"] = client.RegionId
assignSecondaryPrivateIpAddressCountrequest["SecondaryPrivateIpAddressCount"] = requests.NewInteger(diff)
action := "AssignPrivateIpAddresses"
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, assignSecondaryPrivateIpAddressCountrequest, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"InternalError", "InvalidOperation.InvalidEcsState", "InvalidOperation.InvalidEniState", "OperationConflict", "ServiceUnavailable"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, assignSecondaryPrivateIpAddressCountrequest)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if diff < 0 {
diff *= -1
unAssignIps := privateIpList[:diff]
unassignSecondaryPrivateIpAddressCountrequest := map[string]interface{}{
"NetworkInterfaceId": d.Id(),
}
unassignSecondaryPrivateIpAddressCountrequest["RegionId"] = client.RegionId
unassignSecondaryPrivateIpAddressCountrequest["PrivateIpAddress"] = &unAssignIps
action := "UnassignPrivateIpAddresses"
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, unassignSecondaryPrivateIpAddressCountrequest, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"InternalError", "InvalidOperation.InvalidEcsState", "InvalidOperation.InvalidEniState", "OperationConflict", "ServiceUnavailable"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, unassignSecondaryPrivateIpAddressCountrequest)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
err := ecsService.WaitForPrivateIpsCountChanged(d.Id(), newIpsCount.(int))
if err != nil {
return WrapError(err)
}
d.SetPartial("secondary_private_ip_address_count")
}
}
return resourceAlicloudEcsNetworkInterfaceRead(d, meta)
}
func resourceAlicloudEcsNetworkInterfaceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteNetworkInterface"
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"NetworkInterfaceId": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidOperation.Conflict", "InternalError", "InvalidOperation.InvalidEcsState", "InvalidOperation.InvalidEniState", "OperationConflict", "ServiceUnavailable"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidEcsId.NotFound", "InvalidEniId.NotFound", "InvalidSecurityGroupId.NotFound", "InvalidVSwitchId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEcsNetworkInterfaceAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcsNetworkInterfaceAttachmentCreate,
Read: resourceAlicloudEcsNetworkInterfaceAttachmentRead,
Update: resourceAlicloudEcsNetworkInterfaceAttachmentUpdate,
Delete: resourceAlicloudEcsNetworkInterfaceAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(2 * time.Minute),
Delete: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"network_interface_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"trunk_network_instance_id": {
Type: schema.TypeString,
Optional: true,
},
"wait_for_network_configuration_ready": {
Type: schema.TypeBool,
Optional: true,
},
},
}
}
func resourceAlicloudEcsNetworkInterfaceAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
var response map[string]interface{}
action := "AttachNetworkInterface"
request := make(map[string]interface{})
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
request["InstanceId"] = d.Get("instance_id")
request["NetworkInterfaceId"] = d.Get("network_interface_id")
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("trunk_network_instance_id"); ok {
request["TrunkNetworkInstanceId"] = v
}
if v, ok := d.GetOkExists("wait_for_network_configuration_ready"); ok {
request["WaitForNetworkConfigurationReady"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) || IsExpectedErrors(err, NetworkInterfaceInvalidOperations) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecs_network_interface_attachment", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["NetworkInterfaceId"], ":", request["InstanceId"]))
parts, err := ParseResourceId(d.Id(), 2)
stateConf := BuildStateConf([]string{}, []string{"InUse"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, ecsService.EcsNetworkInterfaceStateRefreshFunc(parts[0], []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudEcsNetworkInterfaceAttachmentRead(d, meta)
}
func resourceAlicloudEcsNetworkInterfaceAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
object, err := ecsService.DescribeEcsNetworkInterfaceAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_netWork_interface_attachment ecsService.DescribeNetworkInterfaceAttachment Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_id", object["InstanceId"])
d.Set("network_interface_id", object["NetworkInterfaceId"])
return nil
}
func resourceAlicloudEcsNetworkInterfaceAttachmentUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return resourceAlicloudEcsNetworkInterfaceAttachmentRead(d, meta)
}
func resourceAlicloudEcsNetworkInterfaceAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DetachNetworkInterface"
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"InstanceId": parts[1],
"NetworkInterfaceId": parts[0],
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("trunk_network_instance_id"); ok {
request["TrunkNetworkInstanceId"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) || IsExpectedErrors(err, NetworkInterfaceInvalidOperations) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidEcsId.NotFound", "InvalidEniId.NotFound", "InvalidSecurityGroupId.NotFound", "InvalidVSwitchId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutDelete), 5*time.Second, ecsService.EcsNetworkInterfaceStateRefreshFunc(parts[0], []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudEcsPrefixList() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcsPrefixListCreate,
Read: resourceAlicloudEcsPrefixListRead,
Update: resourceAlicloudEcsPrefixListUpdate,
Delete: resourceAlicloudEcsPrefixListDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"address_family": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"IPv4", "IPv6"}, false),
},
"max_entries": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
ValidateFunc: validation.IntBetween(1, 200),
},
"entry": {
Type: schema.TypeSet,
Required: true,
MaxItems: 200,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cidr": {
Type: schema.TypeString,
Optional: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"prefix_list_name": {
Type: schema.TypeString,
Required: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudEcsPrefixListCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreatePrefixList"
request := make(map[string]interface{})
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
request["AddressFamily"] = d.Get("address_family")
request["MaxEntries"] = d.Get("max_entries")
request["PrefixListName"] = d.Get("prefix_list_name")
request["RegionId"] = client.RegionId
request["ClientToken"] = buildClientToken("CreatePrefixList")
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("entry"); ok {
for entryPtr, entry := range v.(*schema.Set).List() {
entryArg := entry.(map[string]interface{})
request["Entry."+fmt.Sprint(entryPtr+1)+".Cidr"] = entryArg["cidr"]
request["Entry."+fmt.Sprint(entryPtr+1)+".Description"] = entryArg["description"]
}
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecs_prefix_list", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["PrefixListId"]))
return resourceAlicloudEcsPrefixListRead(d, meta)
}
func resourceAlicloudEcsPrefixListRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
object, err := ecsService.DescribeEcsPrefixList(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecs_prefix_list ecsService.DescribeEcsPrefixList Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("address_family", object["AddressFamily"])
d.Set("description", object["Description"])
if entryMap, ok := object["Entries"].(map[string]interface{}); ok && entryMap != nil {
if entryList, ok := entryMap["Entry"]; ok && entryList != nil {
entryMaps := make([]map[string]interface{}, 0)
for _, entryListItem := range entryList.([]interface{}) {
if entryListItemMap, ok := entryListItem.(map[string]interface{}); ok {
res := make(map[string]interface{}, 0)
res["cidr"] = entryListItemMap["Cidr"]
res["description"] = entryListItemMap["Description"]
entryMaps = append(entryMaps, res)
}
}
d.Set("entry", entryMaps)
}
}
if v, ok := object["MaxEntries"]; ok && fmt.Sprint(v) != "0" {
d.Set("max_entries", formatInt(v))
}
d.Set("prefix_list_name", object["PrefixListName"])
return nil
}
func resourceAlicloudEcsPrefixListUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
update := false
request := map[string]interface{}{
"PrefixListId": d.Id(),
}
request["RegionId"] = client.RegionId
if d.HasChange("prefix_list_name") {
update = true
request["PrefixListName"] = d.Get("prefix_list_name")
}
if d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
}
if d.HasChange("entry") {
update = true
oraw, nraw := d.GetChange("entry")
remove := oraw.(*schema.Set).Difference(nraw.(*schema.Set)).List()
if len(remove) != 0 {
for entryPtr, entry := range remove {
entryArg := entry.(map[string]interface{})
request["RemoveEntry."+fmt.Sprint(entryPtr+1)+".Cidr"] = entryArg["cidr"]
}
}
added := nraw.(*schema.Set).Difference(oraw.(*schema.Set)).List()
if len(added) != 0 {
for entryPtr, entry := range added {
entryArg := entry.(map[string]interface{})
request["AddEntry."+fmt.Sprint(entryPtr+1)+".Cidr"] = entryArg["cidr"]
request["AddEntry."+fmt.Sprint(entryPtr+1)+".Description"] = entryArg["description"]
}
}
}
if update {
action := "ModifyPrefixList"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudEcsPrefixListRead(d, meta)
}
func resourceAlicloudEcsPrefixListDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeletePrefixList"
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"PrefixListId": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudEcsSessionManagerStatus() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcsSessionManagerStatusCreate,
Read: resourceAlicloudEcsSessionManagerStatusRead,
Update: resourceAlicloudEcsSessionManagerStatusUpdate,
Delete: resourceAlicloudEcsSessionManagerStatusDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"session_manager_status_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"sessionManagerStatus"}, false),
},
"status": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"Disabled", "Enabled"}, false),
},
},
}
}
func resourceAlicloudEcsSessionManagerStatusCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "ModifyUserBusinessBehavior"
request := make(map[string]interface{})
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
request["statusKey"] = d.Get("session_manager_status_name")
request["statusValue"] = convertEcsSessionManagerStatusStatusRequest(d.Get("status").(string))
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecs_session_manager_status", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["statusKey"]))
return resourceAlicloudEcsSessionManagerStatusRead(d, meta)
}
func resourceAlicloudEcsSessionManagerStatusRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
object, err := ecsService.DescribeEcsSessionManagerStatus(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecs_session_manager_status ecsService.DescribeEcsSessionManagerStatus Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("session_manager_status_name", d.Id())
d.Set("status", convertEcsSessionManagerStatusStatusResponse(object["StatusValue"]))
return nil
}
func resourceAlicloudEcsSessionManagerStatusUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
request := map[string]interface{}{
"statusKey": d.Id(),
}
if d.HasChange("status") {
request["statusValue"] = convertEcsSessionManagerStatusStatusRequest(d.Get("status").(string))
}
action := "ModifyUserBusinessBehavior"
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return resourceAlicloudEcsSessionManagerStatusRead(d, meta)
}
func resourceAlicloudEcsSessionManagerStatusDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudEcsSessionManagerStatus. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
func convertEcsSessionManagerStatusStatusRequest(source interface{}) interface{} {
switch source {
case "Disabled":
return "disabled"
case "Enabled":
return "enabled"
}
return source
}
func convertEcsSessionManagerStatusStatusResponse(source interface{}) interface{} {
switch source {
case "disabled":
return "Disabled"
case "enabled":
return "Enabled"
}
return source
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudEcsSnapshot() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcsSnapshotCreate,
Read: resourceAlicloudEcsSnapshotRead,
Update: resourceAlicloudEcsSnapshotUpdate,
Delete: resourceAlicloudEcsSnapshotDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(2 * time.Minute),
Delete: schema.DefaultTimeout(2 * time.Minute),
},
Schema: map[string]*schema.Schema{
"category": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"flash", "standard"}, false),
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"disk_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"force": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"instant_access": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"instant_access_retention_days": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IntBetween(1, 65535),
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"retention_days": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"snapshot_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"name"},
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Field 'name' has been deprecated from provider version 1.120.0. New field 'snapshot_name' instead.",
ConflictsWith: []string{"snapshot_name"},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
},
}
}
func resourceAlicloudEcsSnapshotCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
var response map[string]interface{}
action := "CreateSnapshot"
request := make(map[string]interface{})
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("category"); ok {
request["Category"] = v
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["DiskId"] = d.Get("disk_id")
if v, ok := d.GetOkExists("instant_access"); ok {
request["InstantAccess"] = v
}
if v, ok := d.GetOk("instant_access_retention_days"); ok {
request["InstantAccessRetentionDays"] = v
}
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("retention_days"); ok {
request["RetentionDays"] = v
}
if v, ok := d.GetOk("snapshot_name"); ok {
request["SnapshotName"] = v
} else if v, ok := d.GetOk("name"); ok {
request["SnapshotName"] = v
}
if v, ok := d.GetOk("tags"); ok {
count := 1
for key, value := range v.(map[string]interface{}) {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("CreateSnapshot")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecs_snapshot", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetId(fmt.Sprint(response["SnapshotId"]))
stateConf := BuildStateConf([]string{}, []string{"accomplished"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, ecsService.EcsSnapshotStateRefreshFunc(d.Id(), []string{"failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudEcsSnapshotRead(d, meta)
}
func resourceAlicloudEcsSnapshotRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
object, err := ecsService.DescribeEcsSnapshot(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecs_snapshot ecsService.DescribeEcsSnapshot Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("category", object["Category"])
d.Set("description", object["Description"])
d.Set("disk_id", object["SourceDiskId"])
d.Set("instant_access", object["InstantAccess"])
d.Set("instant_access_retention_days", formatInt(object["InstantAccessRetentionDays"]))
d.Set("resource_group_id", object["ResourceGroupId"])
d.Set("retention_days", formatInt(object["RetentionDays"]))
d.Set("snapshot_name", object["SnapshotName"])
d.Set("name", object["SnapshotName"])
d.Set("status", object["Status"])
tags, err := ecsService.ListTagResources(d.Id(), "snapshot")
if err != nil {
return WrapError(err)
} else {
d.Set("tags", tagsToMap(tags))
}
return nil
}
func resourceAlicloudEcsSnapshotUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
d.Partial(true)
if d.HasChange("tags") {
if err := ecsService.SetResourceTags(d, "snapshot"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
update := false
request := map[string]interface{}{
"SnapshotId": d.Id(),
}
if d.HasChange("description") {
update = true
request["Description"] = d.Get("description")
}
if d.HasChange("instant_access") {
update = true
request["DisableInstantAccess"] = d.Get("instant_access")
}
if d.HasChange("snapshot_name") {
update = true
request["SnapshotName"] = d.Get("snapshot_name")
}
if d.HasChange("name") {
update = true
request["SnapshotName"] = d.Get("name")
}
if update {
action := "ModifySnapshotAttribute"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("description")
d.SetPartial("instant_access")
d.SetPartial("name")
d.SetPartial("snapshot_name")
}
d.Partial(false)
return resourceAlicloudEcsSnapshotRead(d, meta)
}
func resourceAlicloudEcsSnapshotDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
action := "DeleteSnapshot"
var response map[string]interface{}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"SnapshotId": d.Id(),
}
if v, ok := d.GetOkExists("force"); ok {
request["Force"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidSnapshotId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, ecsService.EcsSnapshotStateRefreshFunc(d.Id(), []string{"failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"strconv"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/services/edas"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEdasApplication() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEdasApplicationCreate,
Update: resourceAlicloudEdasApplicationUpdate,
Read: resourceAlicloudEdasApplicationRead,
Delete: resourceAlicloudEdasApplicationDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"application_name": {
Type: schema.TypeString,
Required: true,
},
"package_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"JAR", "WAR"}, false),
},
"cluster_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"build_pack_id": {
Type: schema.TypeInt,
Optional: true,
},
"descriotion": {
Type: schema.TypeString,
Optional: true,
},
"health_check_url": {
Type: schema.TypeString,
Optional: true,
},
"logical_region_id": {
Type: schema.TypeString,
Optional: true,
},
"ecu_info": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
},
"group_id": {
Type: schema.TypeString,
Optional: true,
},
"package_version": {
Type: schema.TypeString,
Optional: true,
},
"war_url": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudEdasApplicationCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
request := edas.CreateInsertApplicationRequest()
request.ApplicationName = d.Get("application_name").(string)
request.RegionId = client.RegionId
request.PackageType = d.Get("package_type").(string)
request.ClusterId = d.Get("cluster_id").(string)
if v, ok := d.GetOk("build_pack_id"); ok {
request.BuildPackId = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("descriotion"); ok {
request.Description = v.(string)
}
if v, ok := d.GetOk("health_check_url"); ok {
request.HealthCheckUrl = v.(string)
}
if v, ok := d.GetOk("logical_region_id"); ok {
request.LogicalRegionId = v.(string)
}
if v, ok := d.GetOk("ecu_info"); ok {
ecuInfo := v.([]interface{})
aString := make([]string, len(ecuInfo))
for i, v := range ecuInfo {
aString[i] = v.(string)
}
request.EcuInfo = strings.Join(aString, ",")
}
var appId string
var changeOrderId string
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.InsertApplication(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_edas_application", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*edas.InsertApplicationResponse)
appId = response.ApplicationInfo.AppId
changeOrderId = response.ApplicationInfo.ChangeOrderId
d.SetId(appId)
if response.Code != 200 {
return WrapError(Error("create application failed for " + response.Message))
}
if len(changeOrderId) > 0 {
stateConf := BuildStateConf([]string{"0", "1"}, []string{"2"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, edasService.EdasChangeOrderStatusRefreshFunc(changeOrderId, []string{"3", "6", "10"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
// check url information
var groupId string
var warUrl string
if v, ok := d.GetOk("group_id"); ok {
groupId = v.(string)
}
if v, ok := d.GetOk("war_url"); ok {
warUrl = v.(string)
}
if len(warUrl) != 0 && len(groupId) != 0 {
// deploy application
var packageVersion string
if v, ok := d.GetOk("package_version"); ok {
packageVersion = v.(string)
} else {
packageVersion = strconv.FormatInt(time.Now().Unix(), 10)
}
request := edas.CreateDeployApplicationRequest()
request.RegionId = client.RegionId
request.AppId = appId
request.GroupId = groupId
request.PackageVersion = packageVersion
request.DeployType = "url"
request.WarUrl = warUrl
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.DeployApplication(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*edas.DeployApplicationResponse)
changeOrderId := response.ChangeOrderId
if response.Code != 200 {
return WrapError(Error("deploy application failed for " + response.Message))
}
if len(changeOrderId) > 0 {
stateConf := BuildStateConf([]string{"0", "1"}, []string{"2"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, edasService.EdasChangeOrderStatusRefreshFunc(changeOrderId, []string{"3", "6", "10"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
}
return resourceAlicloudEdasApplicationRead(d, meta)
}
func resourceAlicloudEdasApplicationUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
if d.HasChange("application_name") || d.HasChange("descriotion") {
request := edas.CreateUpdateApplicationBaseInfoRequest()
request.AppId = d.Id()
request.RegionId = client.RegionId
request.AppName = d.Get("application_name").(string)
if v, ok := d.GetOk("descriotion"); ok {
request.Desc = v.(string)
}
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.UpdateApplicationBaseInfo(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
}
time.Sleep(3 * time.Second)
return resourceAlicloudEdasApplicationRead(d, meta)
}
func resourceAlicloudEdasApplicationRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
regionId := client.RegionId
appId := d.Id()
request := edas.CreateGetApplicationRequest()
request.RegionId = regionId
request.AppId = appId
wait := incrementalWait(1*time.Second, 2*time.Second)
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.GetApplication(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*edas.GetApplicationResponse)
d.Set("application_name", response.Applcation.Name)
d.Set("cluster_id", response.Applcation.ClusterId)
d.Set("build_pack_id", response.Applcation.BuildPackageId)
d.Set("descriotion", response.Applcation.Description)
d.Set("health_check_url", response.Applcation.HealthCheckUrl)
if len(response.Applcation.ApplicationType) > 0 && response.Applcation.ApplicationType == "FatJar" {
d.Set("package_type", "JAR")
} else {
d.Set("package_type", "WAR")
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_edas_application", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return nil
}
func resourceAlicloudEdasApplicationDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
regionId := client.RegionId
appId := d.Id()
request := edas.CreateStopApplicationRequest()
request.RegionId = regionId
request.AppId = appId
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.StopApplication(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*edas.StopApplicationResponse)
changeOrderId := response.ChangeOrderId
if len(changeOrderId) > 0 {
stateConf := BuildStateConf([]string{"0", "1"}, []string{"2"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, edasService.EdasChangeOrderStatusRefreshFunc(changeOrderId, []string{"3", "6", "10"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
req := edas.CreateDeleteApplicationRequest()
req.RegionId = regionId
req.AppId = d.Id()
wait := incrementalWait(1*time.Second, 2*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.DeleteApplication(req)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(req.GetActionName(), raw, req.RoaRequest, req)
rsp := raw.(*edas.DeleteApplicationResponse)
if rsp.Code == 601 && strings.Contains(rsp.Message, "Operation cannot be processed because there are running instances.") {
err = Error("Operation cannot be processed because there are running instances.")
return resource.RetryableError(err)
}
changeOrderId := response.ChangeOrderId
if len(changeOrderId) > 0 {
stateConf := BuildStateConf([]string{"0", "1"}, []string{"2"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, edasService.EdasChangeOrderStatusRefreshFunc(changeOrderId, []string{"3", "6", "10"}))
if _, err := stateConf.WaitForState(); err != nil {
return resource.NonRetryableError(WrapErrorf(err, IdMsg, d.Id()))
}
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), req.GetActionName(), AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"strconv"
"time"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/services/edas"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEdasApplicationPackageAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEdasApplicationPackageAttachmentCreate,
Read: resourceAlicloudEdasApplicationPackageAttachmentRead,
Delete: resourceAlicloudEdasApplicationPackageAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"app_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"package_version": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"war_url": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"last_package_version": {
Type: schema.TypeString,
Computed: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudEdasApplicationPackageAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
appId := d.Get("app_id").(string)
groupId := d.Get("group_id").(string)
request := edas.CreateDeployApplicationRequest()
request.RegionId = client.RegionId
request.AppId = appId
request.GroupId = groupId
request.WarUrl = d.Get("war_url").(string)
var packageVersion string
if v, ok := d.GetOk("package_version"); ok {
packageVersion = v.(string)
} else {
packageVersion = strconv.FormatInt(time.Now().Unix(), 10)
}
request.DeployType = "url"
request.PackageVersion = packageVersion
if version, err := edasService.GetLastPackgeVersion(appId, groupId); err != nil {
return WrapError(err)
} else {
d.Set("last_package_version", version)
}
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.DeployApplication(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*edas.DeployApplicationResponse)
changeOrderId := response.ChangeOrderId
if response.Code != 200 {
return WrapError(Error("deploy application failed for " + response.Message))
}
if len(changeOrderId) > 0 {
stateConf := BuildStateConf([]string{"0", "1"}, []string{"2"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, edasService.EdasChangeOrderStatusRefreshFunc(changeOrderId, []string{"3", "6", "10"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.SetId(appId + ":" + packageVersion)
return resourceAlicloudEdasApplicationPackageAttachmentRead(d, meta)
}
func resourceAlicloudEdasApplicationPackageAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
regionId := client.RegionId
appId := strings.Split(d.Id(), ":")[0]
request := edas.CreateQueryApplicationStatusRequest()
request.RegionId = regionId
request.AppId = appId
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.QueryApplicationStatus(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_edas_application_package_attachment", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*edas.QueryApplicationStatusResponse)
if response.Code != 200 {
return WrapError(Error("QueryApplicationStatus failed for " + response.Message))
}
groupId := d.Get("group_id").(string)
for _, group := range response.AppInfo.GroupList.Group {
if group.GroupId == groupId {
d.SetId(appId + ":" + group.PackageVersionId)
}
}
return nil
}
func resourceAlicloudEdasApplicationPackageAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
regionId := client.RegionId
appId := d.Get("app_id").(string)
packageVersion := d.Get("last_package_version").(string)
groupId := d.Get("group_id").(string)
if len(packageVersion) == 0 {
return nil
}
request := edas.CreateRollbackApplicationRequest()
request.RegionId = regionId
request.AppId = appId
request.HistoryVersion = packageVersion
request.GroupId = groupId
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.RollbackApplication(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*edas.RollbackApplicationResponse)
changeOrderId := response.ChangeOrderId
if response.Code != 200 && !strings.Contains(response.Message, "ex.app.deploy.group.empty") {
return WrapError(Error("deploy application failed for " + response.Message))
}
if len(changeOrderId) > 0 {
stateConf := BuildStateConf([]string{"0", "1"}, []string{"2"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, edasService.EdasChangeOrderStatusRefreshFunc(changeOrderId, []string{"3", "6", "10"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return nil
}
package alicloud
import (
"time"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/edas"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEdasCluster() *schema.Resource {
return &schema.Resource{
Create: rresourceAlicloudEdasClusterCreate,
Read: resourceAlicloudEdasClusterRead,
Delete: resourceAlicloudEdasClusterDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"cluster_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"cluster_type": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3}),
},
"network_mode": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
ValidateFunc: validation.IntInSlice([]int{1, 2}),
},
"logical_region_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
}
}
func rresourceAlicloudEdasClusterCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
request := edas.CreateInsertClusterRequest()
request.RegionId = client.RegionId
request.ClusterName = d.Get("cluster_name").(string)
request.ClusterType = requests.NewInteger(d.Get("cluster_type").(int))
request.NetworkMode = requests.NewInteger(d.Get("network_mode").(int))
if v, ok := d.GetOk("logical_region_id"); ok {
request.LogicalRegionId = v.(string)
}
if v, ok := d.GetOk("vpc_id"); !ok {
if d.Get("network_mode").(int) == 2 {
return WrapError(Error("vpcId is required for vpc network mode"))
}
} else {
request.VpcId = v.(string)
}
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.InsertCluster(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_edas_cluster", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*edas.InsertClusterResponse)
if response.Code != 200 {
return WrapError(Error("create cluster failed for " + response.Message))
}
d.SetId(response.Cluster.ClusterId)
return resourceAlicloudEdasClusterRead(d, meta)
}
func resourceAlicloudEdasClusterRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
clusterId := d.Id()
regionId := client.RegionId
request := edas.CreateGetClusterRequest()
request.RegionId = regionId
request.ClusterId = clusterId
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.GetCluster(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_edas_cluster", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*edas.GetClusterResponse)
if response.Code != 200 {
return WrapError(Error("create cluster failed for " + response.Message))
}
d.Set("cluster_name", response.Cluster.ClusterName)
d.Set("cluster_type", response.Cluster.ClusterType)
d.Set("network_mode", response.Cluster.NetworkMode)
d.Set("vpc_id", response.Cluster.VpcId)
return nil
}
func resourceAlicloudEdasClusterDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
clusterId := d.Id()
regionId := client.RegionId
request := edas.CreateDeleteClusterRequest()
request.RegionId = regionId
request.ClusterId = clusterId
wait := incrementalWait(1*time.Second, 2*time.Second)
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.DeleteCluster(request)
})
response, _ := raw.(*edas.DeleteClusterResponse)
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if response.Code != 200 {
if strings.Contains(response.Message, "there are still instances in it") {
return resource.RetryableError(Error("delete cluster failed for " + response.Message))
}
return resource.NonRetryableError(Error("delete cluster failed for " + response.Message))
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/edas"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEdasDeployGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEdasDeployGroupCreate,
Read: resourceAlicloudEdasDeployGroupRead,
Delete: resourceAlicloudEdasDeployGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"app_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"group_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"group_type": {
Type: schema.TypeInt,
Computed: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudEdasDeployGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
appId := d.Get("app_id").(string)
regionId := client.RegionId
groupName := d.Get("group_name").(string)
request := edas.CreateInsertDeployGroupRequest()
request.RegionId = regionId
request.AppId = appId
request.GroupName = groupName
wait := incrementalWait(1*time.Second, 2*time.Second)
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.InsertDeployGroup(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
response := raw.(*edas.InsertDeployGroupResponse)
deployGroup := response.DeployGroupEntity
d.SetId(appId + ":" + groupName + ":" + deployGroup.Id)
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_edas_deploy_group", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return resourceAlicloudEdasDeployGroupRead(d, meta)
}
func resourceAlicloudEdasDeployGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
strs, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
appId := strs[0]
groupId := strs[2]
deployGroup, err := edasService.GetDeployGroup(appId, groupId)
if err != nil {
return WrapError(err)
}
if deployGroup == nil {
return nil
}
d.Set("group_type", deployGroup.GroupType)
d.Set("app_id", deployGroup.AppId)
d.Set("group_name", deployGroup.GroupName)
return nil
}
func resourceAlicloudEdasDeployGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
request := edas.CreateDeleteDeployGroupRequest()
request.RegionId = client.RegionId
request.AppId = d.Get("app_id").(string)
request.GroupName = d.Get("group_name").(string)
wait := incrementalWait(1*time.Second, 2*time.Second)
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.DeleteDeployGroup(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/edas"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEdasInstanceApplicationAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEdasInstanceApplicationAttachmentCreate,
Read: resourceAlicloudEdasInstanceApplicationAttachmentRead,
Delete: resourceAlicloudEdasInstanceApplicationAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"ecc_info": {
Type: schema.TypeString,
Computed: true,
ForceNew: true,
},
"app_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"deploy_group": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"force_status": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"ecu_info": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudEdasInstanceApplicationAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
appId := d.Get("app_id").(string)
ecuInfo := d.Get("ecu_info").([]interface{})
aString := make([]string, len(ecuInfo))
for i, v := range ecuInfo {
aString[i] = v.(string)
}
request := edas.CreateScaleOutApplicationRequest()
request.RegionId = client.RegionId
request.AppId = appId
request.DeployGroup = d.Get("deploy_group").(string)
request.EcuInfo = strings.Join(aString, ",")
var changeOrderId string
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.ScaleOutApplication(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_edas_instance_application_attachment", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*edas.ScaleOutApplicationResponse)
changeOrderId = response.ChangeOrderId
d.SetId(appId + ":" + strings.Join(aString, ","))
if response.Code != 200 {
return WrapError(Error("scaleOut application failed for " + response.Message))
}
if len(changeOrderId) > 0 {
stateConf := BuildStateConf([]string{"0", "1"}, []string{"2"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, edasService.EdasChangeOrderStatusRefreshFunc(changeOrderId, []string{"3", "6", "10"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudEdasInstanceApplicationAttachmentRead(d, meta)
}
func resourceAlicloudEdasInstanceApplicationAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
strs, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
appId := strs[0]
regionId := client.RegionId
ecuInfo := strs[1]
aString := strings.Split(ecuInfo, ",")
request := edas.CreateQueryApplicationStatusRequest()
request.RegionId = regionId
request.AppId = appId
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.QueryApplicationStatus(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_edas_instance_application_attachment", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
var eccs []string
response := raw.(*edas.QueryApplicationStatusResponse)
if response.Code != 200 {
return WrapError(Error("QueryApplicationStatus failed for " + response.Message))
}
for _, ecc := range response.AppInfo.EccList.Ecc {
for _, ecu := range aString {
if ecu == ecc.EcuId {
eccs = append(eccs, ecc.EccId)
}
}
}
d.Set("ecc_info", strings.Join(eccs, ","))
return nil
}
func resourceAlicloudEdasInstanceApplicationAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
request := edas.CreateScaleInApplicationRequest()
request.RegionId = client.RegionId
request.AppId = d.Get("app_id").(string)
request.EccInfo = d.Get("ecc_info").(string)
if v, ok := d.GetOk("force_status"); ok {
request.ForceStatus = requests.NewBoolean(v.(bool))
}
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.ScaleInApplication(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_edas_instance_application_attachment", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
var changeOrderId string
response, _ := raw.(*edas.ScaleInApplicationResponse)
if response.Code != 200 {
return WrapError(Error("scaleIn application failed for " + response.Message))
}
changeOrderId = response.ChangeOrderId
if len(changeOrderId) > 0 {
stateConf := BuildStateConf([]string{"0", "1"}, []string{"2"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, edasService.EdasChangeOrderStatusRefreshFunc(changeOrderId, []string{"3", "6", "10"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return nil
}
package alicloud
import (
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/aliyun/alibaba-cloud-sdk-go/services/edas"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEdasInstanceClusterAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEdasInstanceClusterAttachmentCreate,
Read: resourceAlicloudEdasInstanceClusterAttachmentRead,
Delete: resourceAlicloudEdasInstanceClusterAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"cluster_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Required: true,
ForceNew: true,
},
"status_map": {
Type: schema.TypeMap,
Elem: &schema.Schema{
Type: schema.TypeInt,
},
Computed: true,
ForceNew: true,
},
"ecu_map": {
Type: schema.TypeMap,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Computed: true,
ForceNew: true,
},
"cluster_member_ids": {
Type: schema.TypeMap,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Computed: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudEdasInstanceClusterAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
clusterId := d.Get("cluster_id").(string)
instanceIds := d.Get("instance_ids").([]interface{})
aString := make([]string, len(instanceIds))
for i, v := range instanceIds {
aString[i] = v.(string)
}
request := edas.CreateInstallAgentRequest()
request.ClusterId = clusterId
request.RegionId = client.RegionId
request.InstanceIds = strings.Join(aString, ",")
request.SetReadTimeout(30 * time.Second)
if err := edasService.SyncResource("ecs"); err != nil {
return err
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err := resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.InstallAgent(request)
})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*edas.InstallAgentResponse)
if response.Code != 200 {
return resource.NonRetryableError(Error("insert instances to cluster failed for " + response.Message))
}
var instanceIdFailed []string
for _, result := range response.ExecutionResultList.ExecutionResult {
if !result.Success {
instanceIdFailed = append(instanceIdFailed, result.InstanceId)
}
}
if len(instanceIdFailed) > 0 {
err = Error("instances still import failed, try again")
request.InstanceIds = strings.Join(instanceIdFailed, ",")
return resource.RetryableError(err)
}
d.SetId(clusterId + ":" + strings.Join(aString, ","))
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_edas_instance_cluster_attachment", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return resourceAlicloudEdasInstanceClusterAttachmentRead(d, meta)
}
func resourceAlicloudEdasInstanceClusterAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
strs, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
clusterId := strs[0]
regionId := client.RegionId
instanceIdstr := strs[1]
request := edas.CreateListClusterMembersRequest()
request.RegionId = regionId
request.ClusterId = clusterId
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.ListClusterMembers(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_edas_instance_cluster_attachment", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
statusMap := make(map[string]int)
ecuMap := make(map[string]string)
memMap := make(map[string]string)
response := raw.(*edas.ListClusterMembersResponse)
for _, member := range response.ClusterMemberPage.ClusterMemberList.ClusterMember {
if strings.Contains(instanceIdstr, member.EcsId) {
statusMap[member.EcsId] = member.Status
ecuMap[member.EcsId] = member.EcuId
memMap[member.EcsId] = member.ClusterMemberId
}
}
d.Set("status_map", statusMap)
d.Set("ecu_map", ecuMap)
d.Set("cluster_member_ids", memMap)
return nil
}
//有问题 单个实例删除失败会影响整个过程
func resourceAlicloudEdasInstanceClusterAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
memIds := d.Get("cluster_member_ids").(map[string]interface{})
for instanceId, memberId := range memIds {
request := edas.CreateDeleteClusterMemberRequest()
request.RegionId = client.RegionId
request.ClusterId = d.Get("cluster_id").(string)
request.ClusterMemberId = memberId.(string)
wait := incrementalWait(3*time.Second, 3*time.Second)
err := resource.Retry(1*time.Minute, func() *resource.RetryError {
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.DeleteClusterMember(request)
})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*edas.DeleteClusterMemberResponse)
if strings.Contains(response.Message, "there are still applications deployed in this cluster") {
err = Error("there are still applications deployed in this cluster")
return resource.RetryableError(err)
} else if response.Code != 200 {
return resource.NonRetryableError(Error("delete instance:" + instanceId + " from cluster failed for " + response.Message))
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_edas_instance_cluster_attachment", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
return nil
}
package alicloud
import (
"log"
"strconv"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/services/edas"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEdasK8sApplication() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEdasK8sApplicationCreate,
Read: resourceAlicloudEdasK8sApplicationRead,
Update: resourceAlicloudEdasK8sApplicationUpdate,
Delete: resourceAlicloudEdasK8sApplicationDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
Delete: schema.DefaultTimeout(30 * time.Minute),
},
Schema: map[string]*schema.Schema{
"application_name": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"cluster_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"replicas": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
},
"image_url": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"package_url"},
},
"package_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"FatJar", "War", "Image"}, false),
Default: "Image",
},
"application_descriotion": {
Type: schema.TypeString,
Optional: true,
},
"limit_mem": {
Type: schema.TypeInt,
Optional: true,
},
"requests_mem": {
Type: schema.TypeInt,
Optional: true,
},
"command": {
Type: schema.TypeString,
Optional: true,
},
"command_args": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
},
"internet_slb_id": {
Optional: true,
Type: schema.TypeString,
ForceNew: true,
},
"internet_slb_protocol": {
Optional: true,
Type: schema.TypeString,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"TCP", "HTTP", "HTTPS"}, false),
},
"internet_slb_port": {
Type: schema.TypeInt,
ForceNew: true,
Optional: true,
},
"internet_target_port": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"envs": {
Type: schema.TypeMap,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Optional: true,
},
"pre_stop": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
e := EdasService{}
return e.PreStopEqual(old, new)
},
},
"post_start": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
e := EdasService{}
return e.PostStartEqual(old, new)
},
},
"liveness": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
e := EdasService{}
return e.LivenessEqual(old, new)
},
},
"readiness": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
e := EdasService{}
return e.ReadinessEqual(old, new)
},
},
"nas_id": {
Type: schema.TypeString,
Optional: true,
},
"mount_descs": {
Type: schema.TypeString,
Optional: true,
},
"local_volume": {
Type: schema.TypeString,
Optional: true,
},
"namespace": {
Type: schema.TypeString,
Optional: true,
},
"logical_region_id": {
Type: schema.TypeString,
Optional: true,
},
"package_url": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"image_url"},
},
"package_version": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"jdk": {
Type: schema.TypeString,
Optional: true,
},
"web_container": {
Type: schema.TypeString,
Optional: true,
},
"edas_container_version": {
Type: schema.TypeString,
Optional: true,
},
"requests_m_cpu": {
Type: schema.TypeInt,
Optional: true,
},
"limit_m_cpu": {
Type: schema.TypeInt,
Optional: true,
},
},
}
}
func resourceAlicloudEdasK8sApplicationCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
request := edas.CreateInsertK8sApplicationRequest()
packageType := d.Get("package_type").(string)
request.AppName = d.Get("application_name").(string)
request.RegionId = client.RegionId
request.PackageType = packageType
request.ClusterId = d.Get("cluster_id").(string)
if strings.ToLower(packageType) == "image" {
if v, ok := d.GetOk("image_url"); !ok {
return WrapError(Error("image_url is needed for creating image k8s application"))
} else {
request.ImageUrl = v.(string)
}
} else {
if v, ok := d.GetOk("package_url"); !ok {
return WrapError(Error("package_url is needed for creating fatjar k8s application"))
} else {
request.PackageUrl = v.(string)
}
if v, ok := d.GetOk("package_version"); ok {
request.PackageVersion = v.(string)
} else {
request.PackageVersion = strconv.FormatInt(time.Now().Unix(), 10)
}
if v, ok := d.GetOk("jdk"); !ok {
return WrapError(Error("jdk is needed for creating non-image k8s application"))
} else {
request.JDK = v.(string)
}
if strings.ToLower(packageType) == "war" {
var webContainer string
var edasContainer string
if v, ok := d.GetOk("web_container"); ok {
webContainer = v.(string)
}
if v, ok := d.GetOk("edas_container_version"); ok {
edasContainer = v.(string)
}
if len(webContainer) == 0 && len(edasContainer) == 0 {
return WrapError(Error("web_container or edas_container_version is needed for creating war k8s application"))
}
request.WebContainer = webContainer
request.EdasContainerVersion = edasContainer
}
}
request.Replicas = requests.NewInteger(d.Get("replicas").(int))
if v, ok := d.GetOk("application_descriotion"); ok {
request.ApplicationDescription = v.(string)
}
if v, ok := d.GetOk("limit_mem"); ok {
request.LimitMem = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("requests_mem"); ok {
request.RequestsMem = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("command"); ok {
request.Command = v.(string)
}
if v, ok := d.GetOk("command_args"); ok {
commands, err := edasService.GetK8sCommandArgs(v.([]interface{}))
if err != nil {
return WrapError(err)
}
request.CommandArgs = commands
}
if v, ok := d.GetOk("internet_slb_id"); ok {
request.InternetSlbId = v.(string)
}
if v, ok := d.GetOk("internet_slb_protocol"); ok {
request.InternetSlbProtocol = v.(string)
}
if v, ok := d.GetOk("internet_slb_port"); ok {
request.InternetSlbPort = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("internet_target_port"); ok {
request.InternetTargetPort = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("envs"); ok {
envs, err := edasService.GetK8sEnvs(v.(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request.Envs = envs
}
if v, ok := d.GetOk("pre_stop"); ok {
request.PreStop = v.(string)
}
if v, ok := d.GetOk("post_start"); ok {
request.PostStart = v.(string)
}
if v, ok := d.GetOk("liveness"); ok {
request.Liveness = v.(string)
}
if v, ok := d.GetOk("readiness"); ok {
request.Readiness = v.(string)
}
if v, ok := d.GetOk("nas_id"); ok {
request.NasId = v.(string)
}
if v, ok := d.GetOk("mount_descs"); ok {
request.MountDescs = v.(string)
}
if v, ok := d.GetOk("local_volume"); ok {
request.LocalVolume = v.(string)
}
if v, ok := d.GetOk("namespace"); ok {
request.Namespace = v.(string)
}
if v, ok := d.GetOk("logical_region_id"); ok {
request.LogicalRegionId = v.(string)
}
if v, ok := d.GetOk("requests_m_cpu"); ok {
request.RequestsmCpu = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("limit_m_cpu"); ok {
request.LimitmCpu = requests.NewInteger(v.(int))
}
var appId string
var changeOrderId string
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.InsertK8sApplication(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_edas_k8s_application", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*edas.InsertK8sApplicationResponse)
appId = response.ApplicationInfo.AppId
changeOrderId = response.ApplicationInfo.ChangeOrderId
d.SetId(appId)
if response.Code != 200 {
return WrapError(Error("Create k8s application failed for " + response.Message))
}
if len(changeOrderId) > 0 {
stateConf := BuildStateConf([]string{"0", "1"}, []string{"2"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, edasService.EdasChangeOrderStatusRefreshFunc(changeOrderId, []string{"3", "6", "10"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudEdasK8sApplicationRead(d, meta)
}
func resourceAlicloudEdasK8sApplicationRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
response, err := edasService.DescribeEdasK8sApplication(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_edas_k8s_application ecsService.DescribeEdasK8sApplication Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("application_name", response.App.ApplicationName)
d.Set("application_descriotion", response.App.Description)
d.Set("cluster_id", response.App.ClusterId)
d.Set("replicas", response.App.Instances)
d.Set("package_type", response.App.ApplicationType)
d.Set("image_url", response.ImageInfo.ImageUrl)
envs := make(map[string]string)
for _, e := range response.App.EnvList.Env {
envs[e.Name] = e.Value
}
d.Set("envs", envs)
d.Set("command", response.App.Cmd)
d.Set("command_args", response.App.CmdArgs.CmdArg)
allDeploy := response.DeployGroups.DeployGroup
for _, v := range allDeploy {
if len(v.PackageUrl) > 0 {
d.Set("package_url", v.PackageUrl)
}
if len(v.PackageVersion) > 0 {
d.Set("package_version", v.PackageVersion)
}
if len(v.MemoryLimit) > 0 {
d.Set("limit_mem", v.MemoryLimit)
}
if len(v.MemoryRequest) > 0 {
d.Set("requests_mem", v.MemoryRequest)
}
if len(v.CpuRequest) > 0 {
cpu, err := strconv.Atoi(v.CpuRequest)
if err != nil {
return WrapError(err)
}
d.Set("requests_m_cpu", cpu*1000)
}
for _, c := range v.Components.ComponentsItem {
if strings.Contains(c.ComponentKey, "JDK") {
d.Set("jdk", c.ComponentKey)
}
}
}
if len(response.App.EdasContainerVersion) > 0 {
d.Set("edas_container_version", response.App.EdasContainerVersion)
}
if len(response.Conf.PreStop) > 0 {
d.Set("pre_stop", response.Conf.PreStop)
}
if len(response.Conf.PostStart) > 0 {
d.Set("post_start", response.Conf.PostStart)
}
if len(response.Conf.Liveness) > 0 {
d.Set("liveness", response.Conf.Liveness)
}
if len(response.Conf.Readiness) > 0 {
d.Set("readiness", response.Conf.Readiness)
}
d.Set("namespace", response.NameSpace)
return nil
}
func resourceAlicloudEdasK8sApplicationUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
var partialKeys []string
request := edas.CreateDeployK8sApplicationRequest()
request.AppId = d.Id()
request.RegionId = client.RegionId
d.Partial(true)
packageType, err := edasService.QueryK8sAppPackageType(d.Id())
if err != nil {
return WrapError(err)
}
if strings.ToLower(packageType) == "image" {
if d.HasChange("image_url") {
partialKeys = append(partialKeys, "image_url")
}
request.Image = d.Get("image_url").(string)
if len(request.Image) == 0 {
return WrapError(Error("image_url is needed for creating image k8s application"))
}
} else {
if d.HasChange("package_url") {
partialKeys = append(partialKeys, "package_url")
}
request.PackageUrl = d.Get("package_url").(string)
if len(request.PackageUrl) == 0 {
return WrapError(Error("package_url is needed for creating fatjar k8s application"))
}
if v, ok := d.GetOk("package_version"); ok {
request.PackageVersion = v.(string)
} else {
request.PackageVersion = strconv.FormatInt(time.Now().Unix(), 10)
}
if d.HasChange("jdk") {
partialKeys = append(partialKeys, "jdk")
}
request.JDK = d.Get("jdk").(string)
if len(request.JDK) == 0 {
return WrapError(Error("jdk is needed for creating non-image k8s application"))
}
if strings.ToLower(packageType) == "war" {
var webContainer string
var edasContainer string
if d.HasChange("web_container") {
partialKeys = append(partialKeys, "web_container")
}
webContainer = d.Get("web_container").(string)
if d.HasChange("edas_container_version") {
partialKeys = append(partialKeys, "edas_container_version")
}
edasContainer = d.Get("edas_container_version").(string)
if len(webContainer) == 0 && len(edasContainer) == 0 {
return WrapError(Error("web_container or edas_container_version is needed for updating war k8s application"))
}
request.WebContainer = webContainer
request.EdasContainerVersion = edasContainer
}
}
if d.HasChange("replicas") {
partialKeys = append(partialKeys, "replicas")
}
request.Replicas = requests.NewInteger(d.Get("replicas").(int))
if d.HasChange("limit_mem") {
partialKeys = append(partialKeys, "limit_mem")
request.MemoryLimit = requests.NewInteger(d.Get("limit_mem").(int))
}
if d.HasChange("requests_mem") {
partialKeys = append(partialKeys, "requests_mem")
request.MemoryRequest = requests.NewInteger(d.Get("requests_mem").(int))
}
if d.HasChange("command") {
partialKeys = append(partialKeys, "command")
request.Command = d.Get("command").(string)
}
if d.HasChange("command_args") {
partialKeys = append(partialKeys, "command_args")
commands, err := edasService.GetK8sCommandArgsForDeploy(d.Get("command_args").([]interface{}))
if err != nil {
return WrapError(err)
}
request.Args = commands
}
if d.HasChange("envs") {
partialKeys = append(partialKeys, "envs")
envs, err := edasService.GetK8sEnvs(d.Get("envs").(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request.Envs = envs
}
if d.HasChange("pre_stop") {
if !edasService.PreStopEqual(d.GetChange("pre_stop")) {
partialKeys = append(partialKeys, "pre_stop")
request.PreStop = d.Get("pre_stop").(string)
}
}
if d.HasChange("post_start") {
if !edasService.PostStartEqual(d.GetChange("post_start")) {
partialKeys = append(partialKeys, "post_start")
request.PostStart = d.Get("post_start").(string)
}
}
if d.HasChange("liveness") {
if !edasService.LivenessEqual(d.GetChange("liveness")) {
partialKeys = append(partialKeys, "liveness")
request.Liveness = d.Get("liveness").(string)
}
}
if d.HasChange("readiness") {
if !edasService.ReadinessEqual(d.GetChange("readiness")) {
partialKeys = append(partialKeys, "readiness")
request.Readiness = d.Get("readiness").(string)
}
}
if d.HasChange("nas_id") {
partialKeys = append(partialKeys, "nas_id")
request.NasId = d.Get("nas_id").(string)
}
if d.HasChange("mount_descs") {
partialKeys = append(partialKeys, "mount_descs")
request.MountDescs = d.Get("mount_descs").(string)
}
if d.HasChange("local_volume") {
partialKeys = append(partialKeys, "local_volume")
request.LocalVolume = d.Get("local_volume").(string)
}
if d.HasChange("requests_m_cpu") {
partialKeys = append(partialKeys, "requests_m_cpu")
request.McpuRequest = requests.NewInteger(d.Get("requests_m_cpu").(int))
}
if d.HasChange("limit_m_cpu") {
partialKeys = append(partialKeys, "limit_m_cpu")
request.McpuLimit = requests.NewInteger(d.Get("limit_m_cpu").(int))
}
if len(partialKeys) > 0 {
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.DeployK8sApplication(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*edas.DeployK8sApplicationResponse)
changeOrderId := response.ChangeOrderId
if response.Code != 200 {
return WrapError(Error("deploy k8s application failed for " + response.Message))
}
if len(changeOrderId) > 0 {
stateConf := BuildStateConf([]string{"0", "1"}, []string{"2"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, edasService.EdasChangeOrderStatusRefreshFunc(changeOrderId, []string{"3", "6", "10"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
for _, key := range partialKeys {
d.SetPartial(key)
}
}
d.Partial(false)
return resourceAlicloudEdasK8sApplicationRead(d, meta)
}
func resourceAlicloudEdasK8sApplicationDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
request := edas.CreateDeleteK8sApplicationRequest()
request.RegionId = client.RegionId
request.AppId = d.Id()
wait := incrementalWait(1*time.Second, 2*time.Second)
err := resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.DeleteK8sApplication(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response := raw.(*edas.DeleteK8sApplicationResponse)
if response.Code != 200 {
return resource.NonRetryableError(Error("Delete k8s application failed for " + response.Message))
}
changeOrderId := response.ChangeOrderId
if len(changeOrderId) > 0 {
stateConf := BuildStateConf([]string{"0", "1"}, []string{"2"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, edasService.EdasChangeOrderStatusRefreshFunc(changeOrderId, []string{"3", "6", "10"}))
if _, err := stateConf.WaitForState(); err != nil {
return resource.NonRetryableError(WrapErrorf(err, IdMsg, d.Id()))
}
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/edas"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEdasK8sCluster() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEdasK8sClusterCreate,
Read: resourceAlicloudEdasK8sClusterRead,
Delete: resourceAlicloudEdasK8sClusterDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"cs_cluster_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"namespace_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"cluster_name": {
Type: schema.TypeString,
Computed: true,
},
"cluster_type": {
Type: schema.TypeInt,
Computed: true,
},
"network_mode": {
Type: schema.TypeInt,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"cluster_import_status": {
Type: schema.TypeInt,
Computed: true,
},
},
}
}
func resourceAlicloudEdasK8sClusterCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
request := edas.CreateImportK8sClusterRequest()
request.RegionId = client.RegionId
request.ClusterId = d.Get("cs_cluster_id").(string)
if v, ok := d.GetOk("namespace_id"); ok {
request.NamespaceId = v.(string)
}
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.ImportK8sCluster(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_edas_k8s_cluster", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*edas.ImportK8sClusterResponse)
if response.Code != 200 {
return WrapError(Error("import k8s cluster failed for " + response.Message))
}
if len(response.Data) == 0 {
return WrapError(Error("null cluster id after import k8s cluster"))
}
d.SetId(response.Data)
// Wait until import succeed
req := edas.CreateGetClusterRequest()
req.ClusterId = response.Data
wait := incrementalWait(1*time.Second, 2*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.GetCluster(req)
})
response, _ := raw.(*edas.GetClusterResponse)
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if response.Code != 200 {
return resource.NonRetryableError(Error("Get cluster failed for " + response.Message))
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
if response.Cluster.ClusterImportStatus == 3 {
return resource.RetryableError(Error("cluster is importing"))
}
if response.Cluster.ClusterImportStatus == 1 {
return nil
}
return resource.NonRetryableError(Error("cluster status abnormal"))
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return resourceAlicloudEdasK8sClusterRead(d, meta)
}
func resourceAlicloudEdasK8sClusterRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
object, err := edasService.DescribeEdasK8sCluster(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("cluster_name", object.ClusterName)
d.Set("cluster_type", object.ClusterType)
d.Set("network_mode", object.NetworkMode)
d.Set("vpc_id", object.VpcId)
d.Set("namespace_id", object.RegionId)
d.Set("cluster_import_status", object.ClusterImportStatus)
d.Set("cs_cluster_id", object.CsClusterId)
return nil
}
func resourceAlicloudEdasK8sClusterDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
clusterId := d.Id()
regionId := client.RegionId
request := edas.CreateDeleteClusterRequest()
request.RegionId = regionId
request.ClusterId = clusterId
wait := incrementalWait(1*time.Second, 2*time.Second)
err := resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.DeleteCluster(request)
})
response, _ := raw.(*edas.DeleteClusterResponse)
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if response.Code != 200 {
return resource.NonRetryableError(Error("Delete EDAS K8s cluster failed for " + response.Message))
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
reqGet := edas.CreateGetClusterRequest()
reqGet.RegionId = regionId
reqGet.ClusterId = clusterId
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.GetCluster(reqGet)
})
response, _ := raw.(*edas.GetClusterResponse)
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
if response.Code == 200 {
return resource.RetryableError(Error("cluster deleting"))
} else if response.Code == 601 && strings.Contains(response.Message, "does not exist") {
return nil
} else {
return resource.NonRetryableError(Error("check cluster status failed for " + response.Message))
}
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/edas"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudEdasSlbAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEdasSlbAttachmentCreate,
Read: resourceAlicloudEdasSlbAttachmentRead,
Delete: resourceAlicloudEdasSlbAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"app_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"slb_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"slb_ip": {
Type: schema.TypeString,
ValidateFunc: validation.SingleIP(),
Required: true,
ForceNew: true,
},
"type": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"internet", "intranet"}, false),
Required: true,
ForceNew: true,
},
"listener_port": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(1, 65535),
Optional: true,
ForceNew: true,
},
"vserver_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"slb_status": {
Type: schema.TypeString,
Computed: true,
ForceNew: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudEdasSlbAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
appId := d.Get("app_id").(string)
slbId := d.Get("slb_id").(string)
request := edas.CreateBindSlbRequest()
request.RegionId = client.RegionId
request.Type = d.Get("type").(string)
request.AppId = appId
request.SlbId = slbId
request.SlbIp = d.Get("slb_ip").(string)
if v, ok := d.GetOk("listener_port"); ok {
request.ListenerPort = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("vserver_group_id"); ok {
request.VServerGroupId = v.(string)
}
if err := edasService.SyncResource("slb"); err != nil {
return err
}
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.BindSlb(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_edas_slb_attachment", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*edas.BindSlbResponse)
if response.Code != 200 {
return WrapError(Error("bind slb failed for " + response.Message))
}
d.SetId(appId + ":" + slbId)
return resourceAlicloudEdasInstanceApplicationAttachmentRead(d, meta)
}
func resourceAlicloudEdasSlbAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
id := d.Id()
strs, err := ParseResourceId(id, 2)
if err != nil {
return WrapError(err)
}
regionId := client.RegionId
slbId := strs[1]
appId := strs[0]
rq := edas.CreateGetApplicationRequest()
rq.RegionId = regionId
rq.AppId = appId
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.GetApplication(rq)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_edas_slb_attachment", rq.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(rq.GetActionName(), raw, rq.RoaRequest, rq)
rs := raw.(*edas.GetApplicationResponse)
if rs.Applcation.SlbId != slbId && rs.Applcation.ExtSlbId != slbId {
return WrapError(Error("can not find slb:" + slbId))
}
request := edas.CreateListSlbRequest()
request.RegionId = regionId
raw, err = edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.ListSlb(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_edas_slb_attachment", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response := raw.(*edas.ListSlbResponse)
if response.Code != 200 {
return WrapError(Error("List Slb failed for " + response.Message))
}
for _, slb := range response.SlbList.SlbEntity {
if slb.SlbId == slbId {
d.Set("slb_status", slb.SlbStatus)
d.Set("vswitch_id", slb.VswitchId)
return nil
}
}
return nil
}
func resourceAlicloudEdasSlbAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
edasService := EdasService{client}
request := edas.CreateUnbindSlbRequest()
request.RegionId = client.RegionId
request.AppId = d.Get("app_id").(string)
request.SlbId = d.Get("slb_id").(string)
request.Type = d.Get("type").(string)
raw, err := edasService.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.UnbindSlb(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_edas_slb_attachment", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response := raw.(*edas.UnbindSlbResponse)
if response.Code != 200 {
return WrapError(Error("unbind slb failed," + response.Message))
}
return nil
}
package alicloud
import (
"fmt"
"log"
"strconv"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEhpcJobTemplate() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEhpcJobTemplateCreate,
Read: resourceAlicloudEhpcJobTemplateRead,
Update: resourceAlicloudEhpcJobTemplateUpdate,
Delete: resourceAlicloudEhpcJobTemplateDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"array_request": {
Type: schema.TypeString,
Optional: true,
},
"clock_time": {
Type: schema.TypeString,
Optional: true,
},
"command_line": {
Type: schema.TypeString,
Required: true,
},
"gpu": {
Type: schema.TypeInt,
Optional: true,
},
"job_template_name": {
Type: schema.TypeString,
Required: true,
},
"mem": {
Type: schema.TypeString,
Optional: true,
},
"node": {
Type: schema.TypeInt,
Optional: true,
},
"package_path": {
Type: schema.TypeString,
Optional: true,
},
"priority": {
Type: schema.TypeInt,
Optional: true,
},
"queue": {
Type: schema.TypeString,
Optional: true,
},
"re_runable": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"runas_user": {
Type: schema.TypeString,
Optional: true,
},
"stderr_redirect_path": {
Type: schema.TypeString,
Optional: true,
},
"stdout_redirect_path": {
Type: schema.TypeString,
Optional: true,
},
"task": {
Type: schema.TypeInt,
Optional: true,
},
"thread": {
Type: schema.TypeInt,
Optional: true,
},
"variables": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudEhpcJobTemplateCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateJobTemplate"
request := make(map[string]interface{})
conn, err := client.NewEhpcClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("array_request"); ok {
request["ArrayRequest"] = v
}
if v, ok := d.GetOk("clock_time"); ok {
request["ClockTime"] = v
}
request["CommandLine"] = d.Get("command_line")
if v, ok := d.GetOk("gpu"); ok {
request["Gpu"] = v
}
request["Name"] = d.Get("job_template_name")
if v, ok := d.GetOk("mem"); ok {
request["Mem"] = v
}
if v, ok := d.GetOk("node"); ok {
request["Node"] = v
}
if v, ok := d.GetOk("package_path"); ok {
request["PackagePath"] = v
}
if v, ok := d.GetOk("priority"); ok {
request["Priority"] = v
}
if v, ok := d.GetOk("queue"); ok {
request["Queue"] = v
}
if v, ok := d.GetOkExists("re_runable"); ok {
request["ReRunable"] = v
}
if v, ok := d.GetOk("runas_user"); ok {
request["RunasUser"] = v
}
if v, ok := d.GetOk("stderr_redirect_path"); ok {
request["StderrRedirectPath"] = v
}
if v, ok := d.GetOk("stdout_redirect_path"); ok {
request["StdoutRedirectPath"] = v
}
if v, ok := d.GetOk("task"); ok {
request["Task"] = v
}
if v, ok := d.GetOk("thread"); ok {
request["Thread"] = v
}
if v, ok := d.GetOk("variables"); ok {
request["Variables"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2018-04-12"), StringPointer("AK"), request, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ehpc_job_template", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["TemplateId"]))
return resourceAlicloudEhpcJobTemplateRead(d, meta)
}
func resourceAlicloudEhpcJobTemplateRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ehpcService := EhpcService{client}
object, err := ehpcService.DescribeEhpcJobTemplate(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ehpc_job_template ehpcService.DescribeEhpcJobTemplate Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("array_request", object["ArrayRequest"])
d.Set("clock_time", object["ClockTime"])
d.Set("command_line", object["CommandLine"])
if v, ok := object["Gpu"]; ok && fmt.Sprint(v) != "0" {
d.Set("gpu", formatInt(v))
}
d.Set("mem", object["Mem"])
if v, ok := object["Node"]; ok && fmt.Sprint(v) != "0" {
d.Set("node", formatInt(v))
}
d.Set("package_path", object["PackagePath"])
if v, ok := object["Priority"]; ok {
d.Set("priority", formatInt(v))
}
d.Set("queue", object["Queue"])
d.Set("job_template_name", object["Name"])
if v, ok := object["ReRunable"]; ok {
v, _ := strconv.ParseBool(v.(string))
err = d.Set("re_runable", v)
}
d.Set("runas_user", object["RunasUser"])
d.Set("stderr_redirect_path", object["StderrRedirectPath"])
d.Set("stdout_redirect_path", object["StdoutRedirectPath"])
if v, ok := object["Task"]; ok && fmt.Sprint(v) != "0" {
d.Set("task", formatInt(v))
}
if v, ok := object["Thread"]; ok && fmt.Sprint(v) != "0" {
d.Set("thread", formatInt(v))
}
d.Set("variables", object["Variables"])
return nil
}
func resourceAlicloudEhpcJobTemplateUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
request := map[string]interface{}{
"TemplateId": d.Id(),
}
request["CommandLine"] = d.Get("command_line")
request["Name"] = d.Get("job_template_name")
if v, ok := d.GetOk("array_request"); ok {
request["ArrayRequest"] = v
}
if v, ok := d.GetOk("clock_time"); ok {
request["ClockTime"] = v
}
if v, ok := d.GetOk("gpu"); ok {
request["Gpu"] = v
}
if v, ok := d.GetOk("mem"); ok {
request["Mem"] = v
}
if v, ok := d.GetOk("node"); ok {
request["Node"] = v
}
if v, ok := d.GetOk("package_path"); ok {
request["PackagePath"] = v
}
if v, ok := d.GetOk("priority"); ok {
request["Priority"] = v
}
if v, ok := d.GetOk("queue"); ok {
request["Queue"] = v
}
if v, ok := d.GetOk("re_runable"); ok {
request["ReRunable"] = v
}
if v, ok := d.GetOk("runas_user"); ok {
request["RunasUser"] = v
}
if v, ok := d.GetOk("stderr_redirect_path"); ok {
request["StderrRedirectPath"] = v
}
if v, ok := d.GetOk("stdout_redirect_path"); ok {
request["StdoutRedirectPath"] = v
}
if v, ok := d.GetOk("task"); ok {
request["Task"] = v
}
if v, ok := d.GetOk("thread"); ok {
request["Thread"] = v
}
if v, ok := d.GetOk("variables"); ok {
request["Variables"] = v
}
action := "EditJobTemplate"
conn, err := client.NewEhpcClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2018-04-12"), StringPointer("AK"), request, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return resourceAlicloudEhpcJobTemplateRead(d, meta)
}
func resourceAlicloudEhpcJobTemplateDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteJobTemplates"
var response map[string]interface{}
conn, err := client.NewEhpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"Templates": fmt.Sprintf("[{\"Id\":\"%s\"}]", d.Id()),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2018-04-12"), StringPointer("AK"), request, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/denverdino/aliyungo/common"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudEipAddress() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEipAddressCreate,
Read: resourceAlicloudEipAddressRead,
Update: resourceAlicloudEipAddressUpdate,
Delete: resourceAlicloudEipAddressDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
Delete: schema.DefaultTimeout(9 * time.Minute),
},
Schema: map[string]*schema.Schema{
"auto_pay": {
Type: schema.TypeBool,
Optional: true,
},
"activity_id": {
Type: schema.TypeString,
Optional: true,
},
"address_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringLenBetween(2, 128),
ConflictsWith: []string{"name"},
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringLenBetween(2, 128),
ConflictsWith: []string{"address_name"},
Deprecated: "Field 'name' has been deprecated from provider version 1.126.0 and it will be remove in the future version. Please use the new attribute 'address_name' instead.",
},
"bandwidth": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"deletion_protection": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"internet_charge_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PayByBandwidth", "PayByTraffic", "PayByDominantTraffic"}, false),
},
"isp": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"BGP", "BGP_PRO"}, false),
},
"netmode": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"public"}, false),
},
"period": {
Type: schema.TypeInt,
Optional: true,
DiffSuppressFunc: PostPaidDiffSuppressFunc,
ValidateFunc: validation.Any(validation.IntBetween(1, 9), validation.IntInSlice([]int{12, 24, 36})),
},
"payment_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo", "Subscription"}, false),
ConflictsWith: []string{"instance_charge_type"},
},
"instance_charge_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{string(common.PrePaid), string(common.PostPaid)}, false),
Computed: true,
ForceNew: true,
ConflictsWith: []string{"payment_type"},
Deprecated: "Field 'instance_charge_type' has been deprecated from provider version 1.126.0 and it will be remove in the future version. Please use the new attribute 'payment_type' instead.",
},
"ip_address": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
},
}
}
func resourceAlicloudEipAddressCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
action := "AllocateEipAddress"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("activity_id"); ok {
request["ActivityId"] = v
}
if v, ok := d.GetOk("address_name"); ok {
request["Name"] = v
} else if v, ok := d.GetOk("name"); ok {
request["Name"] = v
}
if v, ok := d.GetOk("bandwidth"); ok {
request["Bandwidth"] = v
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("internet_charge_type"); ok {
request["InternetChargeType"] = v
}
if v, ok := d.GetOk("isp"); ok {
request["ISP"] = v
}
if v, ok := d.GetOk("netmode"); ok {
request["Netmode"] = v
}
if v, ok := d.GetOk("payment_type"); ok {
request["InstanceChargeType"] = convertEipAddressPaymentTypeRequest(v)
} else if v, ok := d.GetOk("instance_charge_type"); ok {
request["InstanceChargeType"] = v
}
if v, ok := request["InstanceChargeType"]; ok && v.(string) == "PrePaid" {
period := 1
if v, ok := d.GetOk("period"); ok {
period = v.(int)
}
request["Period"] = period
request["PricingCycle"] = string(Month)
if period > 9 {
request["Period"] = period / 12
request["PricingCycle"] = string(Year)
}
autoPay := true
if v, ok := d.GetOkExists("auto_pay"); ok {
autoPay = v.(bool)
}
request["AutoPay"] = autoPay
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
request["ClientToken"] = buildClientToken("AllocateEipAddress")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"COMMODITY.INVALID_COMPONENT"}) && request["InternetChargeType"] == string(PayByBandwidth) {
return WrapErrorf(err, "Your account is international and it can only create '%s' elastic IP. Please change it and try again. %s", PayByTraffic, AlibabaCloudSdkGoERROR)
}
return WrapErrorf(err, DefaultErrorMsg, "alicloud_eip_address", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["AllocationId"]))
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, vpcService.EipAddressStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudEipAddressUpdate(d, meta)
}
func resourceAlicloudEipAddressRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeEipAddress(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_eip_address vpcService.DescribeEipAddress Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("address_name", object["Name"])
d.Set("name", object["Name"])
d.Set("bandwidth", object["Bandwidth"])
d.Set("deletion_protection", object["DeletionProtection"])
d.Set("description", object["Descritpion"])
d.Set("internet_charge_type", object["InternetChargeType"])
d.Set("isp", object["ISP"])
d.Set("payment_type", convertEipAddressPaymentTypeResponse(object["ChargeType"]))
d.Set("instance_charge_type", object["ChargeType"])
d.Set("ip_address", object["IpAddress"])
d.Set("resource_group_id", object["ResourceGroupId"])
d.Set("status", object["Status"])
listTagResourcesObject, err := vpcService.ListTagResources(d.Id(), "EIP")
if err != nil {
return WrapError(err)
}
d.Set("tags", tagsToMap(listTagResourcesObject))
return nil
}
func resourceAlicloudEipAddressUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
d.Partial(true)
if d.HasChange("tags") {
if err := vpcService.SetResourceTags(d, "eip"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
update := false
request := map[string]interface{}{
"InstanceId": d.Id(),
}
if d.HasChange("deletion_protection") {
update = true
}
request["ProtectionEnable"] = d.Get("deletion_protection")
request["RegionId"] = client.RegionId
request["Type"] = "EIP"
if update {
action := "DeletionProtection"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("DeletionProtection")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("deletion_protection")
}
update = false
moveResourceGroupReq := map[string]interface{}{
"ResourceId": d.Id(),
}
moveResourceGroupReq["RegionId"] = client.RegionId
if !d.IsNewResource() && d.HasChange("resource_group_id") {
update = true
}
moveResourceGroupReq["NewResourceGroupId"] = d.Get("resource_group_id")
moveResourceGroupReq["ResourceType"] = "eip"
if update {
action := "MoveResourceGroup"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, moveResourceGroupReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, moveResourceGroupReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("resource_group_id")
}
update = false
modifyEipAddressAttributeReq := map[string]interface{}{
"AllocationId": d.Id(),
}
if !d.IsNewResource() && (d.HasChange("address_name") || d.HasChange("name")) {
update = true
if _, ok := d.GetOk("address_name"); ok {
modifyEipAddressAttributeReq["Name"] = d.Get("address_name")
} else {
modifyEipAddressAttributeReq["Name"] = d.Get("name")
}
}
if !d.IsNewResource() && d.HasChange("bandwidth") {
update = true
modifyEipAddressAttributeReq["Bandwidth"] = d.Get("bandwidth")
}
if !d.IsNewResource() && d.HasChange("description") {
update = true
modifyEipAddressAttributeReq["Description"] = d.Get("description")
}
modifyEipAddressAttributeReq["RegionId"] = client.RegionId
if update {
action := "ModifyEipAddressAttribute"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, modifyEipAddressAttributeReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyEipAddressAttributeReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("name")
d.SetPartial("address_name")
d.SetPartial("bandwidth")
d.SetPartial("description")
}
d.Partial(false)
return resourceAlicloudEipAddressRead(d, meta)
}
func resourceAlicloudEipAddressDelete(d *schema.ResourceData, meta interface{}) error {
if d.Get("payment_type").(string) == "Subscription" || d.Get("instance_charge_type").(string) == "Prepaid" {
log.Printf("[WARN] Cannot destroy Subscription resource: alicloud_eip_address. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
action := "ReleaseEipAddress"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AllocationId": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectEipStatus", "TaskConflict.AssociateGlobalAccelerationInstance"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
} else if IsExpectedErrors(err, []string{"InvalidAllocationId.NotFound"}) {
return nil
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, vpcService.EipAddressStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
func convertEipAddressPaymentTypeRequest(source interface{}) interface{} {
switch source {
case "PayAsYouGo":
return "PostPaid"
case "Subscription":
return "PrePaid"
}
return source
}
func convertEipAddressPaymentTypeResponse(source interface{}) interface{} {
switch source {
case "PostPaid":
return "PayAsYouGo"
case "PrePaid":
return "Subscription"
}
return source
}
package alicloud
import (
"log"
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliyunEipAssociation() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunEipAssociationCreate,
Read: resourceAliyunEipAssociationRead,
Update: resourceAliyunEipAssociationUpdate,
Delete: resourceAliyunEipAssociationDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"allocation_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"force": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"private_ip_address": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
},
}
}
func resourceAliyunEipAssociationCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
request := vpc.CreateAssociateEipAddressRequest()
request.RegionId = client.RegionId
request.AllocationId = Trim(d.Get("allocation_id").(string))
request.InstanceId = Trim(d.Get("instance_id").(string))
request.InstanceType = EcsInstance
// There is a product api bug about clientToken and after fixed , the clientToken will be opened again.
//request.ClientToken = buildClientToken(request.GetActionName())
if strings.HasPrefix(request.InstanceId, "lb-") {
request.InstanceType = SlbInstance
}
if strings.HasPrefix(request.InstanceId, "ngw-") {
request.InstanceType = Nat
}
if instanceType, ok := d.GetOk("instance_type"); ok {
request.InstanceType = instanceType.(string)
}
if privateIPAddress, ok := d.GetOk("private_ip_address"); ok {
request.PrivateIpAddress = privateIPAddress.(string)
}
if err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.AssociateEipAddress(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"TaskConflict"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_eip_association", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
if err := vpcService.WaitForEip(request.AllocationId, InUse, 60); err != nil {
return WrapError(err)
}
// There is at least 30 seconds delay for ecs instance
if request.InstanceType == EcsInstance {
time.Sleep(30 * time.Second)
}
d.SetId(request.AllocationId + ":" + request.InstanceId)
return resourceAliyunEipAssociationRead(d, meta)
}
func resourceAliyunEipAssociationRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeEipAssociation(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_id", object.InstanceId)
d.Set("allocation_id", object.AllocationId)
d.Set("instance_type", object.InstanceType)
d.Set("force", d.Get("force").(bool))
return nil
}
func resourceAliyunEipAssociationUpdate(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] The update method is used to ensure that the force parameter does not need to add forcenew.")
return nil
}
func resourceAliyunEipAssociationDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
allocationId, instanceId := parts[0], parts[1]
if err != nil {
return WrapError(err)
}
request := vpc.CreateUnassociateEipAddressRequest()
request.RegionId = client.RegionId
request.AllocationId = allocationId
request.InstanceId = instanceId
request.InstanceType = EcsInstance
request.Force = requests.NewBoolean(d.Get("force").(bool))
request.ClientToken = buildClientToken(request.GetActionName())
if strings.HasPrefix(instanceId, "lb-") {
request.InstanceType = SlbInstance
}
if strings.HasPrefix(instanceId, "ngw-") {
request.InstanceType = Nat
}
if instanceType, ok := d.GetOk("instance_type"); ok {
request.InstanceType = instanceType.(string)
}
err = resource.Retry(10*time.Minute, func() *resource.RetryError {
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.UnassociateEipAddress(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectInstanceStatus", "IncorrectHaVipStatus", "TaskConflict",
"InvalidIpStatus.HasBeenUsedBySnatTable", "InvalidIpStatus.HasBeenUsedByForwardEntry", "InvalidStatus.EniStatusNotSupport"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(vpcService.WaitForEipAssociation(d.Id(), Available, DefaultTimeoutMedium))
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudEipanycastAnycastEipAddress() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEipanycastAnycastEipAddressCreate,
Read: resourceAlicloudEipanycastAnycastEipAddressRead,
Update: resourceAlicloudEipanycastAnycastEipAddressUpdate,
Delete: resourceAlicloudEipanycastAnycastEipAddressDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"anycast_eip_address_name": {
Type: schema.TypeString,
Optional: true,
},
"bandwidth": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"internet_charge_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "PayByTraffic",
},
"payment_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo"}, false),
Default: "PayAsYouGo",
},
"service_location": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudEipanycastAnycastEipAddressCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
eipanycastService := EipanycastService{client}
var response map[string]interface{}
action := "AllocateAnycastEipAddress"
request := make(map[string]interface{})
conn, err := client.NewEipanycastClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("anycast_eip_address_name"); ok {
request["Name"] = v
}
if v, ok := d.GetOk("bandwidth"); ok {
request["Bandwidth"] = v
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("internet_charge_type"); ok {
request["InternetChargeType"] = v
}
if v, ok := d.GetOk("payment_type"); ok {
request["InstanceChargeType"] = convertEipanycastAnycastEipAddressPaymentTypeRequest(v.(string))
}
request["ServiceLocation"] = d.Get("service_location")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("AllocateAnycastEipAddress")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_eipanycast_anycast_eip_address", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetId(fmt.Sprint(response["AnycastId"]))
stateConf := BuildStateConf([]string{}, []string{"Allocated"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, eipanycastService.EipanycastAnycastEipAddressStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudEipanycastAnycastEipAddressRead(d, meta)
}
func resourceAlicloudEipanycastAnycastEipAddressRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
eipanycastService := EipanycastService{client}
object, err := eipanycastService.DescribeEipanycastAnycastEipAddress(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_eipanycast_anycast_eip_address eipanycastService.DescribeEipanycastAnycastEipAddress Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("anycast_eip_address_name", object["Name"])
d.Set("bandwidth", formatInt(object["Bandwidth"]))
d.Set("description", object["Description"])
d.Set("internet_charge_type", object["InternetChargeType"])
d.Set("payment_type", convertEipanycastAnycastEipAddressPaymentTypeResponse(object["InstanceChargeType"].(string)))
d.Set("service_location", object["ServiceLocation"])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudEipanycastAnycastEipAddressUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
d.Partial(true)
if d.HasChange("bandwidth") {
request := map[string]interface{}{
"AnycastId": d.Id(),
}
request["Bandwidth"] = d.Get("bandwidth")
action := "ModifyAnycastEipAddressSpec"
conn, err := client.NewEipanycastClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("bandwidth")
}
update := false
request := map[string]interface{}{
"AnycastId": d.Id(),
}
if d.HasChange("anycast_eip_address_name") {
update = true
request["Name"] = d.Get("anycast_eip_address_name")
}
if d.HasChange("description") {
update = true
request["Description"] = d.Get("description")
}
if update {
action := "ModifyAnycastEipAddressAttribute"
conn, err := client.NewEipanycastClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("anycast_eip_address_name")
d.SetPartial("description")
}
d.Partial(false)
return resourceAlicloudEipanycastAnycastEipAddressRead(d, meta)
}
func resourceAlicloudEipanycastAnycastEipAddressDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ReleaseAnycastEipAddress"
var response map[string]interface{}
conn, err := client.NewEipanycastClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AnycastId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func convertEipanycastAnycastEipAddressPaymentTypeRequest(source string) string {
switch source {
case "PayAsYouGo":
return "PostPaid"
}
return source
}
func convertEipanycastAnycastEipAddressPaymentTypeResponse(source string) string {
switch source {
case "PostPaid":
return "PayAsYouGo"
}
return source
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEipanycastAnycastEipAddressAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEipanycastAnycastEipAddressAttachmentCreate,
Read: resourceAlicloudEipanycastAnycastEipAddressAttachmentRead,
Delete: resourceAlicloudEipanycastAnycastEipAddressAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
Delete: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"anycast_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"bind_instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"bind_instance_region_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"bind_instance_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"SlbInstance"}, false),
},
"bind_time": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudEipanycastAnycastEipAddressAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
eipanycastService := EipanycastService{client}
var response map[string]interface{}
action := "AssociateAnycastEipAddress"
request := make(map[string]interface{})
conn, err := client.NewEipanycastClient()
if err != nil {
return WrapError(err)
}
request["AnycastId"] = d.Get("anycast_id")
request["BindInstanceId"] = d.Get("bind_instance_id")
request["BindInstanceRegionId"] = d.Get("bind_instance_region_id")
request["BindInstanceType"] = d.Get("bind_instance_type")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("AssociateAnycastEipAddress")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_eipanycast_anycast_eip_address_attachment", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetId(fmt.Sprint(request["AnycastId"], ":", request["BindInstanceId"], ":", request["BindInstanceRegionId"], ":", request["BindInstanceType"]))
stateConf := BuildStateConf([]string{}, []string{"Associated"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, eipanycastService.EipanycastAnycastEipAddressAttachmentStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudEipanycastAnycastEipAddressAttachmentRead(d, meta)
}
func resourceAlicloudEipanycastAnycastEipAddressAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
eipanycastService := EipanycastService{client}
object, err := eipanycastService.DescribeEipanycastAnycastEipAddressAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_eipanycast_anycast_eip_address_attachment eipanycastService.DescribeEipanycastAnycastEipAddressAttachment Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 4)
if err != nil {
return WrapError(err)
}
d.Set("anycast_id", parts[0])
d.Set("bind_instance_id", parts[1])
d.Set("bind_instance_region_id", parts[2])
d.Set("bind_instance_type", parts[3])
if v, ok := object["AnycastEipBindInfoList"].([]interface{})[0].(map[string]interface{}); ok {
d.Set("bind_time", v["BindTime"])
}
return nil
}
func resourceAlicloudEipanycastAnycastEipAddressAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
eipanycastService := EipanycastService{client}
action := "UnassociateAnycastEipAddress"
parts, err := ParseResourceId(d.Id(), 4)
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
conn, err := client.NewEipanycastClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AnycastId": parts[0],
"BindInstanceId": parts[1],
"BindInstanceRegionId": parts[2],
"BindInstanceType": parts[3],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-09"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, eipanycastService.EipanycastAnycastEipAddressAttachmentStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"regexp"
"strings"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/denverdino/aliyungo/common"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudElasticsearch() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudElasticsearchCreate,
Read: resourceAlicloudElasticsearchRead,
Update: resourceAlicloudElasticsearchUpdate,
Delete: resourceAlicloudElasticsearchDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(120 * time.Minute),
Update: schema.DefaultTimeout(120 * time.Minute),
Delete: schema.DefaultTimeout(120 * time.Minute),
},
Schema: map[string]*schema.Schema{
// Basic instance information
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[\w\-.]{0,30}$`), "be 0 to 30 characters in length and can contain numbers, letters, underscores, (_) and hyphens (-). It must start with a letter, a number or Chinese character."),
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"password": {
Type: schema.TypeString,
Sensitive: true,
Optional: true,
},
"kms_encrypted_password": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: kmsDiffSuppressFunc,
},
"kms_encryption_context": {
Type: schema.TypeMap,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("kms_encrypted_password").(string) == ""
},
Elem: schema.TypeString,
},
"version": {
Type: schema.TypeString,
Required: true,
DiffSuppressFunc: esVersionDiffSuppressFunc,
ForceNew: true,
},
"tags": tagsSchema(),
// Life cycle
"instance_charge_type": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{string(common.PrePaid), string(common.PostPaid)}, false),
Default: PostPaid,
Optional: true,
},
"period": {
Type: schema.TypeInt,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 24, 36}),
Optional: true,
Default: 1,
DiffSuppressFunc: PostPaidDiffSuppressFunc,
},
// Data node configuration
"data_node_amount": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(2, 50),
},
"data_node_spec": {
Type: schema.TypeString,
Required: true,
},
"data_node_disk_size": {
Type: schema.TypeInt,
Required: true,
},
"data_node_disk_type": {
Type: schema.TypeString,
Required: true,
},
"data_node_disk_encrypted": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: false,
},
"private_whitelist": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"enable_public": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"public_whitelist": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
DiffSuppressFunc: elasticsearchEnablePublicDiffSuppressFunc,
},
"master_node_spec": {
Type: schema.TypeString,
Optional: true,
},
// Client node configuration
"client_node_amount": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(2, 25),
},
"client_node_spec": {
Type: schema.TypeString,
Optional: true,
},
"protocol": {
Type: schema.TypeString,
Optional: true,
Default: "HTTP",
ValidateFunc: validation.StringInSlice([]string{"HTTP", "HTTPS"}, false),
},
"domain": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeInt,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
// Kibana node configuration
"kibana_domain": {
Type: schema.TypeString,
Computed: true,
},
"kibana_port": {
Type: schema.TypeInt,
Computed: true,
},
"enable_kibana_public_network": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"kibana_whitelist": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
DiffSuppressFunc: elasticsearchEnableKibanaPublicDiffSuppressFunc,
},
"enable_kibana_private_network": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"kibana_private_whitelist": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
DiffSuppressFunc: elasticsearchEnableKibanaPrivateDiffSuppressFunc,
},
"zone_count": {
Type: schema.TypeInt,
ForceNew: true,
Optional: true,
ValidateFunc: validation.IntBetween(1, 3),
Default: 1,
},
"resource_group_id": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
Computed: true,
},
"setting_config": {
Type: schema.TypeMap,
Optional: true,
Computed: true,
},
},
}
}
func resourceAlicloudElasticsearchCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
elasticsearchService := ElasticsearchService{client}
action := "createInstance"
requestBody, err := buildElasticsearchCreateRequestBody(d, meta)
var response map[string]interface{}
// retry
wait := incrementalWait(3*time.Second, 5*time.Second)
errorCodeList := []string{"TokenPreviousRequestProcessError"}
conn, err := elasticsearchService.client.NewElasticsearchClient()
requestQuery := map[string]*string{
"clientToken": StringPointer(buildClientToken(action)),
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequestWithAction(StringPointer(action), StringPointer("2017-06-13"), nil, StringPointer("POST"), StringPointer("AK"), StringPointer("/openapi/instances"), requestQuery, nil, requestBody, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, errorCodeList) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
addDebug(action, response, nil)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_elasticsearch_instance", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.body.Result.instanceId", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.body.Result.instanceId", response)
}
d.SetId(resp.(string))
stateConf := BuildStateConf([]string{"activating"}, []string{"active"}, d.Timeout(schema.TimeoutCreate), 5*time.Minute, elasticsearchService.ElasticsearchStateRefreshFunc(d.Id(), []string{"inactive"}))
stateConf.PollInterval = 5 * time.Second
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudElasticsearchUpdate(d, meta)
}
func resourceAlicloudElasticsearchRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
elasticsearchService := ElasticsearchService{client}
object, err := elasticsearchService.DescribeElasticsearchInstance(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", object["description"])
d.Set("status", object["status"])
d.Set("vswitch_id", object["networkConfig"].(map[string]interface{})["vswitchId"])
esIPWhitelist := object["esIPWhitelist"].([]interface{})
publicIpWhitelist := object["publicIpWhitelist"].([]interface{})
d.Set("private_whitelist", filterWhitelist(convertArrayInterfaceToArrayString(esIPWhitelist), d.Get("private_whitelist").(*schema.Set)))
d.Set("public_whitelist", filterWhitelist(convertArrayInterfaceToArrayString(publicIpWhitelist), d.Get("public_whitelist").(*schema.Set)))
d.Set("enable_public", object["enablePublic"])
d.Set("version", object["esVersion"])
d.Set("instance_charge_type", getChargeType(object["paymentType"].(string)))
d.Set("domain", object["domain"])
d.Set("port", object["port"])
// Kibana configuration
d.Set("enable_kibana_public_network", object["enableKibanaPublicNetwork"])
kibanaIPWhitelist := object["kibanaIPWhitelist"].([]interface{})
d.Set("kibana_whitelist", filterWhitelist(convertArrayInterfaceToArrayString(kibanaIPWhitelist), d.Get("kibana_whitelist").(*schema.Set)))
if object["enableKibanaPublicNetwork"].(bool) {
d.Set("kibana_domain", object["kibanaDomain"])
d.Set("kibana_port", object["kibanaPort"])
}
d.Set("enable_kibana_private_network", object["enableKibanaPrivateNetwork"])
kibanaPrivateIPWhitelist := object["kibanaPrivateIPWhitelist"].([]interface{})
d.Set("kibana_private_whitelist", filterWhitelist(convertArrayInterfaceToArrayString(kibanaPrivateIPWhitelist), d.Get("kibana_private_whitelist").(*schema.Set)))
// Data node configuration
d.Set("data_node_amount", object["nodeAmount"])
d.Set("data_node_spec", object["nodeSpec"].(map[string]interface{})["spec"])
d.Set("data_node_disk_size", object["nodeSpec"].(map[string]interface{})["disk"])
d.Set("data_node_disk_type", object["nodeSpec"].(map[string]interface{})["diskType"])
d.Set("data_node_disk_encrypted", object["nodeSpec"].(map[string]interface{})["diskEncryption"])
d.Set("master_node_spec", object["masterConfiguration"].(map[string]interface{})["spec"])
// Client node configuration
d.Set("client_node_amount", object["clientNodeConfiguration"].(map[string]interface{})["amount"])
d.Set("client_node_spec", object["clientNodeConfiguration"].(map[string]interface{})["spec"])
// Protocol: HTTP/HTTPS
d.Set("protocol", object["protocol"])
// Cross zone configuration
d.Set("zone_count", object["zoneCount"])
d.Set("resource_group_id", object["resourceGroupId"])
esConfig := object["esConfig"].(map[string]interface{})
if esConfig != nil {
d.Set("setting_config", esConfig)
}
// tags
tags, err := elasticsearchService.DescribeElasticsearchTags(d.Id())
if err != nil {
return WrapError(err)
}
if len(tags) > 0 {
d.Set("tags", tags)
}
return nil
}
func resourceAlicloudElasticsearchUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
elasticsearchService := ElasticsearchService{client}
d.Partial(true)
stateConf := BuildStateConf([]string{"activating"}, []string{"active"}, d.Timeout(schema.TimeoutUpdate), 5*time.Minute, elasticsearchService.ElasticsearchStateRefreshFunc(d.Id(), []string{"inactive"}))
stateConf.PollInterval = 5 * time.Second
if d.HasChange("description") {
if err := updateDescription(d, meta); err != nil {
return WrapError(err)
}
d.SetPartial("description")
}
if d.HasChange("private_whitelist") {
content := make(map[string]interface{})
content["networkType"] = string(PRIVATE)
content["nodeType"] = string(WORKER)
content["whiteIpList"] = d.Get("private_whitelist").(*schema.Set).List()
if err := elasticsearchService.ModifyWhiteIps(d, content, meta); err != nil {
return WrapError(err)
}
d.SetPartial("private_whitelist")
}
if d.HasChange("enable_public") {
content := make(map[string]interface{})
content["networkType"] = string(PUBLIC)
content["nodeType"] = string(WORKER)
content["actionType"] = elasticsearchService.getActionType(d.Get("enable_public").(bool))
if err := elasticsearchService.TriggerNetwork(d, content, meta); err != nil {
return WrapError(err)
}
d.SetPartial("enable_public")
}
if d.Get("enable_public").(bool) == true && d.HasChange("public_whitelist") {
content := make(map[string]interface{})
content["networkType"] = string(PUBLIC)
content["nodeType"] = string(WORKER)
content["whiteIpList"] = d.Get("public_whitelist").(*schema.Set).List()
if err := elasticsearchService.ModifyWhiteIps(d, content, meta); err != nil {
return WrapError(err)
}
d.SetPartial("public_whitelist")
}
if d.HasChange("enable_kibana_public_network") || d.IsNewResource() {
content := make(map[string]interface{})
content["networkType"] = string(PUBLIC)
content["nodeType"] = string(KIBANA)
content["actionType"] = elasticsearchService.getActionType(d.Get("enable_kibana_public_network").(bool))
if err := elasticsearchService.TriggerNetwork(d, content, meta); err != nil {
return WrapError(err)
}
d.SetPartial("enable_kibana_public_network")
}
if d.Get("enable_kibana_public_network").(bool) == true && d.HasChange("kibana_whitelist") {
content := make(map[string]interface{})
content["networkType"] = string(PUBLIC)
content["nodeType"] = string(KIBANA)
content["whiteIpList"] = d.Get("kibana_whitelist").(*schema.Set).List()
if err := elasticsearchService.ModifyWhiteIps(d, content, meta); err != nil {
return WrapError(err)
}
d.SetPartial("kibana_whitelist")
}
if d.HasChange("enable_kibana_private_network") {
content := make(map[string]interface{})
content["networkType"] = string(PRIVATE)
content["nodeType"] = string(KIBANA)
content["actionType"] = elasticsearchService.getActionType(d.Get("enable_kibana_private_network").(bool))
if err := elasticsearchService.TriggerNetwork(d, content, meta); err != nil {
return WrapError(err)
}
d.SetPartial("enable_kibana_private_network")
}
if d.Get("enable_kibana_private_network").(bool) == true && d.HasChange("kibana_private_whitelist") {
content := make(map[string]interface{})
content["networkType"] = string(PRIVATE)
content["nodeType"] = string(KIBANA)
content["whiteIpList"] = d.Get("kibana_private_whitelist").(*schema.Set).List()
if err := elasticsearchService.ModifyWhiteIps(d, content, meta); err != nil {
return WrapError(err)
}
d.SetPartial("kibana_private_whitelist")
}
if d.HasChange("tags") {
if err := updateInstanceTags(d, meta); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
if d.HasChange("client_node_spec") || d.HasChange("client_node_amount") {
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
if err := updateClientNode(d, meta); err != nil {
return WrapError(err)
}
d.SetPartial("client_node_spec")
d.SetPartial("client_node_amount")
}
if d.HasChange("protocol") {
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
var https func(*schema.ResourceData, interface{}) error
if d.Get("protocol") == "HTTPS" {
https = openHttps
} else if d.Get("protocol") == "HTTP" {
https = closeHttps
}
if nil != https {
if err := https(d, meta); err != nil {
return WrapError(err)
}
}
d.SetPartial("protocol")
}
if d.HasChange("setting_config") {
conn, err := client.NewElasticsearchClient()
if err != nil {
return WrapError(err)
}
action := "UpdateInstanceSettings"
content := make(map[string]interface{})
config := d.Get("setting_config").(map[string]interface{})
content["esConfig"] = config
requestQuery := map[string]*string{
"clientToken": StringPointer(buildClientToken(action)),
}
// retry
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequestWithAction(StringPointer(action), StringPointer("2017-06-13"), nil, StringPointer("POST"), StringPointer("AK"),
String(fmt.Sprintf("/openapi/instances/%s/instance-settings", d.Id())), requestQuery, nil, content, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ConcurrencyUpdateInstanceConflict", "InstanceStatusNotSupportCurrentAction", "InstanceDuplicateScheduledTask"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, content)
return nil
})
if err != nil && !IsExpectedErrors(err, []string{"MustChangeOneResource", "CssCheckUpdowngradeError"}) {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"activating"}, []string{"active"}, d.Timeout(schema.TimeoutUpdate), 5*time.Minute, elasticsearchService.ElasticsearchStateRefreshFunc(d.Id(), []string{"inactive"}))
stateConf.PollInterval = 5 * time.Second
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("setting_config")
}
if d.IsNewResource() {
d.Partial(false)
return resourceAlicloudElasticsearchRead(d, meta)
}
if d.HasChange("instance_charge_type") {
if err := updateInstanceChargeType(d, meta); err != nil {
return WrapError(err)
}
d.SetPartial("instance_charge_type")
d.SetPartial("period")
} else if d.Get("instance_charge_type").(string) == string(PrePaid) && d.HasChange("period") {
if err := renewInstance(d, meta); err != nil {
return WrapError(err)
}
d.SetPartial("period")
}
if d.HasChange("data_node_amount") {
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
if err := updateDataNodeAmount(d, meta); err != nil {
return WrapError(err)
}
d.SetPartial("data_node_amount")
}
if d.HasChange("data_node_spec") || d.HasChange("data_node_disk_size") || d.HasChange("data_node_disk_type") {
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
if err := updateDataNodeSpec(d, meta); err != nil {
return WrapError(err)
}
d.SetPartial("data_node_spec")
d.SetPartial("data_node_disk_size")
d.SetPartial("data_node_disk_type")
d.SetPartial("data_node_disk_encrypted")
}
if d.HasChange("master_node_spec") {
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
if err := updateMasterNode(d, meta); err != nil {
return WrapError(err)
}
d.SetPartial("master_node_spec")
}
if d.HasChange("password") || d.HasChange("kms_encrypted_password") {
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
if err := updatePassword(d, meta); err != nil {
return WrapError(err)
}
d.SetPartial("password")
}
d.Partial(false)
return resourceAlicloudElasticsearchRead(d, meta)
}
func resourceAlicloudElasticsearchDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
elasticsearchService := ElasticsearchService{client}
action := "DeleteInstance"
if strings.ToLower(d.Get("instance_charge_type").(string)) == strings.ToLower(string(PrePaid)) {
return WrapError(Error("At present, 'PrePaid' instance cannot be deleted and must wait it to be expired and release it automatically"))
}
var response map[string]interface{}
requestQuery := map[string]*string{
"clientToken": StringPointer(buildClientToken(action)),
}
// retry
wait := incrementalWait(3*time.Second, 5*time.Second)
errorCodeList := []string{"InstanceActivating", "TokenPreviousRequestProcessError"}
conn, err := elasticsearchService.client.NewElasticsearchClient()
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequestWithAction(StringPointer(action), StringPointer("2017-06-13"), nil, StringPointer("DELETE"), StringPointer("AK"),
String(fmt.Sprintf("/openapi/instances/%s", d.Id())), requestQuery, nil, nil, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, errorCodeList) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
addDebug(action, response, nil)
if err != nil {
if IsExpectedErrors(err, []string{"InstanceNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"activating", "inactive", "active"}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Minute, elasticsearchService.ElasticsearchStateRefreshFunc(d.Id(), []string{}))
stateConf.PollInterval = 5 * time.Second
if _, err = stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
// Instance will be completed deleted in 5 minutes, so deleting vswitch is available after the time.
time.Sleep(5 * time.Minute)
return nil
}
func buildElasticsearchCreateRequestBody(d *schema.ResourceData, meta interface{}) (map[string]interface{}, error) {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
content := make(map[string]interface{})
if v, ok := d.GetOk("resource_group_id"); ok && v.(string) != "" {
content["resourceGroupId"] = v.(string)
}
content["paymentType"] = strings.ToLower(d.Get("instance_charge_type").(string))
if d.Get("instance_charge_type").(string) == string(PrePaid) {
paymentInfo := make(map[string]interface{})
if d.Get("period").(int) >= 12 {
paymentInfo["duration"] = d.Get("period").(int) / 12
paymentInfo["pricingCycle"] = string(Year)
} else {
paymentInfo["duration"] = d.Get("period").(int)
paymentInfo["pricingCycle"] = string(Month)
}
content["paymentInfo"] = paymentInfo
}
content["nodeAmount"] = d.Get("data_node_amount")
content["esVersion"] = d.Get("version")
content["description"] = d.Get("description")
password := d.Get("password").(string)
kmsPassword := d.Get("kms_encrypted_password").(string)
if password == "" && kmsPassword == "" {
return nil, WrapError(Error("One of the 'password' and 'kms_encrypted_password' should be set."))
}
if password != "" {
content["esAdminPassword"] = password
} else {
kmsService := KmsService{client}
decryptResp, err := kmsService.Decrypt(kmsPassword, d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return content, WrapError(err)
}
content["esAdminPassword"] = decryptResp
}
// Data node configuration
dataNodeSpec := make(map[string]interface{})
dataNodeSpec["spec"] = d.Get("data_node_spec")
dataNodeSpec["disk"] = d.Get("data_node_disk_size")
dataNodeSpec["diskType"] = d.Get("data_node_disk_type")
dataNodeSpec["diskEncryption"] = d.Get("data_node_disk_encrypted")
content["nodeSpec"] = dataNodeSpec
// Master node configuration
if d.Get("master_node_spec") != nil && d.Get("master_node_spec") != "" {
masterNode := make(map[string]interface{})
masterNode["spec"] = d.Get("master_node_spec")
masterNode["amount"] = "3"
masterNode["disk"] = "20"
masterNode["diskType"] = "cloud_ssd"
content["advancedDedicateMaster"] = true
content["masterConfiguration"] = masterNode
}
// Client node configuration
if d.Get("client_node_spec") != nil && d.Get("client_node_spec") != "" {
clientNode := make(map[string]interface{})
clientNode["spec"] = d.Get("client_node_spec")
clientNode["disk"] = "20"
clientNode["diskType"] = "cloud_efficiency"
if d.Get("client_node_amount") == nil {
clientNode["amount"] = 2
} else {
clientNode["amount"] = d.Get("client_node_amount")
}
content["haveClientNode"] = true
content["clientNodeConfiguration"] = clientNode
}
// Network configuration
vswitchId := d.Get("vswitch_id")
vsw, err := vpcService.DescribeVSwitch(vswitchId.(string))
if err != nil {
return nil, WrapError(err)
}
network := make(map[string]interface{})
network["type"] = "vpc"
network["vpcId"] = vsw.VpcId
network["vswitchId"] = vswitchId
network["vsArea"] = vsw.ZoneId
content["networkConfig"] = network
if d.Get("zone_count") != nil && d.Get("zone_count") != "" {
content["zoneCount"] = d.Get("zone_count")
}
return content, nil
}
package alicloud
import (
"strconv"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/emr"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEmrCluster() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEmrClusterCreate,
Read: resourceAlicloudEmrClusterRead,
Update: resourceAlicloudEmrClusterUpdate,
Delete: resourceAlicloudEmrClusterDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(20 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"cluster_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"emr_ver": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"charge_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "PostPaid",
ValidateFunc: validation.StringInSlice([]string{string(PrePaid), string(PostPaid)}, false),
},
"period": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 24, 36}),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("charge_type").(string) == "PostPaid"
},
},
"tags": tagsSchema(),
"host_group": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"host_group_name": {
Type: schema.TypeString,
Optional: true,
},
"host_group_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"MASTER", "CORE", "TASK", "GATEWAY"}, false),
},
"period": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 24, 36}),
},
"charge_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{string(PrePaid), string(PostPaid)}, false),
},
"node_count": {
Type: schema.TypeString,
Optional: true,
},
"instance_type": {
Type: schema.TypeString,
Optional: true,
},
"disk_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"cloud", "cloud_efficiency", "cloud_ssd", "cloud_essd", "local_disk"}, false),
},
"disk_capacity": {
Type: schema.TypeString,
Optional: true,
},
"disk_count": {
Type: schema.TypeString,
Optional: true,
},
"sys_disk_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"cloud", "cloud_efficiency", "cloud_ssd", "cloud_essd"}, false),
},
"sys_disk_capacity": {
Type: schema.TypeString,
Optional: true,
},
"auto_renew": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"gpu_driver": {
Type: schema.TypeString,
Optional: true,
},
"instance_list": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"bootstrap_action": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
},
"path": {
Type: schema.TypeString,
Optional: true,
},
"arg": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"zone_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"security_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"is_open_public_ip": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: false,
},
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"option_software_list": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"high_availability_enable": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: false,
},
"use_local_metadb": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: false,
},
"ssh_enable": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: false,
},
"master_pwd": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"eas_enable": {
Type: schema.TypeBool,
Optional: true,
Default: false,
ForceNew: true,
},
"user_defined_emr_ecs_role": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"key_pair_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"deposit_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"FULLY_MANAGED", "HALF_MANAGED"}, false),
Default: "HALF_MANAGED",
},
"related_cluster_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudEmrClusterCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := emr.CreateCreateClusterV2Request()
if name, ok := d.GetOk("name"); ok {
request.Name = name.(string)
}
if emrVer, ok := d.GetOk("emr_ver"); ok {
request.EmrVer = emrVer.(string)
}
if clusterType, ok := d.GetOk("cluster_type"); ok {
request.ClusterType = clusterType.(string)
}
if zoneId, ok := d.GetOk("zone_id"); ok {
request.ZoneId = zoneId.(string)
}
if securityGroupId, ok := d.GetOk("security_group_id"); ok {
request.SecurityGroupId = securityGroupId.(string)
}
if publicIp, ok := d.GetOkExists("is_open_public_ip"); ok {
request.IsOpenPublicIp = requests.NewBoolean(publicIp.(bool))
}
if userDefinedRole, ok := d.GetOk("user_defined_emr_ecs_role"); ok {
request.UserDefinedEmrEcsRole = userDefinedRole.(string)
}
if sshEnable, ok := d.GetOkExists("ssh_enable"); ok {
request.SshEnable = requests.NewBoolean(sshEnable.(bool))
}
if masterPwd, ok := d.GetOk("master_pwd"); ok {
request.MasterPwd = masterPwd.(string)
}
if chargeType, ok := d.GetOk("charge_type"); ok {
request.ChargeType = chargeType.(string)
}
if period, ok := d.GetOk("period"); ok {
request.Period = requests.NewInteger(period.(int))
}
if keyPairName, ok := d.GetOk("key_pair_name"); ok {
request.KeyPairName = keyPairName.(string)
}
if depositType, ok := d.GetOk("deposit_type"); ok {
request.DepositType = depositType.(string)
}
if ha, ok := d.GetOkExists("high_availability_enable"); ok {
request.HighAvailabilityEnable = requests.NewBoolean(ha.(bool))
}
if eas, ok := d.GetOkExists("eas_enable"); ok {
request.EasEnable = requests.NewBoolean(eas.(bool))
}
if localMeta, ok := d.GetOkExists("use_local_metadb"); ok {
request.UseLocalMetaDb = requests.NewBoolean(localMeta.(bool))
}
if relatedClusterId, ok := d.GetOk("related_cluster_id"); ok {
request.RelatedClusterId = relatedClusterId.(string)
}
if optionSoftware, ok := d.GetOk("option_software_list"); ok {
var softwareList []string
for _, vv := range optionSoftware.([]interface{}) {
softwareList = append(softwareList, vv.(string))
}
request.OptionSoftWareList = &softwareList
}
vpcService := VpcService{client}
vswitchId := Trim(d.Get("vswitch_id").(string))
request.NetType = "classic"
if vswitchId != "" {
request.VSwitchId = vswitchId
request.NetType = "vpc"
vsw, err := vpcService.DescribeVSwitch(vswitchId)
if err != nil {
return WrapError(err)
}
if request.ZoneId == "" {
request.ZoneId = vsw.ZoneId
} else if request.ZoneId != vsw.ZoneId {
return WrapError(Error("The specified vswitch %s isn't in the zone %s.", vsw.VSwitchId, request.ZoneId))
}
request.VpcId = vsw.VpcId
}
var hostGroups []emr.CreateClusterV2HostGroup
if groups, ok := d.GetOk("host_group"); ok {
nodeChecker := map[string]int{}
for _, group := range groups.(*schema.Set).List() {
kv := group.(map[string]interface{})
hostGroup := emr.CreateClusterV2HostGroup{}
if v, ok := kv["period"]; ok {
hostGroup.Period = strconv.Itoa(v.(int))
}
if v, ok := kv["sys_disk_capacity"]; ok {
hostGroup.SysDiskCapacity = v.(string)
}
if v, ok := kv["disk_capacity"]; ok {
hostGroup.DiskCapacity = v.(string)
}
if v, ok := kv["sys_disk_type"]; ok {
hostGroup.SysDiskType = strings.ToUpper(v.(string))
}
if v, ok := kv["disk_type"]; ok {
hostGroup.DiskType = strings.ToUpper(v.(string))
}
if v, ok := kv["host_group_name"]; ok {
hostGroup.HostGroupName = v.(string)
}
if v, ok := kv["disk_count"]; ok {
hostGroup.DiskCount = v.(string)
}
if v, ok := kv["auto_renew"]; ok {
if v.(bool) == false {
hostGroup.AutoRenew = "false"
} else if v.(bool) == true {
hostGroup.AutoRenew = "true"
}
}
if v, ok := kv["gpu_driver"]; ok {
hostGroup.GpuDriver = v.(string)
}
if v, ok := kv["node_count"]; ok {
hostGroup.NodeCount = v.(string)
}
if v, ok := kv["instance_type"]; ok {
hostGroup.InstanceType = v.(string)
}
if v, ok := kv["charge_type"]; ok {
hostGroup.ChargeType = v.(string)
}
if v, ok := kv["host_group_type"]; ok {
hostGroup.HostGroupType = v.(string)
if nodeCount, exist := kv["node_count"]; exist {
count, _ := strconv.Atoi(nodeCount.(string))
nodeChecker[v.(string)] = count
}
}
hostGroups = append(hostGroups, hostGroup)
}
// Gateway emr cluster do not need to check
if request.ClusterType != "GATEWAY" {
if nodeChecker["MASTER"] < 1 || nodeChecker["CORE"] < 2 {
return WrapError(Error("%s emr cluster must contains 1 MASTER node and 2 CORE nodes.",
request.ClusterType))
}
if taskNodeCount, exist := nodeChecker["TASK"]; exist && taskNodeCount < 1 {
return WrapError(Error("%s emr cluster can not create with 0 Task node, must greater than 0.",
request.ClusterType))
}
if ha, ok := d.GetOkExists("high_availability_enable"); ok && ha.(bool) && nodeChecker["MASTER"] < 2 {
return WrapError(Error("High available %s emr cluster must contains 2 MASTER nodes",
request.ClusterType))
}
}
}
request.HostGroup = &hostGroups
var bootstrapActions []emr.CreateClusterV2BootstrapAction
if actions, ok := d.GetOk("bootstrap_action"); ok {
for _, action := range actions.(*schema.Set).List() {
kv := action.(map[string]interface{})
bootstrapAction := emr.CreateClusterV2BootstrapAction{}
if v, ok := kv["name"]; ok {
bootstrapAction.Name = v.(string)
}
if v, ok := kv["path"]; ok {
bootstrapAction.Path = v.(string)
}
if v, ok := kv["arg"]; ok {
bootstrapAction.Arg = v.(string)
}
bootstrapActions = append(bootstrapActions, bootstrapAction)
}
}
request.BootstrapAction = &bootstrapActions
raw, err := client.WithEmrClient(func(emrClient *emr.Client) (interface{}, error) {
return emrClient.CreateClusterV2(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_emr_cluster", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*emr.CreateClusterV2Response)
d.SetId(response.ClusterId)
d.Partial(true)
emrService := EmrService{client}
if err := emrService.setEmrClusterTags(d); err != nil {
return WrapError(err)
}
d.Partial(false)
stateConf := BuildStateConf([]string{"CREATING"}, []string{"IDLE"}, d.Timeout(schema.TimeoutCreate), 10*time.Minute, emrService.EmrClusterStateRefreshFunc(d.Id(), []string{"CREATE_FAILED"}))
stateConf.PollInterval = 10 * time.Second
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudEmrClusterRead(d, meta)
}
func resourceAlicloudEmrClusterRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
emrService := EmrService{client}
object, err := emrService.DescribeEmrCluster(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", object.ClusterInfo.Name)
d.Set("charge_type", object.ClusterInfo.ChargeType)
d.Set("high_availability_enable", object.ClusterInfo.HighAvailabilityEnable)
d.Set("net_type", object.ClusterInfo.NetType)
d.Set("security_group_id", object.ClusterInfo.SecurityGroupId)
d.Set("net_type", object.ClusterInfo.NetType)
d.Set("vpc_id", object.ClusterInfo.VpcId)
d.Set("vswitch_id", object.ClusterInfo.VSwitchId)
d.Set("use_local_metadb", object.ClusterInfo.LocalMetaDb)
d.Set("deposit_type", object.ClusterInfo.DepositType)
d.Set("eas_enable", object.ClusterInfo.EasEnable)
d.Set("user_defined_emr_ecs_role", object.ClusterInfo.UserDefinedEmrEcsRole)
d.Set("related_cluster_id", object.ClusterInfo.RelateClusterInfo.ClusterId)
d.Set("zone_id", object.ClusterInfo.ZoneId)
d.Set("emr_ver", object.ClusterInfo.SoftwareInfo.EmrVer)
d.Set("cluster_type", object.ClusterInfo.SoftwareInfo.ClusterType)
tags, err := emrService.DescribeEmrClusterTags(d.Id(), TagResourceInstance)
if err != nil {
return WrapError(err)
}
d.Set("tags", emrService.tagsToMap(tags))
return nil
}
func resourceAlicloudEmrClusterUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
emrService := EmrService{client}
d.Partial(true)
if err := emrService.setEmrClusterTags(d); err != nil {
return WrapError(err)
}
if d.HasChange("name") {
request := emr.CreateModifyClusterNameRequest()
request.Name = d.Get("name").(string)
request.Id = d.Id()
raw, err := client.WithEmrClient(func(emrClient *emr.Client) (interface{}, error) {
return emrClient.ModifyClusterName(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("name")
}
if d.HasChange("host_group") {
v1, v2 := d.GetChange("host_group")
oldHostGroup := map[string]map[string]interface{}{}
for _, v := range v1.(*schema.Set).List() {
hostGroupName := v.(map[string]interface{})["host_group_name"].(string)
oldHostGroup[hostGroupName] = v.(map[string]interface{})
}
newHostGroup := map[string]map[string]interface{}{}
for _, v := range v2.(*schema.Set).List() {
hostGroupName := v.(map[string]interface{})["host_group_name"].(string)
newHostGroup[hostGroupName] = v.(map[string]interface{})
}
resizeRequest := emr.CreateResizeClusterV2Request()
resizeRequest.ClusterId = d.Id()
var resizeHostGroups []emr.ResizeClusterV2HostGroup
releaseRequest := emr.CreateReleaseClusterHostGroupRequest()
releaseRequest.ClusterId = d.Id()
for k, v1 := range newHostGroup {
if _, ok := oldHostGroup[k]; ok {
newNodeCount, _ := strconv.Atoi(v1["node_count"].(string))
listHostGroupRequest := emr.CreateListClusterHostGroupRequest()
listHostGroupRequest.ClusterId = d.Id()
listHostGroupRequest.HostGroupName = k
raw, err := client.WithEmrClient(func(emrClient *emr.Client) (interface{}, error) {
return emrClient.ListClusterHostGroup(listHostGroupRequest)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_emr_cluster", listHostGroupRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
resp := raw.(*emr.ListClusterHostGroupResponse)
if len(resp.HostGroupList.HostGroup) == 0 {
continue
}
hostGroupId := resp.HostGroupList.HostGroup[0].HostGroupId
oldNodeCount := resp.HostGroupList.HostGroup[0].NodeCount
// scala up
if oldNodeCount < newNodeCount {
count := newNodeCount - oldNodeCount
resizeHostGroup := emr.ResizeClusterV2HostGroup{}
resizeHostGroup.ClusterId = d.Id()
resizeHostGroup.HostGroupId = hostGroupId
resizeHostGroup.NodeCount = strconv.Itoa(count)
resizeHostGroup.InstanceType = v1["instance_type"].(string)
resizeHostGroup.HostGroupType = v1["host_group_type"].(string)
resizeHostGroup.HostGroupName = k
resizeHostGroup.ChargeType = v1["charge_type"].(string)
resizeHostGroup.SysDiskType = v1["sys_disk_type"].(string)
resizeHostGroup.SysDiskCapacity = v1["sys_disk_capacity"].(string)
resizeHostGroup.DiskType = v1["disk_type"].(string)
resizeHostGroup.DiskCount = v1["disk_count"].(string)
resizeHostGroup.DiskCapacity = v1["disk_capacity"].(string)
resizeHostGroups = append(resizeHostGroups, resizeHostGroup)
} else if oldNodeCount > newNodeCount { //scale down
releaseRequest.HostGroupId = hostGroupId
releaseRequest.InstanceIdList = v1["instance_list"].(string)
_, err := client.WithEmrClient(func(emrClient *emr.Client) (interface{}, error) {
return emrClient.ReleaseClusterHostGroup(releaseRequest)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_emr_cluster", releaseRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
} else { // 'Task' HostGroupType may not exist when create emr_cluster
clusterHostGroupRequest := emr.CreateCreateClusterHostGroupRequest()
clusterHostGroupRequest.ClusterId = d.Id()
clusterHostGroupRequest.HostGroupType = v1["host_group_type"].(string)
clusterHostGroupRequest.HostGroupName = k
createClusterHostGroupResponse, err := client.WithEmrClient(func(emrClient *emr.Client) (interface{}, error) {
return emrClient.CreateClusterHostGroup(clusterHostGroupRequest)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_emr_cluster", clusterHostGroupRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(clusterHostGroupRequest.GetActionName(), createClusterHostGroupResponse, clusterHostGroupRequest.RpcRequest, clusterHostGroupRequest)
listHostGroupRequest := emr.CreateListClusterHostGroupRequest()
listHostGroupRequest.ClusterId = d.Id()
listHostGroupRequest.HostGroupName = k
raw, err := client.WithEmrClient(func(emrClient *emr.Client) (interface{}, error) {
return emrClient.ListClusterHostGroup(listHostGroupRequest)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_emr_cluster", listHostGroupRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
listHostGroupResponse := raw.(*emr.ListClusterHostGroupResponse)
if len(listHostGroupResponse.HostGroupList.HostGroup) == 0 {
continue
}
hostGroupId := listHostGroupResponse.HostGroupList.HostGroup[0].HostGroupId
newNodeCount, _ := strconv.Atoi(v1["node_count"].(string))
if newNodeCount <= 0 {
return WrapError(Error("emr cluster can not resize with 0 Task node, must greater than 0."))
}
resizeHostGroup := emr.ResizeClusterV2HostGroup{}
resizeHostGroup.ClusterId = d.Id()
resizeHostGroup.HostGroupId = hostGroupId
resizeHostGroup.HostGroupName = k
resizeHostGroup.NodeCount = strconv.Itoa(newNodeCount)
resizeHostGroup.ChargeType = v1["charge_type"].(string)
resizeHostGroup.InstanceType = v1["instance_type"].(string)
resizeHostGroup.HostGroupType = v1["host_group_type"].(string)
resizeHostGroup.SysDiskType = v1["sys_disk_type"].(string)
resizeHostGroup.SysDiskCapacity = v1["sys_disk_capacity"].(string)
resizeHostGroup.DiskType = v1["disk_type"].(string)
resizeHostGroup.DiskCount = v1["disk_count"].(string)
resizeHostGroup.DiskCapacity = v1["disk_capacity"].(string)
resizeHostGroups = append(resizeHostGroups, resizeHostGroup)
}
}
if len(resizeHostGroups) != 0 {
resizeRequest.HostGroup = &resizeHostGroups
_, err := client.WithEmrClient(func(emrClient *emr.Client) (interface{}, error) {
return emrClient.ResizeClusterV2(resizeRequest)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_emr_cluster", resizeRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("host_group")
}
d.Partial(false)
return nil
}
func resourceAlicloudEmrClusterDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
emrService := EmrService{client}
request := emr.CreateReleaseClusterRequest()
request.Id = d.Id()
request.ForceRelease = requests.NewBoolean(true)
raw, err := client.WithEmrClient(func(emrClient *emr.Client) (interface{}, error) {
return emrClient.ReleaseCluster(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
stateConf := BuildStateConf([]string{"RELEASING"}, []string{}, d.Timeout(schema.TimeoutDelete), 1*time.Minute, emrService.EmrClusterStateRefreshFunc(d.Id(), []string{"RELEASE_FAILED"}))
stateConf.PollInterval = 5 * time.Second
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return WrapError(emrService.WaitForEmrCluster(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEnsKeyPair() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEnsKeyPairCreate,
Read: resourceAlicloudEnsKeyPairRead,
Delete: resourceAlicloudEnsKeyPairDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"key_pair_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"version": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudEnsKeyPairCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateKeyPair"
request := make(map[string]interface{})
conn, err := client.NewEnsClient()
if err != nil {
return WrapError(err)
}
request["KeyPairName"] = d.Get("key_pair_name")
request["Version"] = d.Get("version")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-11-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ens_key_pair", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["KeyPairName"], ":", request["Version"]))
return resourceAlicloudEnsKeyPairRead(d, meta)
}
func resourceAlicloudEnsKeyPairRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ensService := EnsService{client}
_, err := ensService.DescribeEnsKeyPair(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ens_key_pair ensService.DescribeEnsKeyPair Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("key_pair_name", parts[0])
d.Set("version", parts[1])
return nil
}
func resourceAlicloudEnsKeyPairDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteKeyPairs"
var response map[string]interface{}
conn, err := client.NewEnsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"KeyPairName": parts[0],
"Version": parts[1],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-11-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"strconv"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ess"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEssAlarm() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunEssAlarmCreate,
Read: resourceAliyunEssAlarmRead,
Update: resourceAliyunEssAlarmUpdate,
Delete: resourceAliyunEssAlarmDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"enable": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"alarm_actions": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Required: true,
MaxItems: 5,
MinItems: 1,
},
"scaling_group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"metric_type": {
Type: schema.TypeString,
Optional: true,
Default: "system",
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"system", "custom"}, false),
},
"metric_name": {
Type: schema.TypeString,
Required: true,
},
"period": {
Type: schema.TypeInt,
Optional: true,
Default: 300,
ForceNew: true,
ValidateFunc: validation.IntInSlice([]int{60, 120, 300, 900}),
},
"statistics": {
Type: schema.TypeString,
Optional: true,
Default: Average,
ValidateFunc: validation.StringInSlice([]string{
string(Average),
string(Minimum),
string(Maximum),
}, false),
},
"threshold": {
Type: schema.TypeString,
Required: true,
},
"comparison_operator": {
Type: schema.TypeString,
Optional: true,
Default: ">=",
ValidateFunc: validation.StringInSlice([]string{">", ">=", "<", "<="}, false),
},
"evaluation_count": {
Type: schema.TypeInt,
Optional: true,
Default: 3,
ValidateFunc: validation.IntAtLeast(0),
},
"cloud_monitor_group_id": {
Type: schema.TypeInt,
Optional: true,
},
"dimensions": {
Type: schema.TypeMap,
Optional: true,
Computed: true,
},
"state": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAliyunEssAlarmCreate(d *schema.ResourceData, meta interface{}) error {
request, err := buildAlicloudEssAlarmArgs(d)
if err != nil {
return WrapError(err)
}
client := meta.(*connectivity.AliyunClient)
request.RegionId = client.RegionId
var raw interface{}
if err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.CreateAlarm(request)
})
if err != nil {
if IsExpectedErrors(err, []string{Throttling}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ess_alarm", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*ess.CreateAlarmResponse)
d.SetId(response.AlarmTaskId)
// enable or disable alarm
enable := d.Get("enable")
if !enable.(bool) {
disableAlarmRequest := ess.CreateDisableAlarmRequest()
disableAlarmRequest.RegionId = client.RegionId
disableAlarmRequest.AlarmTaskId = response.AlarmTaskId
raw, err = client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DisableAlarm(disableAlarmRequest)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), disableAlarmRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(disableAlarmRequest.GetActionName(), raw, disableAlarmRequest.RpcRequest, disableAlarmRequest)
}
return resourceAliyunEssAlarmRead(d, meta)
}
func resourceAliyunEssAlarmRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
object, err := essService.DescribeEssAlarm(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", object.Name)
d.Set("description", object.Description)
d.Set("alarm_actions", object.AlarmActions.AlarmAction)
d.Set("scaling_group_id", object.ScalingGroupId)
d.Set("metric_type", object.MetricType)
d.Set("metric_name", object.MetricName)
d.Set("period", object.Period)
d.Set("statistics", object.Statistics)
d.Set("threshold", strconv.FormatFloat(object.Threshold, 'f', -1, 32))
d.Set("comparison_operator", object.ComparisonOperator)
d.Set("evaluation_count", object.EvaluationCount)
d.Set("state", object.State)
d.Set("enable", object.Enable)
dims := make([]ess.Dimension, 0, len(object.Dimensions.Dimension))
for _, dimension := range object.Dimensions.Dimension {
if dimension.DimensionKey == GroupId {
d.Set("cloud_monitor_group_id", dimension.DimensionValue)
} else {
dims = append(dims, dimension)
}
}
if err := d.Set("dimensions", essService.flattenDimensionsToMap(dims)); err != nil {
return WrapError(err)
}
return nil
}
func resourceAliyunEssAlarmUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ess.CreateModifyAlarmRequest()
request.AlarmTaskId = d.Id()
request.RegionId = client.RegionId
d.Partial(true)
if metricType, ok := d.GetOk("metric_type"); ok && metricType.(string) != "" {
request.MetricType = metricType.(string)
}
if d.HasChange("name") {
request.Name = d.Get("name").(string)
}
if d.HasChange("description") {
request.Description = d.Get("description").(string)
}
if d.HasChange("alarm_actions") {
if v, ok := d.GetOk("alarm_actions"); ok {
alarmActions := expandStringList(v.(*schema.Set).List())
if len(alarmActions) > 0 {
request.AlarmAction = &alarmActions
}
}
}
if d.HasChange("metric_name") {
request.MetricName = d.Get("metric_name").(string)
}
if d.HasChange("statistics") {
request.Statistics = d.Get("statistics").(string)
}
if d.HasChange("threshold") {
request.Threshold = requests.Float(d.Get("threshold").(string))
}
if d.HasChange("comparison_operator") {
request.ComparisonOperator = d.Get("comparison_operator").(string)
}
if d.HasChange("evaluation_count") {
request.EvaluationCount = requests.NewInteger(d.Get("evaluation_count").(int))
}
if v, ok := d.GetOk("cloud_monitor_group_id"); ok {
request.GroupId = requests.NewInteger(v.(int))
}
dimensions := d.Get("dimensions").(map[string]interface{})
createAlarmDimensions := make([]ess.ModifyAlarmDimension, 0, len(dimensions))
for k, v := range dimensions {
if k == UserId || k == ScalingGroup {
return WrapError(Error("Invalide dimension keys, %s", k))
}
if k != "" {
dimension := ess.ModifyAlarmDimension{
DimensionKey: k,
DimensionValue: v.(string),
}
createAlarmDimensions = append(createAlarmDimensions, dimension)
}
}
request.Dimension = &createAlarmDimensions
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.ModifyAlarm(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("name")
d.SetPartial("description")
d.SetPartial("alarm_actions")
d.SetPartial("metric_name")
d.SetPartial("statistics")
d.SetPartial("threshold")
d.SetPartial("comparison_operator")
d.SetPartial("evaluation_count")
d.SetPartial("cloud_monitor_group_id")
d.SetPartial("dimensions")
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
if d.HasChange("enable") {
enable := d.Get("enable")
if enable.(bool) {
enableAlarmRequest := ess.CreateEnableAlarmRequest()
enableAlarmRequest.AlarmTaskId = d.Id()
raw, err = client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.EnableAlarm(enableAlarmRequest)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), enableAlarmRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(enableAlarmRequest.GetActionName(), raw)
} else {
disableAlarmRequest := ess.CreateDisableAlarmRequest()
disableAlarmRequest.AlarmTaskId = d.Id()
raw, err = client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DisableAlarm(disableAlarmRequest)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), disableAlarmRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(disableAlarmRequest.GetActionName(), raw)
}
d.SetPartial("enable")
}
d.Partial(false)
return resourceAliyunEssAlarmRead(d, meta)
}
func resourceAliyunEssAlarmDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
request := ess.CreateDeleteAlarmRequest()
request.AlarmTaskId = d.Id()
request.RegionId = client.RegionId
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DeleteAlarm(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"404"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(essService.WaitForEssAlarm(d.Id(), Deleted, DefaultTimeout))
}
func buildAlicloudEssAlarmArgs(d *schema.ResourceData) (*ess.CreateAlarmRequest, error) {
request := ess.CreateCreateAlarmRequest()
if name, ok := d.GetOk("name"); ok && name.(string) != "" {
request.Name = name.(string)
}
if description, ok := d.GetOk("description"); ok && description.(string) != "" {
request.Description = description.(string)
}
if v, ok := d.GetOk("alarm_actions"); ok {
alarmActions := expandStringList(v.(*schema.Set).List())
request.AlarmAction = &alarmActions
}
if scalingGroupId := d.Get("scaling_group_id").(string); scalingGroupId != "" {
request.ScalingGroupId = scalingGroupId
}
if metricType, ok := d.GetOk("metric_type"); ok && metricType.(string) != "" {
request.MetricType = metricType.(string)
}
if metricName := d.Get("metric_name").(string); metricName != "" {
request.MetricName = metricName
}
if period, ok := d.GetOk("period"); ok && period.(int) > 0 {
request.Period = requests.NewInteger(period.(int))
}
if statistics, ok := d.GetOk("statistics"); ok && statistics.(string) != "" {
request.Statistics = statistics.(string)
}
if v, ok := d.GetOk("threshold"); ok {
threshold, err := strconv.ParseFloat(v.(string), 32)
if err != nil {
return nil, WrapError(err)
}
request.Threshold = requests.NewFloat(threshold)
}
if comparisonOperator, ok := d.GetOk("comparison_operator"); ok && comparisonOperator.(string) != "" {
request.ComparisonOperator = comparisonOperator.(string)
}
if evaluationCount, ok := d.GetOk("evaluation_count"); ok && evaluationCount.(int) > 0 {
request.EvaluationCount = requests.NewInteger(evaluationCount.(int))
}
if groupId, ok := d.GetOk("cloud_monitor_group_id"); ok {
request.GroupId = requests.NewInteger(groupId.(int))
}
if v, ok := d.GetOk("dimensions"); ok {
dimensions := v.(map[string]interface{})
createAlarmDimensions := make([]ess.CreateAlarmDimension, 0, len(dimensions))
for k, v := range dimensions {
if k == UserId || k == ScalingGroup {
return nil, WrapError(Error("Invalide dimension keys, %s", k))
}
if k != "" {
dimension := ess.CreateAlarmDimension{
DimensionKey: k,
DimensionValue: v.(string),
}
createAlarmDimensions = append(createAlarmDimensions, dimension)
}
}
request.Dimension = &createAlarmDimensions
}
return request, nil
}
package alicloud
import (
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ess"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEssAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunEssAttachmentCreate,
Read: resourceAliyunEssAttachmentRead,
Update: resourceAliyunEssAttachmentUpdate,
Delete: resourceAliyunEssAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"scaling_group_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"instance_ids": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Required: true,
MaxItems: 20,
MinItems: 1,
},
"force": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func resourceAliyunEssAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
d.SetId(d.Get("scaling_group_id").(string))
return resourceAliyunEssAttachmentUpdate(d, meta)
}
func resourceAliyunEssAttachmentUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
d.Partial(true)
if d.HasChange("instance_ids") {
object, err := essService.DescribeEssScalingGroup(d.Id())
if err != nil {
return WrapError(err)
}
if object.LifecycleState == string(Inactive) {
return WrapError(Error("Scaling group current status is %s, please active it before attaching or removing ECS instances.", object.LifecycleState))
} else {
if err := essService.WaitForEssScalingGroup(object.ScalingGroupId, Active, DefaultTimeout); err != nil {
return WrapError(err)
}
}
o, n := d.GetChange("instance_ids")
os := o.(*schema.Set)
ns := n.(*schema.Set)
remove := os.Difference(ns).List()
add := convertArrayInterfaceToArrayString(ns.Difference(os).List())
if len(add) > 0 {
request := ess.CreateAttachInstancesRequest()
request.RegionId = client.RegionId
request.ScalingGroupId = d.Id()
request.InstanceId = &add
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.AttachInstances(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectCapacity.MaxSize"}) {
instances, err := essService.DescribeEssAttachment(d.Id(), make([]string, 0))
if !NotFoundError(err) {
return resource.NonRetryableError(err)
}
var autoAdded, attached []string
if len(instances) > 0 {
for _, inst := range instances {
if inst.CreationType == "Attached" {
attached = append(attached, inst.InstanceId)
} else {
autoAdded = append(autoAdded, inst.InstanceId)
}
}
}
if len(add) > object.MaxSize {
return resource.NonRetryableError(WrapError(Error("To attach %d instances, the total capacity will be greater than the scaling group max size %d. "+
"Please enlarge scaling group max size.", len(add), object.MaxSize)))
}
if len(autoAdded) > 0 {
if d.Get("force").(bool) {
if err := essService.EssRemoveInstances(d.Id(), autoAdded); err != nil {
return resource.NonRetryableError(WrapError(err))
}
time.Sleep(5)
return resource.RetryableError(WrapError(err))
} else {
return resource.NonRetryableError(WrapError(Error("To attach the instances, the total capacity will be greater than the scaling group max size %d."+
"Please enlarge scaling group max size or set 'force' to true to remove autocreated instances: %#v.", object.MaxSize, autoAdded)))
}
}
if len(attached) > 0 {
return resource.NonRetryableError(WrapError(Error("To attach the instances, the total capacity will be greater than the scaling group max size %d. "+
"Please enlarge scaling group max size or remove already attached instances: %#v.", object.MaxSize, attached)))
}
}
if IsExpectedErrors(err, []string{"ScalingActivityInProgress"}) {
time.Sleep(5)
return resource.RetryableError(WrapError(err))
}
return resource.NonRetryableError(WrapError(err))
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapError(err)
}
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
instances, err := essService.DescribeEssAttachment(d.Id(), add)
if err != nil {
return resource.NonRetryableError(WrapError(err))
}
if len(instances) < 0 {
return resource.RetryableError(WrapError(Error("There are no ECS instances have been attached.")))
}
for _, inst := range instances {
if inst.LifecycleState != string(InService) {
return resource.RetryableError(WrapError(Error("There are still ECS instances are not %s.", string(InService))))
}
}
return nil
})
if err != nil {
return WrapError(err)
}
}
if len(remove) > 0 {
if err := essService.EssRemoveInstances(d.Id(), convertArrayInterfaceToArrayString(remove)); err != nil {
return WrapError(err)
}
}
d.SetPartial("instance_ids")
}
d.Partial(false)
return resourceAliyunEssAttachmentRead(d, meta)
}
func resourceAliyunEssAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
object, err := essService.DescribeEssAttachment(d.Id(), make([]string, 0))
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
var instanceIds []string
for _, inst := range object {
instanceIds = append(instanceIds, inst.InstanceId)
}
d.Set("scaling_group_id", object[0].ScalingGroupId)
d.Set("instance_ids", instanceIds)
return nil
}
func resourceAliyunEssAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
removed := convertArrayInterfaceToArrayString(d.Get("instance_ids").(*schema.Set).List())
if len(removed) < 1 {
return nil
}
object, err := essService.DescribeEssScalingGroup(d.Id())
if err != nil {
return WrapError(err)
}
if err := essService.WaitForEssScalingGroup(object.ScalingGroupId, Active, DefaultTimeout); err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
if err := resource.Retry(5*time.Minute, func() *resource.RetryError {
request := ess.CreateRemoveInstancesRequest()
request.RegionId = client.RegionId
request.ScalingGroupId = d.Id()
if len(removed) > 0 {
request.InstanceId = &removed
} else {
return nil
}
raw, err := essService.client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.RemoveInstances(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectCapacity.MinSize"}) {
instances, err := essService.DescribeEssAttachment(d.Id(), removed)
if len(instances) > 0 {
if object.MinSize == 0 {
return resource.RetryableError(WrapError(err))
}
return resource.NonRetryableError(WrapError(Error("To remove %d instances, the total capacity will be lesser than the scaling group min size %d. "+
"Please shorten scaling group min size and try again.", len(removed), object.MinSize)))
}
}
if IsExpectedErrors(err, []string{"ScalingActivityInProgress", "IncorrectScalingGroupStatus"}) {
time.Sleep(5)
return resource.RetryableError(WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR))
}
if IsExpectedErrors(err, []string{"InvalidScalingGroupId.NotFound"}) {
return nil
}
return resource.NonRetryableError(WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR))
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
time.Sleep(3 * time.Second)
instances, err := essService.DescribeEssAttachment(d.Id(), removed)
if err != nil {
if NotFoundError(err) {
return nil
}
return resource.NonRetryableError(WrapError(err))
}
if len(instances) > 0 {
removed = make([]string, 0)
for _, inst := range instances {
removed = append(removed, inst.InstanceId)
}
return resource.RetryableError(WrapError(Error("There are still ECS instances in the scaling group.")))
}
return nil
}); err != nil {
return WrapError(err)
}
return WrapError(essService.WaitForEssAttachment(d.Id(), Deleted, DefaultTimeout))
}
func convertArrayInterfaceToArrayString(elm []interface{}) (arr []string) {
if len(elm) < 1 {
return
}
for _, e := range elm {
arr = append(arr, e.(string))
}
return
}
package alicloud
import (
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ess"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEssLifecycleHook() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunEssLifeCycleHookCreate,
Read: resourceAliyunEssLifeCycleHookRead,
Update: resourceAliyunEssLifeCycleHookUpdate,
Delete: resourceAliyunEssLifeCycleHookDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"scaling_group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"lifecycle_transition": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"SCALE_IN", "SCALE_OUT"}, false),
},
"heartbeat_timeout": {
Type: schema.TypeInt,
Optional: true,
Default: 600,
ValidateFunc: validation.IntBetween(30, 21600),
},
"default_result": {
Type: schema.TypeString,
Optional: true,
Default: "CONTINUE",
ValidateFunc: validation.StringInSlice([]string{"CONTINUE", "ABANDON"}, false),
},
"notification_arn": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"notification_metadata": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
},
}
}
func resourceAliyunEssLifeCycleHookCreate(d *schema.ResourceData, meta interface{}) error {
request := buildAlicloudEssLifeCycleHookArgs(d)
client := meta.(*connectivity.AliyunClient)
request.RegionId = client.RegionId
if err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.CreateLifecycleHook(request)
})
if err != nil {
if IsExpectedErrors(err, []string{Throttling}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ess.CreateLifecycleHookResponse)
d.SetId(response.LifecycleHookId)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ess_lifecyclehook", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return resourceAliyunEssLifeCycleHookRead(d, meta)
}
func resourceAliyunEssLifeCycleHookRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
object, err := essService.DescribeEssLifecycleHook(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("scaling_group_id", object.ScalingGroupId)
d.Set("name", object.LifecycleHookName)
d.Set("lifecycle_transition", object.LifecycleTransition)
d.Set("heartbeat_timeout", object.HeartbeatTimeout)
d.Set("default_result", object.DefaultResult)
d.Set("notification_arn", object.NotificationArn)
d.Set("notification_metadata", object.NotificationMetadata)
return nil
}
func resourceAliyunEssLifeCycleHookUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ess.CreateModifyLifecycleHookRequest()
request.LifecycleHookId = d.Id()
request.RegionId = client.RegionId
if d.HasChange("lifecycle_transition") {
request.LifecycleTransition = d.Get("lifecycle_transition").(string)
}
if d.HasChange("heartbeat_timeout") {
request.HeartbeatTimeout = requests.NewInteger(d.Get("heartbeat_timeout").(int))
}
if d.HasChange("default_result") {
request.DefaultResult = d.Get("default_result").(string)
}
if d.HasChange("notification_arn") {
request.NotificationArn = d.Get("notification_arn").(string)
}
if d.HasChange("notification_metadata") {
request.NotificationMetadata = d.Get("notification_metadata").(string)
}
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.ModifyLifecycleHook(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return resourceAliyunEssLifeCycleHookRead(d, meta)
}
func resourceAliyunEssLifeCycleHookDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
request := ess.CreateDeleteLifecycleHookRequest()
request.LifecycleHookId = d.Id()
request.RegionId = client.RegionId
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DeleteLifecycleHook(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidLifecycleHookId.NotExist"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(essService.WaitForEssLifecycleHook(d.Id(), Deleted, DefaultTimeout))
}
func buildAlicloudEssLifeCycleHookArgs(d *schema.ResourceData) *ess.CreateLifecycleHookRequest {
request := ess.CreateCreateLifecycleHookRequest()
request.ScalingGroupId = d.Get("scaling_group_id").(string)
if v, ok := d.GetOk("name"); ok && v.(string) != "" {
request.LifecycleHookName = v.(string)
}
if transition := d.Get("lifecycle_transition").(string); transition != "" {
request.LifecycleTransition = transition
}
if timeout, ok := d.GetOk("heartbeat_timeout"); ok && timeout.(int) > 0 {
request.HeartbeatTimeout = requests.NewInteger(timeout.(int))
}
if v, ok := d.GetOk("default_result"); ok && v.(string) != "" {
request.DefaultResult = v.(string)
}
if v, ok := d.GetOk("notification_arn"); ok && v.(string) != "" {
request.NotificationArn = v.(string)
}
if v, ok := d.GetOk("notification_metadata"); ok && v.(string) != "" {
request.NotificationMetadata = v.(string)
}
return request
}
package alicloud
import (
"fmt"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ess"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEssNotification() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEssNotificationCreate,
Read: resourceAlicloudEssNotificationRead,
Update: resourceAlicloudEssNotificationUpdate,
Delete: resourceAlicloudEssNotificationDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"notification_arn": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"notification_types": {
Required: true,
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
MinItems: 1,
},
"scaling_group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudEssNotificationCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ess.CreateCreateNotificationConfigurationRequest()
request.RegionId = client.RegionId
request.ScalingGroupId = d.Get("scaling_group_id").(string)
request.NotificationArn = d.Get("notification_arn").(string)
if v, ok := d.GetOk("notification_types"); ok {
notificationTypes := make([]string, 0)
notificationTypeList := v.(*schema.Set).List()
if len(notificationTypeList) > 0 {
for _, n := range notificationTypeList {
notificationTypes = append(notificationTypes, n.(string))
}
}
if len(notificationTypes) > 0 {
request.NotificationType = ¬ificationTypes
}
}
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.CreateNotificationConfiguration(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ess_notification", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetId(fmt.Sprintf("%s:%s", request.ScalingGroupId, request.NotificationArn))
return resourceAlicloudEssNotificationRead(d, meta)
}
func resourceAlicloudEssNotificationRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
object, err := essService.DescribeEssNotification(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("scaling_group_id", object.ScalingGroupId)
d.Set("notification_arn", object.NotificationArn)
d.Set("notification_types", object.NotificationTypes.NotificationType)
return nil
}
func resourceAlicloudEssNotificationUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ess.CreateModifyNotificationConfigurationRequest()
request.RegionId = client.RegionId
parts := strings.SplitN(d.Id(), ":", 2)
request.ScalingGroupId = parts[0]
request.NotificationArn = parts[1]
if d.HasChange("notification_types") {
v := d.Get("notification_types")
notificationTypes := make([]string, 0)
notificationTypeList := v.(*schema.Set).List()
if len(notificationTypeList) > 0 {
for _, n := range notificationTypeList {
notificationTypes = append(notificationTypes, n.(string))
}
}
if len(notificationTypes) > 0 {
request.NotificationType = ¬ificationTypes
}
}
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.ModifyNotificationConfiguration(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return resourceAlicloudEssNotificationRead(d, meta)
}
func resourceAlicloudEssNotificationDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
request := ess.CreateDeleteNotificationConfigurationRequest()
request.RegionId = client.RegionId
parts := strings.SplitN(d.Id(), ":", 2)
request.ScalingGroupId = parts[0]
request.NotificationArn = parts[1]
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DeleteNotificationConfiguration(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"NotificationConfigurationNotExist", "InvalidScalingGroupId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(essService.WaitForEssNotification(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"encoding/base64"
"fmt"
"regexp"
"strconv"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ess"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEssScalingConfiguration() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunEssScalingConfigurationCreate,
Read: resourceAliyunEssScalingConfigurationRead,
Update: resourceAliyunEssScalingConfigurationUpdate,
Delete: resourceAliyunEssScalingConfigurationDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"active": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"enable": {
Type: schema.TypeBool,
Optional: true,
},
"scaling_group_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"image_id": {
Type: schema.TypeString,
Optional: true,
},
"image_name": {
Type: schema.TypeString,
Optional: true,
},
"instance_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^ecs\..*`), "prefix must be 'ecs.'"),
ConflictsWith: []string{"instance_types"},
},
"instance_types": {
Type: schema.TypeList,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Optional: true,
ConflictsWith: []string{"instance_type"},
MaxItems: int(MaxScalingConfigurationInstanceTypes),
},
"io_optimized": {
Type: schema.TypeString,
Optional: true,
Deprecated: "Attribute io_optimized has been deprecated on instance resource. All the launched alicloud instances will be IO optimized. Suggest to remove it from your template.",
},
"is_outdated": {
Type: schema.TypeBool,
Optional: true,
},
"security_group_id": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"security_group_ids"},
},
"security_group_ids": {
Type: schema.TypeList,
Elem: &schema.Schema{
Type: schema.TypeString,
},
ConflictsWith: []string{"security_group_id"},
Optional: true,
MaxItems: 16,
},
"scaling_configuration_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"internet_charge_type": {
Type: schema.TypeString,
Optional: true,
Default: PayByBandwidth,
ValidateFunc: validation.StringInSlice([]string{"PayByBandwidth", "PayByTraffic"}, false),
},
"internet_max_bandwidth_in": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"internet_max_bandwidth_out": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(0, 100),
},
"credit_specification": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{
string(CreditSpecificationStandard),
string(CreditSpecificationUnlimited),
}, false),
},
"system_disk_category": {
Type: schema.TypeString,
Optional: true,
Default: DiskCloudEfficiency,
ValidateFunc: validation.StringInSlice([]string{"cloud", "ephemeral_ssd", "cloud_ssd", "cloud_essd", "cloud_efficiency"}, false),
},
"system_disk_size": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(20, 500),
},
"system_disk_name": {
Type: schema.TypeString,
Optional: true,
},
"system_disk_description": {
Type: schema.TypeString,
Optional: true,
},
"system_disk_auto_snapshot_policy_id": {
Type: schema.TypeString,
Optional: true,
},
"data_disk": {
Optional: true,
Type: schema.TypeList,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"size": {
Type: schema.TypeInt,
Optional: true,
},
"category": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"all", "cloud", "ephemeral_ssd", "cloud_essd", "cloud_efficiency", "cloud_ssd", "local_disk"}, false),
},
"snapshot_id": {
Type: schema.TypeString,
Optional: true,
},
"device": {
Type: schema.TypeString,
Optional: true,
Deprecated: "Attribute device has been deprecated on disk attachment resource. Suggest to remove it from your template.",
},
"delete_with_instance": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"encrypted": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"kms_key_id": {
Type: schema.TypeString,
Optional: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"auto_snapshot_policy_id": {
Type: schema.TypeString,
Optional: true,
},
"performance_level": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"instance_ids": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return true
},
Deprecated: "Field 'instance_ids' has been deprecated from provider version 1.6.0. New resource 'alicloud_ess_attachment' replaces it.",
},
"substitute": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"user_data": {
Type: schema.TypeString,
Optional: true,
},
"role_name": {
Type: schema.TypeString,
Optional: true,
},
"key_name": {
Type: schema.TypeString,
Optional: true,
},
"force_delete": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"tags": {
Type: schema.TypeMap,
Optional: true,
},
"instance_name": {
Type: schema.TypeString,
Optional: true,
Default: "ESS-Instance",
ValidateFunc: validation.StringLenBetween(2, 128),
},
"override": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"password": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("password_inherit").(bool)
},
},
"password_inherit": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"kms_encrypted_password": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("password_inherit").(bool) || d.Get("password").(string) != ""
},
},
"kms_encryption_context": {
Type: schema.TypeMap,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("kms_encrypted_password").(string) == ""
},
Elem: schema.TypeString,
},
"system_disk_performance_level": {
Type: schema.TypeString,
Optional: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
},
"host_name": {
Type: schema.TypeString,
Optional: true,
},
"spot_strategy": {
Type: schema.TypeString,
Optional: true,
},
"spot_price_limit": {
Optional: true,
Type: schema.TypeSet,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"instance_type": {
Type: schema.TypeString,
Optional: true,
},
"price_limit": {
Type: schema.TypeFloat,
Optional: true,
},
},
},
},
},
}
}
func resourceAliyunEssScalingConfigurationCreate(d *schema.ResourceData, meta interface{}) error {
// Ensure instance_type is generation three
client := meta.(*connectivity.AliyunClient)
request, err := buildAlicloudEssScalingConfigurationArgs(d, meta)
if err != nil {
return WrapError(err)
}
request.IoOptimized = string(IOOptimized)
if d.Get("is_outdated").(bool) == true {
request.IoOptimized = string(NoneOptimized)
}
if err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.CreateScalingConfiguration(request)
})
if err != nil {
if IsExpectedErrors(err, []string{Throttling, "IncorrectScalingGroupStatus"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ess.CreateScalingConfigurationResponse)
d.SetId(response.ScalingConfigurationId)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ess_scalingconfiguration", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return resourceAliyunEssScalingConfigurationUpdate(d, meta)
}
func resourceAliyunEssScalingConfigurationUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
d.Partial(true)
if strings.Contains(d.Id(), COLON_SEPARATED) {
d.SetId(strings.Split(d.Id(), COLON_SEPARATED)[1])
}
if d.HasChange("active") {
c, err := essService.DescribeEssScalingConfiguration(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
if d.Get("active").(bool) {
if c.LifecycleState == string(Inactive) {
err := essService.ActiveEssScalingConfiguration(c.ScalingGroupId, d.Id())
if err != nil {
return WrapError(err)
}
}
} else {
if c.LifecycleState == string(Active) {
_, err := activeSubstituteScalingConfiguration(d, meta)
if err != nil {
return WrapError(err)
}
}
}
d.SetPartial("active")
}
if err := enableEssScalingConfiguration(d, meta); err != nil {
return WrapError(err)
}
if err := modifyEssScalingConfiguration(d, meta); err != nil {
return WrapError(err)
}
d.Partial(false)
return resourceAliyunEssScalingConfigurationRead(d, meta)
}
func modifyEssScalingConfiguration(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ess.CreateModifyScalingConfigurationRequest()
request.ScalingConfigurationId = d.Id()
if d.HasChange("override") {
request.Override = requests.NewBoolean(d.Get("override").(bool))
d.SetPartial("override")
}
if d.HasChange("password_inherit") {
request.PasswordInherit = requests.NewBoolean(d.Get("password_inherit").(bool))
d.SetPartial("password_inherit")
}
if d.HasChange("image_id") || d.Get("override").(bool) {
request.ImageId = d.Get("image_id").(string)
d.SetPartial("image_id")
}
if d.HasChange("image_name") || d.Get("override").(bool) {
request.ImageName = d.Get("image_name").(string)
d.SetPartial("image_name")
}
hasChangeInstanceType := d.HasChange("instance_type")
hasChangeInstanceTypes := d.HasChange("instance_types")
if hasChangeInstanceType || hasChangeInstanceTypes || d.Get("override").(bool) {
instanceType := d.Get("instance_type").(string)
instanceTypes := d.Get("instance_types").([]interface{})
if instanceType == "" && (instanceTypes == nil || len(instanceTypes) == 0) {
return fmt.Errorf("instance_type or instance_types must be assigned")
}
types := make([]string, 0, int(MaxScalingConfigurationInstanceTypes))
if instanceTypes != nil && len(instanceTypes) > 0 {
types = expandStringList(instanceTypes)
}
if instanceType != "" {
types = append(types, instanceType)
}
request.InstanceTypes = &types
}
hasChangeSecurityGroupId := d.HasChange("security_group_id")
hasChangeSecurityGroupIds := d.HasChange("security_group_ids")
if hasChangeSecurityGroupId || hasChangeSecurityGroupIds || d.Get("override").(bool) {
securityGroupId := d.Get("security_group_id").(string)
securityGroupIds := d.Get("security_group_ids").([]interface{})
if securityGroupId == "" && (securityGroupIds == nil || len(securityGroupIds) == 0) {
return fmt.Errorf("securityGroupId or securityGroupIds must be assigned")
}
if securityGroupIds != nil && len(securityGroupIds) > 0 {
sgs := expandStringList(securityGroupIds)
request.SecurityGroupIds = &sgs
}
if securityGroupId != "" {
request.SecurityGroupId = securityGroupId
}
}
if d.HasChange("scaling_configuration_name") {
request.ScalingConfigurationName = d.Get("scaling_configuration_name").(string)
d.SetPartial("scaling_configuration_name")
}
if d.HasChange("internet_charge_type") {
request.InternetChargeType = d.Get("internet_charge_type").(string)
d.SetPartial("internet_charge_type")
}
if d.HasChange("internet_max_bandwidth_out") {
request.InternetMaxBandwidthOut = requests.NewInteger(d.Get("internet_max_bandwidth_out").(int))
d.SetPartial("internet_max_bandwidth_out")
}
if d.HasChange("credit_specification") {
request.CreditSpecification = d.Get("credit_specification").(string)
d.SetPartial("credit_specification")
}
if d.HasChange("system_disk_category") {
request.SystemDiskCategory = d.Get("system_disk_category").(string)
d.SetPartial("system_disk_category")
}
if d.HasChange("system_disk_size") {
request.SystemDiskSize = requests.NewInteger(d.Get("system_disk_size").(int))
d.SetPartial("system_disk_size")
}
if d.HasChange("system_disk_name") {
request.SystemDiskDiskName = d.Get("system_disk_name").(string)
d.SetPartial("system_disk_name")
}
if d.HasChange("system_disk_description") {
request.SystemDiskDescription = d.Get("system_disk_description").(string)
d.SetPartial("system_disk_description")
}
if d.HasChange("system_disk_auto_snapshot_policy_id") {
request.SystemDiskAutoSnapshotPolicyId = d.Get("system_disk_auto_snapshot_policy_id").(string)
d.SetPartial("system_disk_auto_snapshot_policy_id")
}
if d.HasChange("system_disk_performance_level") {
request.SystemDiskPerformanceLevel = d.Get("system_disk_performance_level").(string)
d.SetPartial("system_disk_performance_level")
}
if d.HasChange("resource_group_id") {
request.ResourceGroupId = d.Get("resource_group_id").(string)
d.SetPartial("resource_group_id")
}
if d.HasChange("user_data") {
if v, ok := d.GetOk("user_data"); ok && v.(string) != "" {
_, base64DecodeError := base64.StdEncoding.DecodeString(v.(string))
if base64DecodeError == nil {
request.UserData = v.(string)
} else {
request.UserData = base64.StdEncoding.EncodeToString([]byte(v.(string)))
}
}
d.SetPartial("user_data")
}
if d.HasChange("role_name") {
request.RamRoleName = d.Get("role_name").(string)
d.SetPartial("role_name")
}
if d.HasChange("key_name") {
request.KeyPairName = d.Get("key_name").(string)
d.SetPartial("key_name")
}
if d.HasChange("instance_name") {
request.InstanceName = d.Get("instance_name").(string)
d.SetPartial("instance_name")
}
if d.HasChange("host_name") {
request.HostName = d.Get("host_name").(string)
d.SetPartial("host_name")
}
if d.HasChange("spot_strategy") {
request.SpotStrategy = d.Get("spot_strategy").(string)
d.SetPartial("spot_strategy")
}
if d.HasChange("spot_price_limit") {
v, ok := d.GetOk("spot_price_limit")
if ok {
spotPriceLimits := make([]ess.ModifyScalingConfigurationSpotPriceLimit, 0)
for _, e := range v.(*schema.Set).List() {
pack := e.(map[string]interface{})
l := ess.ModifyScalingConfigurationSpotPriceLimit{
InstanceType: pack["instance_type"].(string),
PriceLimit: strconv.FormatFloat(pack["price_limit"].(float64), 'f', 2, 64),
}
spotPriceLimits = append(spotPriceLimits, l)
}
request.SpotPriceLimit = &spotPriceLimits
}
d.SetPartial("spot_price_limit")
}
if d.HasChange("tags") {
if v, ok := d.GetOk("tags"); ok {
tags := "{"
for key, value := range v.(map[string]interface{}) {
tags += "\"" + key + "\"" + ":" + "\"" + value.(string) + "\"" + ","
}
request.Tags = strings.TrimSuffix(tags, ",") + "}"
}
d.SetPartial("tags")
}
if d.HasChange("data_disk") {
dds, ok := d.GetOk("data_disk")
if ok {
disks := dds.([]interface{})
createDataDisks := make([]ess.ModifyScalingConfigurationDataDisk, 0, len(disks))
for _, e := range disks {
pack := e.(map[string]interface{})
dataDisk := ess.ModifyScalingConfigurationDataDisk{
Size: strconv.Itoa(pack["size"].(int)),
Category: pack["category"].(string),
SnapshotId: pack["snapshot_id"].(string),
DeleteWithInstance: strconv.FormatBool(pack["delete_with_instance"].(bool)),
Device: pack["device"].(string),
Encrypted: strconv.FormatBool(pack["encrypted"].(bool)),
KMSKeyId: pack["kms_key_id"].(string),
DiskName: pack["name"].(string),
Description: pack["description"].(string),
AutoSnapshotPolicyId: pack["auto_snapshot_policy_id"].(string),
PerformanceLevel: pack["performance_level"].(string),
}
createDataDisks = append(createDataDisks, dataDisk)
}
request.DataDisk = &createDataDisks
}
d.SetPartial("data_disk")
}
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.ModifyScalingConfiguration(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}
func enableEssScalingConfiguration(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
if d.HasChange("enable") {
sgId := d.Get("scaling_group_id").(string)
group, err := essService.DescribeEssScalingGroup(sgId)
if err != nil {
return WrapError(err)
}
if d.Get("enable").(bool) {
if group.LifecycleState == string(Inactive) {
object, err := essService.DescribeEssScalingConfifurations(sgId)
if err != nil {
return WrapError(err)
}
activeConfig := ""
var csIds []string
for _, c := range object {
csIds = append(csIds, c.ScalingConfigurationId)
if c.LifecycleState == string(Active) {
activeConfig = c.ScalingConfigurationId
}
}
if activeConfig == "" {
return WrapError(Error("Please active a scaling configuration before enabling scaling group %s. Its all scaling configuration are %s.",
sgId, strings.Join(csIds, ",")))
}
request := ess.CreateEnableScalingGroupRequest()
request.RegionId = client.RegionId
request.ScalingGroupId = sgId
request.ActiveScalingConfigurationId = activeConfig
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.EnableScalingGroup(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
if err := essService.WaitForEssScalingGroup(sgId, Active, DefaultTimeout); err != nil {
return WrapError(err)
}
d.SetPartial("scaling_configuration_id")
}
} else {
if group.LifecycleState == string(Active) {
request := ess.CreateDisableScalingGroupRequest()
request.RegionId = client.RegionId
request.ScalingGroupId = sgId
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DisableScalingGroup(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
if err := essService.WaitForEssScalingGroup(sgId, Inactive, DefaultTimeout); err != nil {
return WrapError(err)
}
}
}
d.SetPartial("enable")
}
return nil
}
func resourceAliyunEssScalingConfigurationRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
if strings.Contains(d.Id(), COLON_SEPARATED) {
d.SetId(strings.Split(d.Id(), COLON_SEPARATED)[1])
}
object, err := essService.DescribeEssScalingConfiguration(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("scaling_group_id", object.ScalingGroupId)
d.Set("active", object.LifecycleState == string(Active))
d.Set("image_id", object.ImageId)
d.Set("image_name", object.ImageName)
d.Set("scaling_configuration_name", object.ScalingConfigurationName)
d.Set("internet_charge_type", object.InternetChargeType)
d.Set("internet_max_bandwidth_in", object.InternetMaxBandwidthIn)
d.Set("internet_max_bandwidth_out", object.InternetMaxBandwidthOut)
d.Set("credit_specification", object.CreditSpecification)
d.Set("system_disk_category", object.SystemDiskCategory)
d.Set("system_disk_size", object.SystemDiskSize)
d.Set("system_disk_name", object.SystemDiskName)
d.Set("system_disk_description", object.SystemDiskDescription)
d.Set("system_disk_auto_snapshot_policy_id", object.SystemDiskAutoSnapshotPolicyId)
d.Set("system_disk_performance_level", object.SystemDiskPerformanceLevel)
d.Set("data_disk", essService.flattenDataDiskMappings(object.DataDisks.DataDisk))
d.Set("role_name", object.RamRoleName)
d.Set("key_name", object.KeyPairName)
d.Set("force_delete", d.Get("force_delete").(bool))
d.Set("tags", essTagsToMap(object.Tags.Tag))
d.Set("instance_name", object.InstanceName)
d.Set("override", d.Get("override").(bool))
d.Set("password_inherit", object.PasswordInherit)
d.Set("resource_group_id", object.ResourceGroupId)
d.Set("host_name", object.HostName)
d.Set("spot_strategy", object.SpotStrategy)
d.Set("spot_price_limit", essService.flattenSpotPriceLimitMappings(object.SpotPriceLimit.SpotPriceModel))
if sg, ok := d.GetOk("security_group_id"); ok && sg.(string) != "" {
d.Set("security_group_id", object.SecurityGroupId)
}
if sgs, ok := d.GetOk("security_group_ids"); ok && len(sgs.([]interface{})) > 0 {
d.Set("security_group_ids", object.SecurityGroupIds.SecurityGroupId)
}
if instanceType, ok := d.GetOk("instance_type"); ok && instanceType.(string) != "" {
d.Set("instance_type", object.InstanceType)
}
if instanceTypes, ok := d.GetOk("instance_types"); ok && len(instanceTypes.([]interface{})) > 0 {
d.Set("instance_types", object.InstanceTypes.InstanceType)
}
userData := d.Get("user_data")
if userData.(string) != "" {
_, base64DecodeError := base64.StdEncoding.DecodeString(userData.(string))
if base64DecodeError == nil {
d.Set("user_data", object.UserData)
} else {
d.Set("user_data", userDataHashSum(object.UserData))
}
} else {
d.Set("user_data", userDataHashSum(object.UserData))
}
return nil
}
func resourceAliyunEssScalingConfigurationDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
if strings.Contains(d.Id(), COLON_SEPARATED) {
d.SetId(strings.Split(d.Id(), COLON_SEPARATED)[1])
}
object, err := essService.DescribeEssScalingConfiguration(d.Id())
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
request := ess.CreateDescribeScalingConfigurationsRequest()
request.RegionId = client.RegionId
request.ScalingGroupId = object.ScalingGroupId
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DescribeScalingConfigurations(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ess.DescribeScalingConfigurationsResponse)
if len(response.ScalingConfigurations.ScalingConfiguration) < 1 {
return nil
} else if len(response.ScalingConfigurations.ScalingConfiguration) == 1 {
if d.Get("force_delete").(bool) {
request := ess.CreateDeleteScalingGroupRequest()
request.ScalingGroupId = object.ScalingGroupId
request.ForceDelete = requests.NewBoolean(true)
request.RegionId = client.RegionId
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DeleteScalingGroup(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidScalingGroupId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(essService.WaitForEssScalingGroup(d.Id(), Deleted, DefaultTimeout))
}
return WrapError(Error("Current scaling configuration %s is the last configuration for the scaling group %s. Please launch a new "+
"active scaling configuration or set 'force_delete' to 'true' to delete it with deleting its scaling group.", d.Id(), object.ScalingGroupId))
}
deleteScalingConfigurationRequest := ess.CreateDeleteScalingConfigurationRequest()
deleteScalingConfigurationRequest.ScalingConfigurationId = d.Id()
rawDeleteScalingConfiguration, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DeleteScalingConfiguration(deleteScalingConfigurationRequest)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidScalingGroupId.NotFound", "InvalidScalingConfigurationId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), rawDeleteScalingConfiguration, request.RpcRequest, request)
return WrapError(essService.WaitForScalingConfiguration(d.Id(), Deleted, DefaultTimeout))
}
func buildAlicloudEssScalingConfigurationArgs(d *schema.ResourceData, meta interface{}) (*ess.CreateScalingConfigurationRequest, error) {
client := meta.(*connectivity.AliyunClient)
//ecsService := EcsService{client}
//zoneId, validZones, _, err := ecsService.DescribeAvailableResources(d, meta, InstanceTypeResource)
//if err != nil {
// return nil, WrapError(err)
//}
request := ess.CreateCreateScalingConfigurationRequest()
request.RegionId = client.RegionId
request.ScalingGroupId = d.Get("scaling_group_id").(string)
request.ImageId = d.Get("image_id").(string)
request.SecurityGroupId = d.Get("security_group_id").(string)
request.PasswordInherit = requests.NewBoolean(d.Get("password_inherit").(bool))
securityGroupId := d.Get("security_group_id").(string)
securityGroupIds := d.Get("security_group_ids").([]interface{})
password := d.Get("password").(string)
kmsPassword := d.Get("kms_encrypted_password").(string)
if password != "" {
request.Password = password
} else if kmsPassword != "" {
kmsService := KmsService{client}
decryptResp, err := kmsService.Decrypt(kmsPassword, d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return nil, WrapError(err)
}
request.Password = decryptResp
}
if securityGroupId == "" && (securityGroupIds == nil || len(securityGroupIds) == 0) {
return nil, WrapError(Error("security_group_id or security_group_ids must be assigned"))
}
if securityGroupIds != nil && len(securityGroupIds) > 0 {
sgs := expandStringList(securityGroupIds)
request.SecurityGroupIds = &sgs
}
if securityGroupId != "" {
request.SecurityGroupId = securityGroupId
}
types := make([]string, 0, int(MaxScalingConfigurationInstanceTypes))
instanceType := d.Get("instance_type").(string)
instanceTypes := d.Get("instance_types").([]interface{})
if instanceType == "" && (instanceTypes == nil || len(instanceTypes) == 0) {
return nil, WrapError(Error("instance_type or instance_types must be assigned"))
}
if instanceTypes != nil && len(instanceTypes) > 0 {
types = expandStringList(instanceTypes)
}
if instanceType != "" {
types = append(types, instanceType)
}
//for _, v := range types {
// if err := ecsService.InstanceTypeValidation(v, zoneId, validZones); err != nil {
// return nil, WrapError(err)
// }
//}
request.InstanceTypes = &types
if v := d.Get("scaling_configuration_name").(string); v != "" {
request.ScalingConfigurationName = v
}
if v := d.Get("image_name").(string); v != "" {
request.ImageName = v
}
if v := d.Get("internet_charge_type").(string); v != "" {
request.InternetChargeType = v
}
if v := d.Get("internet_max_bandwidth_in").(int); v != 0 {
request.InternetMaxBandwidthIn = requests.NewInteger(v)
}
request.InternetMaxBandwidthOut = requests.NewInteger(d.Get("internet_max_bandwidth_out").(int))
if v := d.Get("credit_specification").(string); v != "" {
request.CreditSpecification = v
}
if v := d.Get("system_disk_category").(string); v != "" {
request.SystemDiskCategory = v
}
if v := d.Get("system_disk_size").(int); v != 0 {
request.SystemDiskSize = requests.NewInteger(v)
}
if v := d.Get("system_disk_name").(string); v != "" {
request.SystemDiskDiskName = v
}
if v := d.Get("system_disk_description").(string); v != "" {
request.SystemDiskDescription = v
}
if v := d.Get("system_disk_auto_snapshot_policy_id").(string); v != "" {
request.SystemDiskAutoSnapshotPolicyId = v
}
if v := d.Get("system_disk_performance_level").(string); v != "" {
request.SystemDiskPerformanceLevel = v
}
if v := d.Get("resource_group_id").(string); v != "" {
request.ResourceGroupId = v
}
dds, ok := d.GetOk("data_disk")
if ok {
disks := dds.([]interface{})
createDataDisks := make([]ess.CreateScalingConfigurationDataDisk, 0, len(disks))
for _, e := range disks {
pack := e.(map[string]interface{})
dataDisk := ess.CreateScalingConfigurationDataDisk{
Size: strconv.Itoa(pack["size"].(int)),
Category: pack["category"].(string),
SnapshotId: pack["snapshot_id"].(string),
DeleteWithInstance: strconv.FormatBool(pack["delete_with_instance"].(bool)),
Device: pack["device"].(string),
Encrypted: strconv.FormatBool(pack["encrypted"].(bool)),
KMSKeyId: pack["kms_key_id"].(string),
DiskName: pack["name"].(string),
Description: pack["description"].(string),
AutoSnapshotPolicyId: pack["auto_snapshot_policy_id"].(string),
PerformanceLevel: pack["performance_level"].(string),
}
createDataDisks = append(createDataDisks, dataDisk)
}
request.DataDisk = &createDataDisks
}
if v, ok := d.GetOk("role_name"); ok && v.(string) != "" {
request.RamRoleName = v.(string)
}
if v, ok := d.GetOk("key_name"); ok && v.(string) != "" {
request.KeyPairName = v.(string)
}
if v, ok := d.GetOk("user_data"); ok && v.(string) != "" {
_, base64DecodeError := base64.StdEncoding.DecodeString(v.(string))
if base64DecodeError == nil {
request.UserData = v.(string)
} else {
request.UserData = base64.StdEncoding.EncodeToString([]byte(v.(string)))
}
}
if v, ok := d.GetOk("tags"); ok {
tags := "{"
for key, value := range v.(map[string]interface{}) {
tags += "\"" + key + "\"" + ":" + "\"" + value.(string) + "\"" + ","
}
request.Tags = strings.TrimSuffix(tags, ",") + "}"
}
if v, ok := d.GetOk("instance_name"); ok && v.(string) != "" {
request.InstanceName = v.(string)
}
if v, ok := d.GetOk("host_name"); ok && v.(string) != "" {
request.HostName = v.(string)
}
if v, ok := d.GetOk("spot_strategy"); ok && v.(string) != "" {
request.SpotStrategy = v.(string)
}
v, ok := d.GetOk("spot_price_limit")
if ok {
spotPriceLimits := make([]ess.CreateScalingConfigurationSpotPriceLimit, 0)
for _, e := range v.(*schema.Set).List() {
pack := e.(map[string]interface{})
l := ess.CreateScalingConfigurationSpotPriceLimit{
InstanceType: pack["instance_type"].(string),
PriceLimit: strconv.FormatFloat(pack["price_limit"].(float64), 'f', 2, 64),
}
spotPriceLimits = append(spotPriceLimits, l)
}
request.SpotPriceLimit = &spotPriceLimits
}
return request, nil
}
func activeSubstituteScalingConfiguration(d *schema.ResourceData, meta interface{}) (configures []ess.ScalingConfiguration, err error) {
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
substituteId, ok := d.GetOk("substitute")
c, err := essService.DescribeEssScalingConfiguration(d.Id())
if err != nil {
err = WrapError(err)
return
}
request := ess.CreateDescribeScalingConfigurationsRequest()
request.RegionId = client.RegionId
request.ScalingGroupId = c.ScalingGroupId
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DescribeScalingConfigurations(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ess.DescribeScalingConfigurationsResponse)
if len(response.ScalingConfigurations.ScalingConfiguration) < 1 {
return
}
if !ok || substituteId.(string) == "" {
if len(response.ScalingConfigurations.ScalingConfiguration) == 1 {
return configures, WrapError(Error("Current scaling configuration %s is the last configuration for the scaling group %s, and it can't be inactive.", d.Id(), c.ScalingGroupId))
}
var configs []string
for _, cc := range response.ScalingConfigurations.ScalingConfiguration {
if cc.ScalingConfigurationId != d.Id() {
configs = append(configs, cc.ScalingConfigurationId)
}
}
return configures, WrapError(Error("Before inactivating current scaling configuration, you must select a substitute for scaling group from: %s.", strings.Join(configs, ",")))
}
err = essService.ActiveEssScalingConfiguration(c.ScalingGroupId, substituteId.(string))
if err != nil {
return configures, WrapError(Error("Inactive scaling configuration %s err: %#v. Substitute scaling configuration ID: %s",
d.Id(), err, substituteId.(string)))
}
return response.ScalingConfigurations.ScalingConfiguration, nil
}
package alicloud
import (
"fmt"
"math"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"reflect"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ess"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEssScalingGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunEssScalingGroupCreate,
Read: resourceAliyunEssScalingGroupRead,
Update: resourceAliyunEssScalingGroupUpdate,
Delete: resourceAliyunEssScalingGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"min_size": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(0, 1000),
},
"max_size": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(0, 1000),
},
"desired_capacity": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(0, 1000),
},
"scaling_group_name": {
Type: schema.TypeString,
Optional: true,
},
"default_cooldown": {
Type: schema.TypeInt,
Default: 300,
Optional: true,
ValidateFunc: validation.IntBetween(0, 86400),
},
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
Deprecated: "Field 'vswitch_id' has been deprecated from provider version 1.7.1, and new field 'vswitch_ids' can replace it.",
},
"vswitch_ids": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
MinItems: 1,
},
"removal_policies": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
Computed: true,
MaxItems: 2,
MinItems: 1,
},
"db_instance_ids": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
MinItems: 0,
},
"loadbalancer_ids": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
MinItems: 0,
},
"multi_az_policy": {
Type: schema.TypeString,
Optional: true,
Default: "PRIORITY",
ValidateFunc: validation.StringInSlice([]string{"PRIORITY", "BALANCE", "COST_OPTIMIZED"}, false),
ForceNew: true,
},
"on_demand_base_capacity": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(0, 1000),
},
"on_demand_percentage_above_base_capacity": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(0, 100),
},
"spot_instance_pools": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(0, 10),
},
"spot_instance_remedy": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"group_deletion_protection": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"launch_template_id": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAliyunEssScalingGroupCreate(d *schema.ResourceData, meta interface{}) error {
request, err := buildAlicloudEssScalingGroupArgs(d, meta)
if err != nil {
return WrapError(err)
}
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
if err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.CreateScalingGroup(request)
})
if err != nil {
if IsExpectedErrors(err, []string{Throttling, "IncorrectLoadBalancerHealthCheck", "IncorrectLoadBalancerStatus"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ess.CreateScalingGroupResponse)
d.SetId(response.ScalingGroupId)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ess_scalinggroup", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
if err := essService.WaitForEssScalingGroup(d.Id(), Inactive, DefaultTimeout); err != nil {
return WrapError(err)
}
return resourceAliyunEssScalingGroupUpdate(d, meta)
}
func resourceAliyunEssScalingGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
object, err := essService.DescribeEssScalingGroup(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("min_size", object.MinSize)
d.Set("max_size", object.MaxSize)
d.Set("desired_capacity", object.DesiredCapacity)
d.Set("scaling_group_name", object.ScalingGroupName)
d.Set("default_cooldown", object.DefaultCooldown)
d.Set("multi_az_policy", object.MultiAZPolicy)
d.Set("on_demand_base_capacity", object.OnDemandBaseCapacity)
d.Set("on_demand_percentage_above_base_capacity", object.OnDemandPercentageAboveBaseCapacity)
d.Set("spot_instance_pools", object.SpotInstancePools)
d.Set("spot_instance_remedy", object.SpotInstanceRemedy)
d.Set("group_deletion_protection", object.GroupDeletionProtection)
var polices []string
if len(object.RemovalPolicies.RemovalPolicy) > 0 {
for _, v := range object.RemovalPolicies.RemovalPolicy {
polices = append(polices, v)
}
}
d.Set("removal_policies", polices)
var dbIds []string
if len(object.DBInstanceIds.DBInstanceId) > 0 {
for _, v := range object.DBInstanceIds.DBInstanceId {
dbIds = append(dbIds, v)
}
}
d.Set("db_instance_ids", dbIds)
var slbIds []string
if len(object.LoadBalancerIds.LoadBalancerId) > 0 {
for _, v := range object.LoadBalancerIds.LoadBalancerId {
slbIds = append(slbIds, v)
}
}
d.Set("loadbalancer_ids", slbIds)
var vswitchIds []string
if len(object.VSwitchIds.VSwitchId) > 0 {
for _, v := range object.VSwitchIds.VSwitchId {
vswitchIds = append(vswitchIds, v)
}
}
d.Set("vswitch_ids", vswitchIds)
d.Set("launch_template_id", object.LaunchTemplateId)
return nil
}
func resourceAliyunEssScalingGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ess.CreateModifyScalingGroupRequest()
request.RegionId = client.RegionId
request.ScalingGroupId = d.Id()
d.Partial(true)
if d.HasChange("scaling_group_name") {
request.ScalingGroupName = d.Get("scaling_group_name").(string)
}
if d.HasChange("min_size") {
request.MinSize = requests.NewInteger(d.Get("min_size").(int))
}
if d.HasChange("max_size") {
request.MaxSize = requests.NewInteger(d.Get("max_size").(int))
}
if d.HasChange("desired_capacity") {
request.DesiredCapacity = requests.NewInteger(d.Get("desired_capacity").(int))
}
if d.HasChange("default_cooldown") {
request.DefaultCooldown = requests.NewInteger(d.Get("default_cooldown").(int))
}
if d.HasChange("vswitch_ids") {
vSwitchIds := expandStringList(d.Get("vswitch_ids").(*schema.Set).List())
request.VSwitchIds = &vSwitchIds
}
if d.HasChange("removal_policies") {
policyies := expandStringList(d.Get("removal_policies").([]interface{}))
s := reflect.ValueOf(request).Elem()
for i, p := range policyies {
s.FieldByName(fmt.Sprintf("RemovalPolicy%d", i+1)).Set(reflect.ValueOf(p))
}
}
if d.HasChange("on_demand_base_capacity") {
request.OnDemandBaseCapacity = requests.NewInteger(d.Get("on_demand_base_capacity").(int))
}
if d.HasChange("on_demand_percentage_above_base_capacity") {
request.OnDemandPercentageAboveBaseCapacity = requests.NewInteger(d.Get("on_demand_percentage_above_base_capacity").(int))
}
if d.HasChange("spot_instance_pools") {
request.SpotInstancePools = requests.NewInteger(d.Get("spot_instance_pools").(int))
}
if d.HasChange("spot_instance_remedy") {
request.SpotInstanceRemedy = requests.NewBoolean(d.Get("spot_instance_remedy").(bool))
}
if d.HasChange("group_deletion_protection") {
request.GroupDeletionProtection = requests.NewBoolean(d.Get("group_deletion_protection").(bool))
}
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.ModifyScalingGroup(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("scaling_group_name")
d.SetPartial("min_size")
d.SetPartial("max_size")
d.SetPartial("desired_capacity")
d.SetPartial("default_cooldown")
d.SetPartial("vswitch_ids")
d.SetPartial("removal_policies")
d.SetPartial("on_demand_base_capacity")
d.SetPartial("on_demand_percentage_above_base_capacity")
d.SetPartial("spot_instance_pools")
d.SetPartial("spot_instance_remedy")
d.SetPartial("group_deletion_protection")
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
if d.HasChange("loadbalancer_ids") {
oldLoadbalancers, newLoadbalancers := d.GetChange("loadbalancer_ids")
err = attachOrDetachLoadbalancers(d, client, oldLoadbalancers.(*schema.Set), newLoadbalancers.(*schema.Set))
if err != nil {
return WrapError(err)
}
d.SetPartial("loadbalancer_ids")
}
if d.HasChange("db_instance_ids") {
oldDbInstanceIds, newDbInstanceIds := d.GetChange("db_instance_ids")
err = attachOrDetachDbInstances(d, client, oldDbInstanceIds.(*schema.Set), newDbInstanceIds.(*schema.Set))
if err != nil {
return WrapError(err)
}
d.SetPartial("db_instance_ids")
}
d.Partial(false)
return resourceAliyunEssScalingGroupRead(d, meta)
}
func resourceAliyunEssScalingGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
request := ess.CreateDeleteScalingGroupRequest()
request.RegionId = client.RegionId
request.ScalingGroupId = d.Id()
request.ForceDelete = requests.NewBoolean(true)
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DeleteScalingGroup(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidScalingGroupId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(essService.WaitForEssScalingGroup(d.Id(), Deleted, DefaultTimeout))
}
func buildAlicloudEssScalingGroupArgs(d *schema.ResourceData, meta interface{}) (*ess.CreateScalingGroupRequest, error) {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
request := ess.CreateCreateScalingGroupRequest()
request.RegionId = client.RegionId
request.MinSize = requests.NewInteger(d.Get("min_size").(int))
request.MaxSize = requests.NewInteger(d.Get("max_size").(int))
request.DefaultCooldown = requests.NewInteger(d.Get("default_cooldown").(int))
if v, ok := d.GetOk("scaling_group_name"); ok && v.(string) != "" {
request.ScalingGroupName = v.(string)
}
if v, ok := d.GetOk("desired_capacity"); ok {
request.DesiredCapacity = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("vswitch_ids"); ok {
ids := expandStringList(v.(*schema.Set).List())
request.VSwitchIds = &ids
}
if dbs, ok := d.GetOk("db_instance_ids"); ok {
request.DBInstanceIds = convertListToJsonString(dbs.(*schema.Set).List())
}
if lbs, ok := d.GetOk("loadbalancer_ids"); ok {
for _, lb := range lbs.(*schema.Set).List() {
if err := slbService.WaitForSlb(lb.(string), Active, DefaultTimeout); err != nil {
return nil, WrapError(err)
}
}
request.LoadBalancerIds = convertListToJsonString(lbs.(*schema.Set).List())
}
if v, ok := d.GetOk("multi_az_policy"); ok && v.(string) != "" {
request.MultiAZPolicy = v.(string)
}
if v, ok := d.GetOk("on_demand_base_capacity"); ok {
request.OnDemandBaseCapacity = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("on_demand_percentage_above_base_capacity"); ok {
request.OnDemandPercentageAboveBaseCapacity = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("spot_instance_pools"); ok {
request.SpotInstancePools = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("spot_instance_remedy"); ok {
request.SpotInstanceRemedy = requests.NewBoolean(v.(bool))
}
if v, ok := d.GetOk("group_deletion_protection"); ok {
request.GroupDeletionProtection = requests.NewBoolean(v.(bool))
}
if v, ok := d.GetOk("launch_template_id"); ok {
request.LaunchTemplateId = v.(string)
}
return request, nil
}
func attachOrDetachLoadbalancers(d *schema.ResourceData, client *connectivity.AliyunClient, oldLoadbalancerSet *schema.Set, newLoadbalancerSet *schema.Set) error {
detachLoadbalancerSet := oldLoadbalancerSet.Difference(newLoadbalancerSet)
attachLoadbalancerSet := newLoadbalancerSet.Difference(oldLoadbalancerSet)
// attach
if attachLoadbalancerSet.Len() > 0 {
var subLists = partition(attachLoadbalancerSet, int(AttachDetachLoadbalancersBatchsize))
for _, subList := range subLists {
attachLoadbalancersRequest := ess.CreateAttachLoadBalancersRequest()
attachLoadbalancersRequest.RegionId = client.RegionId
attachLoadbalancersRequest.ScalingGroupId = d.Id()
attachLoadbalancersRequest.ForceAttach = requests.NewBoolean(true)
attachLoadbalancersRequest.LoadBalancer = &subList
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.AttachLoadBalancers(attachLoadbalancersRequest)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), attachLoadbalancersRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(attachLoadbalancersRequest.GetActionName(), raw, attachLoadbalancersRequest.RpcRequest, attachLoadbalancersRequest)
}
}
// detach
if detachLoadbalancerSet.Len() > 0 {
var subLists = partition(detachLoadbalancerSet, int(AttachDetachLoadbalancersBatchsize))
for _, subList := range subLists {
detachLoadbalancersRequest := ess.CreateDetachLoadBalancersRequest()
detachLoadbalancersRequest.RegionId = client.RegionId
detachLoadbalancersRequest.ScalingGroupId = d.Id()
detachLoadbalancersRequest.ForceDetach = requests.NewBoolean(false)
detachLoadbalancersRequest.LoadBalancer = &subList
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DetachLoadBalancers(detachLoadbalancersRequest)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), detachLoadbalancersRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(detachLoadbalancersRequest.GetActionName(), raw, detachLoadbalancersRequest.RpcRequest, detachLoadbalancersRequest)
}
}
return nil
}
func attachOrDetachDbInstances(d *schema.ResourceData, client *connectivity.AliyunClient, oldDbInstanceIdSet *schema.Set, newDbInstanceIdSet *schema.Set) error {
detachDbInstanceSet := oldDbInstanceIdSet.Difference(newDbInstanceIdSet)
attachDbInstanceSet := newDbInstanceIdSet.Difference(oldDbInstanceIdSet)
// attach
if attachDbInstanceSet.Len() > 0 {
var subLists = partition(attachDbInstanceSet, int(AttachDetachDbinstancesBatchsize))
for _, subList := range subLists {
attachDbInstancesRequest := ess.CreateAttachDBInstancesRequest()
attachDbInstancesRequest.RegionId = client.RegionId
attachDbInstancesRequest.ScalingGroupId = d.Id()
attachDbInstancesRequest.ForceAttach = requests.NewBoolean(true)
attachDbInstancesRequest.DBInstance = &subList
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.AttachDBInstances(attachDbInstancesRequest)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), attachDbInstancesRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(attachDbInstancesRequest.GetActionName(), raw, attachDbInstancesRequest.RpcRequest, attachDbInstancesRequest)
}
}
// detach
if detachDbInstanceSet.Len() > 0 {
var subLists = partition(detachDbInstanceSet, int(AttachDetachDbinstancesBatchsize))
for _, subList := range subLists {
detachDbInstancesRequest := ess.CreateDetachDBInstancesRequest()
detachDbInstancesRequest.RegionId = client.RegionId
detachDbInstancesRequest.ScalingGroupId = d.Id()
detachDbInstancesRequest.ForceDetach = requests.NewBoolean(true)
detachDbInstancesRequest.DBInstance = &subList
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DetachDBInstances(detachDbInstancesRequest)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), detachDbInstancesRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(detachDbInstancesRequest.GetActionName(), raw, detachDbInstancesRequest.RpcRequest, detachDbInstancesRequest)
}
}
return nil
}
func partition(instanceIds *schema.Set, batchSize int) [][]string {
var res [][]string
size := instanceIds.Len()
batchCount := int(math.Ceil(float64(size) / float64(batchSize)))
idList := expandStringList(instanceIds.List())
for i := 1; i <= batchCount; i++ {
fromIndex := batchSize * (i - 1)
toIndex := int(math.Min(float64(batchSize*i), float64(size)))
subList := idList[fromIndex:toIndex]
res = append(res, subList)
}
return res
}
package alicloud
import (
"bytes"
"fmt"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/helper/hashcode"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ess"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEssScalingGroupVserverGroups() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunEssVserverGroupsCreate,
Read: resourceAliyunEssVserverGroupsRead,
Update: resourceAliyunEssVserverGroupsUpdate,
Delete: resourceAliyunEssVserverGroupsDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"scaling_group_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"vserver_groups": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"loadbalancer_id": {
Type: schema.TypeString,
Required: true,
},
"vserver_attributes": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"vserver_group_id": {
Type: schema.TypeString,
Required: true,
},
"port": {
Type: schema.TypeInt,
Required: true,
},
"weight": {
Type: schema.TypeInt,
Required: true,
},
},
},
Set: func(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
if v, ok := m["vserver_group_id"]; ok {
buf.WriteString(fmt.Sprintf("%s-", v.(string)))
}
if v, ok := m["port"]; ok {
buf.WriteString(fmt.Sprintf("%d-", v.(int)))
}
return hashcode.String(buf.String())
},
},
},
},
},
"force": {
Type: schema.TypeBool,
Optional: true,
Default: true,
DiffSuppressFunc: func(k, old string, new string, d *schema.ResourceData) bool {
return old == "" && new == "true" && d.Id() != ""
},
},
},
}
}
func resourceAliyunEssVserverGroupsCreate(d *schema.ResourceData, meta interface{}) error {
d.SetId(d.Get("scaling_group_id").(string))
return resourceAliyunEssVserverGroupsUpdate(d, meta)
}
func resourceAliyunEssVserverGroupsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
object, err := essService.DescribeEssScalingGroup(d.Id())
if err != nil {
return WrapError(err)
}
err = d.Set("scaling_group_id", object.ScalingGroupId)
if err != nil {
return WrapError(err)
}
err = d.Set("vserver_groups", essService.flattenVserverGroupList(object.VServerGroups.VServerGroup))
if err != nil {
return WrapError(err)
}
return nil
}
func resourceAliyunEssVserverGroupsUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
object, err := essService.DescribeEssScalingGroup(d.Id())
if err != nil {
return WrapError(err)
}
d.Partial(true)
vserverGroupsMapFromScalingGroup := vserverGroupMapFromScalingGroup(object.VServerGroups.VServerGroup)
vserverGroupsMapFromConfig := vserverGroupMapFromConfig(d.Get("vserver_groups").(*schema.Set))
err = vserverGroupMapPreCheckLb(vserverGroupsMapFromConfig, meta.(*connectivity.AliyunClient))
if err != nil {
return WrapError(err)
}
attachMap, detachMap := attachOrDetachVserverGroupMap(vserverGroupsMapFromConfig, vserverGroupsMapFromScalingGroup)
v, ok := d.GetOkExists("force")
force := true
if ok {
force = v.(bool)
}
err = detachVserverGroups(d, client, detachMap, force)
if err != nil {
return WrapError(err)
}
d.SetPartial("vserver_groups")
err = attachVserverGroups(d, client, attachMap, force)
if err != nil {
return WrapError(err)
}
d.SetPartial("vserver_groups")
d.Partial(false)
return resourceAliyunEssVserverGroupsRead(d, meta)
}
func resourceAliyunEssVserverGroupsDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vserverGroupsFromConfig := vserverGroupMapFromConfig(d.Get("vserver_groups").(*schema.Set))
_, detachMap := attachOrDetachVserverGroupMap(make(map[string]string, 0), vserverGroupsFromConfig)
v, ok := d.GetOkExists("force")
force := true
if ok {
force = v.(bool)
}
err := detachVserverGroups(d, client, detachMap, force)
if err != nil {
return WrapError(err)
}
return nil
}
func vserverGroupMapFromScalingGroup(vServerGroups []ess.VServerGroup) map[string]string {
vserverGroupMap := make(map[string]string)
if vServerGroups != nil && len(vServerGroups) > 0 {
for _, v := range vServerGroups {
vserverGroupAttributes := v.VServerGroupAttributes.VServerGroupAttribute
for _, a := range vserverGroupAttributes {
key := fmt.Sprintf("%s_%s_%d_%d", v.LoadBalancerId, a.VServerGroupId, a.Port, a.Weight)
vserverGroupMap[key] = key
}
}
}
return vserverGroupMap
}
func vserverGroupMapFromConfig(vserverGroups *schema.Set) map[string]string {
vserverGroupMap := make(map[string]string)
vserverGroupList := vserverGroups.List()
if len(vserverGroupList) > 0 {
for _, v := range vserverGroupList {
vserverGroup := v.(map[string]interface{})
loadBalancerId := vserverGroup["loadbalancer_id"].(string)
attrs := vserverGroup["vserver_attributes"].(*schema.Set).List()
for _, e := range attrs {
vserverAttribute := e.(map[string]interface{})
vserverGroupId := vserverAttribute["vserver_group_id"].(string)
port := vserverAttribute["port"].(int)
weight := vserverAttribute["weight"].(int)
key := fmt.Sprintf("%s_%s_%d_%d", loadBalancerId, vserverGroupId, port, weight)
vserverGroupMap[key] = key
}
}
}
return vserverGroupMap
}
func attachOrDetachVserverGroupMap(newMap map[string]string, oldMap map[string]string) (map[string]string, map[string]string) {
attachMap := make(map[string]string)
detachMap := make(map[string]string)
for k, v := range newMap {
if _, ok := oldMap[k]; !ok {
attachMap[k] = v
}
}
for k, v := range oldMap {
if _, ok := newMap[k]; !ok {
detachMap[k] = v
}
}
return attachMap, detachMap
}
func buildEssVserverGroupListMap(vserverGroupMap map[string]string) map[string][]string {
vserverGroupRequestMap := make(map[string][]string, 0)
for _, v := range vserverGroupMap {
attrs := strings.Split(v, "_")
loadbalancerId := attrs[0]
if _, ok := vserverGroupRequestMap[loadbalancerId]; !ok {
vserverGroupAttributes := make([]string, 0)
vserverGroupAttributes = append(vserverGroupAttributes, v)
vserverGroupRequestMap[loadbalancerId] = vserverGroupAttributes
} else {
vserverGroupAttributes := vserverGroupRequestMap[loadbalancerId]
vserverGroupAttributes = append(vserverGroupAttributes, v)
vserverGroupRequestMap[loadbalancerId] = vserverGroupAttributes
}
}
return vserverGroupRequestMap
}
func attachVserverGroups(d *schema.ResourceData, client *connectivity.AliyunClient, attachMap map[string]string, force bool) error {
if len(attachMap) > 0 {
vserverGroupListMap := buildEssVserverGroupListMap(attachMap)
attachScalingGroupVserverGroups := make([]ess.AttachVServerGroupsVServerGroup, 0)
for k, v := range vserverGroupListMap {
vserverAttributes := make([]ess.AttachVServerGroupsVServerGroupAttribute, 0)
for _, e := range v {
attrs := strings.Split(e, "_")
vserverAttribute := ess.AttachVServerGroupsVServerGroupAttribute{
VServerGroupId: attrs[1],
Port: attrs[2],
Weight: attrs[3],
}
vserverAttributes = append(vserverAttributes, vserverAttribute)
}
vserverGroup := ess.AttachVServerGroupsVServerGroup{
LoadBalancerId: k,
VServerGroupAttribute: &vserverAttributes,
}
attachScalingGroupVserverGroups = append(attachScalingGroupVserverGroups, vserverGroup)
}
request := ess.CreateAttachVServerGroupsRequest()
request.RegionId = client.RegionId
request.ScalingGroupId = d.Id()
request.ForceAttach = requests.NewBoolean(force)
request.VServerGroup = &attachScalingGroupVserverGroups
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.AttachVServerGroups(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
return nil
}
func detachVserverGroups(d *schema.ResourceData, client *connectivity.AliyunClient, detachMap map[string]string, force bool) error {
if len(detachMap) > 0 {
vserverGroupListMap := buildEssVserverGroupListMap(detachMap)
detachScalingGroupVserverGroups := make([]ess.DetachVServerGroupsVServerGroup, 0)
for k, v := range vserverGroupListMap {
vserverAttributes := make([]ess.DetachVServerGroupsVServerGroupAttribute, 0)
for _, e := range v {
attrs := strings.Split(e, "_")
vserverAttribute := ess.DetachVServerGroupsVServerGroupAttribute{
VServerGroupId: attrs[1],
Port: attrs[2],
}
vserverAttributes = append(vserverAttributes, vserverAttribute)
}
vserverGroup := ess.DetachVServerGroupsVServerGroup{
LoadBalancerId: k,
VServerGroupAttribute: &vserverAttributes,
}
detachScalingGroupVserverGroups = append(detachScalingGroupVserverGroups, vserverGroup)
}
request := ess.CreateDetachVServerGroupsRequest()
request.RegionId = client.RegionId
request.ScalingGroupId = d.Id()
request.ForceDetach = requests.NewBoolean(force)
request.VServerGroup = &detachScalingGroupVserverGroups
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DetachVServerGroups(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
return nil
}
func vserverGroupMapPreCheckLb(vserverGroupsMapFromConfig map[string]string, client *connectivity.AliyunClient) error {
slbService := SlbService{client}
for _, v := range vserverGroupsMapFromConfig {
attrs := strings.Split(v, "_")
loadbalancerID := attrs[0]
if err := slbService.WaitForSlb(loadbalancerID, Active, DefaultTimeout); err != nil {
return WrapError(err)
}
}
return nil
}
package alicloud
import (
"strconv"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ess"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEssScalingRule() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunEssScalingRuleCreate,
Read: resourceAliyunEssScalingRuleRead,
Update: resourceAliyunEssScalingRuleUpdate,
Delete: resourceAliyunEssScalingRuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"scaling_group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"adjustment_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"QuantityChangeInCapacity", "PercentChangeInCapacity", "TotalCapacity"}, false),
},
"adjustment_value": {
Type: schema.TypeInt,
Optional: true,
},
"scaling_rule_name": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"ari": {
Type: schema.TypeString,
Computed: true,
},
"cooldown": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(0, 86400),
},
"scaling_rule_type": {
Type: schema.TypeString,
Optional: true,
Default: "SimpleScalingRule",
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
string(SimpleScalingRule),
string(TargetTrackingScalingRule),
string(StepScalingRule),
}, false),
},
"estimated_instance_warmup": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"metric_name": {
Type: schema.TypeString,
Optional: true,
},
"target_value": {
Type: schema.TypeFloat,
Optional: true,
},
"disable_scale_in": {
Type: schema.TypeBool,
Optional: true,
},
"step_adjustment": {
Type: schema.TypeList,
Optional: true,
MinItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"metric_interval_lower_bound": {
Type: schema.TypeString,
Optional: true,
},
"metric_interval_upper_bound": {
Type: schema.TypeString,
Optional: true,
},
"scaling_adjustment": {
Type: schema.TypeInt,
Optional: true,
},
},
},
},
},
}
}
func resourceAliyunEssScalingRuleCreate(d *schema.ResourceData, meta interface{}) error {
request, err := buildAlicloudEssScalingRuleArgs(d, meta)
if err != nil {
return WrapError(err)
}
client := meta.(*connectivity.AliyunClient)
request.RegionId = client.RegionId
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.CreateScalingRule(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ess_scalingrule", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ess.CreateScalingRuleResponse)
d.SetId(response.ScalingRuleId)
return resourceAliyunEssScalingRuleRead(d, meta)
}
func resourceAliyunEssScalingRuleRead(d *schema.ResourceData, meta interface{}) error {
//Compatible with older versions id
if strings.Contains(d.Id(), COLON_SEPARATED) {
parts, _ := ParseResourceId(d.Id(), 2)
d.SetId(parts[1])
}
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
object, err := essService.DescribeEssScalingRule(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("scaling_group_id", object.ScalingGroupId)
d.Set("ari", object.ScalingRuleAri)
d.Set("adjustment_type", object.AdjustmentType)
d.Set("adjustment_value", object.AdjustmentValue)
d.Set("scaling_rule_name", object.ScalingRuleName)
d.Set("cooldown", object.Cooldown)
d.Set("scaling_rule_type", object.ScalingRuleType)
d.Set("estimated_instance_warmup", object.EstimatedInstanceWarmup)
d.Set("metric_name", object.MetricName)
targetValue, err := strconv.ParseFloat(strconv.FormatFloat(object.TargetValue, 'f', 3, 64), 64)
if err != nil {
return WrapError(err)
}
d.Set("target_value", targetValue)
d.Set("disable_scale_in", object.DisableScaleIn)
steps, err := flattenStepAdjustmentMappings(object.StepAdjustments.StepAdjustment)
if err != nil {
return WrapError(err)
}
d.Set("step_adjustment", steps)
return nil
}
func resourceAliyunEssScalingRuleDelete(d *schema.ResourceData, meta interface{}) error {
//Compatible with older versions id
if strings.Contains(d.Id(), COLON_SEPARATED) {
parts, _ := ParseResourceId(d.Id(), 2)
d.SetId(parts[1])
}
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
request := ess.CreateDeleteScalingRuleRequest()
request.ScalingRuleId = d.Id()
request.RegionId = client.RegionId
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DeleteScalingRule(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidScalingRuleId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(essService.WaitForEssScalingRule(d.Id(), Deleted, DefaultTimeout))
}
func resourceAliyunEssScalingRuleUpdate(d *schema.ResourceData, meta interface{}) error {
//Compatible with older versions id
if strings.Contains(d.Id(), COLON_SEPARATED) {
parts, _ := ParseResourceId(d.Id(), 2)
d.SetId(parts[1])
}
client := meta.(*connectivity.AliyunClient)
request := ess.CreateModifyScalingRuleRequest()
request.ScalingRuleId = d.Id()
request.RegionId = client.RegionId
if d.HasChange("scaling_rule_name") {
request.ScalingRuleName = d.Get("scaling_rule_name").(string)
}
scalingRuleType := d.Get("scaling_rule_type")
switch scalingRuleType {
case string(SimpleScalingRule):
if d.HasChange("adjustment_type") {
request.AdjustmentType = d.Get("adjustment_type").(string)
}
if d.HasChange("adjustment_value") {
request.AdjustmentValue = requests.NewInteger(d.Get("adjustment_value").(int))
}
if d.HasChange("cooldown") {
request.Cooldown = requests.NewInteger(d.Get("cooldown").(int))
}
case string(TargetTrackingScalingRule):
if d.HasChange("metric_name") {
request.MetricName = d.Get("metric_name").(string)
}
if d.HasChange("disable_scale_in") {
request.DisableScaleIn = requests.NewBoolean(d.Get("disable_scale_in").(bool))
}
if d.HasChange("estimated_instance_warmup") {
request.EstimatedInstanceWarmup = requests.NewInteger(d.Get("estimated_instance_warmup").(int))
}
if d.HasChange("target_value") {
targetValue, err := strconv.ParseFloat(strconv.FormatFloat(d.Get("target_value").(float64), 'f', 3, 64), 64)
if err != nil {
return WrapError(err)
}
request.TargetValue = requests.NewFloat(targetValue)
}
case string(StepScalingRule):
if d.HasChange("step_adjustment") {
steps := make([]ess.ModifyScalingRuleStepAdjustment, 0)
for _, e := range d.Get("step_adjustment").([]interface{}) {
pack := e.(map[string]interface{})
step := ess.ModifyScalingRuleStepAdjustment{
ScalingAdjustment: strconv.Itoa(pack["scaling_adjustment"].(int)),
}
if pack["metric_interval_lower_bound"] != "" {
lowerBound, err := strconv.ParseFloat(pack["metric_interval_lower_bound"].(string), 64)
if err != nil {
return WrapError(err)
}
step.MetricIntervalLowerBound = strconv.FormatFloat(lowerBound, 'f', 3, 64)
}
if pack["metric_interval_upper_bound"] != "" {
upperBound, err := strconv.ParseFloat(pack["metric_interval_upper_bound"].(string), 64)
if err != nil {
return WrapError(err)
}
step.MetricIntervalUpperBound = strconv.FormatFloat(upperBound, 'f', 3, 64)
}
steps = append(steps, step)
}
request.StepAdjustment = &steps
}
}
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.ModifyScalingRule(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return resourceAliyunEssScalingRuleRead(d, meta)
}
func buildAlicloudEssScalingRuleArgs(d *schema.ResourceData, meta interface{}) (*ess.CreateScalingRuleRequest, error) {
request := ess.CreateCreateScalingRuleRequest()
// common params
request.ScalingGroupId = d.Get("scaling_group_id").(string)
scalingRuleType := d.Get("scaling_rule_type").(string)
if v, ok := d.GetOk("scaling_rule_name"); ok && v.(string) != "" {
request.ScalingRuleName = v.(string)
}
request.ScalingRuleType = d.Get("scaling_rule_type").(string)
switch scalingRuleType {
case string(SimpleScalingRule):
if v, ok := d.GetOk("adjustment_type"); ok && v.(string) != "" {
request.AdjustmentType = v.(string)
}
if v, ok := d.GetOkExists("adjustment_value"); ok {
request.AdjustmentValue = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("cooldown"); ok {
request.Cooldown = requests.NewInteger(v.(int))
}
case string(TargetTrackingScalingRule):
if v, ok := d.GetOk("estimated_instance_warmup"); ok {
request.EstimatedInstanceWarmup = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("metric_name"); ok && v.(string) != "" {
request.MetricName = v.(string)
}
if v, ok := d.GetOk("target_value"); ok {
targetValue, err := strconv.ParseFloat(strconv.FormatFloat(v.(float64), 'f', 3, 64), 64)
if err != nil {
return nil, WrapError(err)
}
request.TargetValue = requests.NewFloat(targetValue)
}
if v, ok := d.GetOk("disable_scale_in"); ok {
request.DisableScaleIn = requests.NewBoolean(v.(bool))
}
case string(StepScalingRule):
v, ok := d.GetOk("step_adjustment")
if v, ok := d.GetOk("adjustment_type"); ok && v.(string) != "" {
request.AdjustmentType = v.(string)
}
if v, ok := d.GetOk("estimated_instance_warmup"); ok {
request.EstimatedInstanceWarmup = requests.NewInteger(v.(int))
}
if ok {
steps := make([]ess.CreateScalingRuleStepAdjustment, 0)
for _, e := range v.([]interface{}) {
pack := e.(map[string]interface{})
step := ess.CreateScalingRuleStepAdjustment{
ScalingAdjustment: strconv.Itoa(pack["scaling_adjustment"].(int)),
}
if pack["metric_interval_lower_bound"] != "" {
lowerBound, err := strconv.ParseFloat(pack["metric_interval_lower_bound"].(string), 64)
if err != nil {
return nil, WrapError(err)
}
step.MetricIntervalLowerBound = strconv.FormatFloat(lowerBound, 'f', 3, 64)
}
if pack["metric_interval_upper_bound"] != "" {
upperBound, err := strconv.ParseFloat(pack["metric_interval_upper_bound"].(string), 64)
if err != nil {
return nil, WrapError(err)
}
step.MetricIntervalUpperBound = strconv.FormatFloat(upperBound, 'f', 3, 64)
}
steps = append(steps, step)
}
request.StepAdjustment = &steps
}
}
return request, nil
}
func flattenStepAdjustmentMappings(list []ess.StepAdjustment) ([]map[string]interface{}, error) {
result := make([]map[string]interface{}, 0, len(list))
for _, i := range list {
lowerBound, err := strconv.ParseFloat(strconv.FormatFloat(i.MetricIntervalLowerBound, 'f', 3, 64), 64)
if err != nil {
return nil, WrapError(err)
}
upperBound, err := strconv.ParseFloat(strconv.FormatFloat(i.MetricIntervalUpperBound, 'f', 3, 64), 64)
if err != nil {
return nil, WrapError(err)
}
l := map[string]interface{}{
"metric_interval_lower_bound": lowerBound,
"metric_interval_upper_bound": upperBound,
"scaling_adjustment": i.ScalingAdjustment,
}
result = append(result, l)
}
return result, nil
}
package alicloud
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ess"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudEssScheduledTask() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunEssScheduledTaskCreate,
Read: resourceAliyunEssScheduledTaskRead,
Update: resourceAliyunEssScheduledTaskUpdate,
Delete: resourceAliyunEssScheduledTaskDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"scheduled_action": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"scaling_group_id"},
},
"launch_time": {
Type: schema.TypeString,
Optional: true,
},
"scheduled_task_name": {
Type: schema.TypeString,
Optional: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"scaling_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"scheduled_action"},
},
"launch_expiration_time": {
Type: schema.TypeInt,
Default: 600,
Optional: true,
ValidateFunc: validation.IntBetween(0, 21600),
},
"min_value": {
Type: schema.TypeInt,
Optional: true,
},
"max_value": {
Type: schema.TypeInt,
Optional: true,
},
"desired_capacity": {
Type: schema.TypeInt,
Optional: true,
},
//RecurrenceType, RecurrenceValue and RecurrenceEndTime must be specified.
"recurrence_type": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Daily", "Weekly", "Monthly", "Cron"}, false),
},
"recurrence_value": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"recurrence_end_time": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"task_enabled": {
Type: schema.TypeBool,
Default: true,
Optional: true,
},
},
}
}
func resourceAliyunEssScheduledTaskCreate(d *schema.ResourceData, meta interface{}) error {
request := buildAlicloudEssScheduledTaskArgs(d)
client := meta.(*connectivity.AliyunClient)
request.RegionId = client.RegionId
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.CreateScheduledTask(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ess_scheduled_task", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ess.CreateScheduledTaskResponse)
d.SetId(response.ScheduledTaskId)
return resourceAliyunEssScheduledTaskRead(d, meta)
}
func resourceAliyunEssScheduledTaskRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
object, err := essService.DescribeEssScheduledTask(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("scheduled_action", object.ScheduledAction)
d.Set("launch_time", object.LaunchTime)
d.Set("scheduled_task_name", object.ScheduledTaskName)
d.Set("description", object.Description)
d.Set("launch_expiration_time", object.LaunchExpirationTime)
d.Set("recurrence_type", object.RecurrenceType)
d.Set("recurrence_value", object.RecurrenceValue)
d.Set("recurrence_end_time", object.RecurrenceEndTime)
d.Set("task_enabled", object.TaskEnabled)
d.Set("min_value", object.MinValue)
d.Set("max_value", object.MaxValue)
d.Set("desired_capacity", object.DesiredCapacity)
d.Set("scaling_group_id", object.ScalingGroupId)
return nil
}
func resourceAliyunEssScheduledTaskUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ess.CreateModifyScheduledTaskRequest()
request.RegionId = client.RegionId
request.ScheduledTaskId = d.Id()
request.LaunchExpirationTime = requests.NewInteger(d.Get("launch_expiration_time").(int))
if d.HasChange("scheduled_task_name") {
request.ScheduledTaskName = d.Get("scheduled_task_name").(string)
}
if d.HasChange("scaling_group_id") {
request.ScalingGroupId = d.Get("scaling_group_id").(string)
}
if d.HasChange("min_value") {
request.MinValue = requests.NewInteger(d.Get("min_value").(int))
}
if d.HasChange("max_value") {
request.MaxValue = requests.NewInteger(d.Get("max_value").(int))
}
if d.HasChange("desired_capacity") {
request.DesiredCapacity = requests.NewInteger(d.Get("desired_capacity").(int))
}
if d.HasChange("description") {
request.Description = d.Get("description").(string)
}
if d.HasChange("scheduled_action") {
request.ScheduledAction = d.Get("scheduled_action").(string)
}
if d.HasChange("launch_time") {
request.LaunchTime = d.Get("launch_time").(string)
}
if d.HasChange("recurrence_type") || d.HasChange("recurrence_value") || d.HasChange("recurrence_end_time") {
request.RecurrenceType = d.Get("recurrence_type").(string)
request.RecurrenceValue = d.Get("recurrence_value").(string)
request.RecurrenceEndTime = d.Get("recurrence_end_time").(string)
}
if d.HasChange("task_enabled") {
request.TaskEnabled = requests.NewBoolean(d.Get("task_enabled").(bool))
}
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.ModifyScheduledTask(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return resourceAliyunEssScheduledTaskRead(d, meta)
}
func resourceAliyunEssScheduledTaskDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
essService := EssService{client}
request := ess.CreateDeleteScheduledTaskRequest()
request.ScheduledTaskId = d.Id()
request.RegionId = client.RegionId
raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DeleteScheduledTask(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidScheduledTaskId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(essService.WaitForEssScheduledTask(d.Id(), Deleted, DefaultTimeout))
}
func buildAlicloudEssScheduledTaskArgs(d *schema.ResourceData) *ess.CreateScheduledTaskRequest {
request := ess.CreateCreateScheduledTaskRequest()
if v, ok := d.GetOk("scheduled_action"); ok && v.(string) != "" {
request.ScheduledAction = v.(string)
}
if v, ok := d.GetOk("launch_time"); ok && v.(string) != "" {
request.LaunchTime = v.(string)
}
if v, ok := d.GetOk("task_enabled"); ok {
request.TaskEnabled = requests.NewBoolean(v.(bool))
}
if v, ok := d.GetOk("scheduled_task_name"); ok && v.(string) != "" {
request.ScheduledTaskName = v.(string)
}
if v, ok := d.GetOk("description"); ok && v.(string) != "" {
request.Description = v.(string)
}
if v, ok := d.GetOk("recurrence_type"); ok && v.(string) != "" {
request.RecurrenceType = v.(string)
}
if v, ok := d.GetOk("recurrence_value"); ok && v.(string) != "" {
request.RecurrenceValue = v.(string)
}
if v, ok := d.GetOk("recurrence_end_time"); ok && v.(string) != "" {
request.RecurrenceEndTime = v.(string)
}
if v, ok := d.GetOk("scaling_group_id"); ok && v.(string) != "" {
request.ScalingGroupId = v.(string)
}
if v, ok := d.GetOk("launch_expiration_time"); ok && v.(int) != 0 {
request.LaunchExpirationTime = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("min_value"); ok && v.(int) != 0 {
request.MinValue = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("max_value"); ok && v.(int) != 0 {
request.MaxValue = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("desired_capacity"); ok && v.(int) != 0 {
request.DesiredCapacity = requests.NewInteger(v.(int))
}
return request
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEventBridgeEventBus() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEventBridgeEventBusCreate,
Read: resourceAlicloudEventBridgeEventBusRead,
Update: resourceAlicloudEventBridgeEventBusUpdate,
Delete: resourceAlicloudEventBridgeEventBusDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
},
"event_bus_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(0, 127),
},
},
}
}
func resourceAlicloudEventBridgeEventBusCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateEventBus"
request := make(map[string]interface{})
conn, err := client.NewEventbridgeClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["EventBusName"] = d.Get("event_bus_name")
request["ClientToken"] = buildClientToken("CreateEventBus")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_event_bridge_event_bus", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return WrapError(fmt.Errorf("CreateEventBus failed, response: %v", response))
}
d.SetId(fmt.Sprint(request["EventBusName"]))
return resourceAlicloudEventBridgeEventBusRead(d, meta)
}
func resourceAlicloudEventBridgeEventBusRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
eventbridgeService := EventbridgeService{client}
object, err := eventbridgeService.DescribeEventBridgeEventBus(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_event_bridge_event_bus eventbridgeService.DescribeEventBridgeEventBus Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("event_bus_name", d.Id())
d.Set("description", object["Description"])
return nil
}
func resourceAlicloudEventBridgeEventBusUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
if d.HasChange("description") {
request := map[string]interface{}{
"EventBusName": d.Id(),
}
request["Description"] = d.Get("description")
action := "UpdateEventBus"
conn, err := client.NewEventbridgeClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return WrapError(fmt.Errorf("UpdateEventBus failed, response: %v", response))
}
}
return resourceAlicloudEventBridgeEventBusRead(d, meta)
}
func resourceAlicloudEventBridgeEventBusDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteEventBus"
var response map[string]interface{}
conn, err := client.NewEventbridgeClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"EventBusName": d.Id(),
}
request["ClientToken"] = buildClientToken("DeleteEventBus")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EventBusNotExist"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("DeleteEventBus failed, response: %v", response))
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEventBridgeEventSource() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEventBridgeEventSourceCreate,
Read: resourceAlicloudEventBridgeEventSourceRead,
Update: resourceAlicloudEventBridgeEventSourceUpdate,
Delete: resourceAlicloudEventBridgeEventSourceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
},
"event_bus_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"event_source_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"external_source_config": {
Type: schema.TypeMap,
Optional: true,
},
"external_source_type": {
Type: schema.TypeString,
Optional: true,
},
"linked_external_source": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
},
}
}
func resourceAlicloudEventBridgeEventSourceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateEventSource"
request := make(map[string]interface{})
conn, err := client.NewEventbridgeClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["EventSourceName"] = d.Get("event_source_name")
request["EventBusName"] = d.Get("event_bus_name")
if v, ok := d.GetOk("external_source_config"); ok {
if v, err := convertMaptoJsonString(v.(map[string]interface{})); err == nil {
request["ExternalSourceConfig"] = v
} else {
return WrapError(err)
}
}
if v, ok := d.GetOk("external_source_type"); ok {
request["ExternalSourceType"] = v
}
if v, ok := d.GetOkExists("linked_external_source"); ok {
request["LinkedExternalSource"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_event_bridge_event_source", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetId(fmt.Sprint(request["EventSourceName"]))
return resourceAlicloudEventBridgeEventSourceRead(d, meta)
}
func resourceAlicloudEventBridgeEventSourceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
eventbridgeService := EventbridgeService{client}
object, err := eventbridgeService.DescribeEventBridgeEventSource(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_event_bridge_event_source eventbridgeService.DescribeEventBridgeEventSource Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("event_source_name", d.Id())
d.Set("description", object["Description"])
d.Set("event_bus_name", object["EventBusName"])
d.Set("external_source_config", object["ExternalSourceConfig"])
d.Set("external_source_type", object["ExternalSourceType"])
d.Set("linked_external_source", object["LinkedExternalSource"])
return nil
}
func resourceAlicloudEventBridgeEventSourceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"EventSourceName": d.Id(),
}
if d.HasChange("description") {
update = true
request["Description"] = d.Get("description")
}
if d.HasChange("external_source_config") {
update = true
if v, err := convertMaptoJsonString(d.Get("external_source_config").(map[string]interface{})); err == nil {
request["ExternalSourceConfig"] = v
} else {
return WrapError(err)
}
}
request["ExternalSourceType"] = d.Get("external_source_type")
if d.HasChange("external_source_type") {
update = true
}
request["LinkedExternalSource"] = d.Get("linked_external_source")
if d.HasChange("linked_external_source") || d.IsNewResource() {
update = true
}
if update {
action := "UpdateEventSource"
conn, err := client.NewEventbridgeClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("event_bus_name"); ok {
request["EventBusName"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
}
return resourceAlicloudEventBridgeEventSourceRead(d, meta)
}
func resourceAlicloudEventBridgeEventSourceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteEventSource"
var response map[string]interface{}
conn, err := client.NewEventbridgeClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"EventSourceName": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudEventBridgeRule() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEventBridgeRuleCreate,
Read: resourceAlicloudEventBridgeRuleRead,
Update: resourceAlicloudEventBridgeRuleUpdate,
Delete: resourceAlicloudEventBridgeRuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
},
"event_bus_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"filter_pattern": {
Type: schema.TypeString,
Required: true,
},
"rule_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"DISABLE", "ENABLE"}, false),
},
"targets": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"endpoint": {
Type: schema.TypeString,
Required: true,
},
"param_list": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"form": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"ORIGINAL", "TEMPLATE", "JSONPATH", "CONSTANT"}, false),
},
"resource_key": {
Type: schema.TypeString,
Required: true,
},
"template": {
Type: schema.TypeString,
Optional: true,
},
"value": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"target_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"acs.fc.function", "acs.mns.topic", "acs.mns.queue", "http", "acs.sms", "acs.mail", "acs.dingtalk", "https", "acs.eventbridge", "acs.rabbitmq", "acs.rocketmq"}, false),
},
},
},
},
},
}
}
func resourceAlicloudEventBridgeRuleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateRule"
request := make(map[string]interface{})
conn, err := client.NewEventbridgeClient()
if err != nil {
return WrapError(err)
}
request["EventBusName"] = d.Get("event_bus_name")
if v, ok := d.GetOk("filter_pattern"); ok {
request["FilterPattern"] = v
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["RuleName"] = d.Get("rule_name")
if v, ok := d.GetOk("targets"); ok {
targetsMaps := make([]map[string]interface{}, 0)
for _, targets := range v.(*schema.Set).List() {
targetsArg := targets.(map[string]interface{})
targetsMap := map[string]interface{}{}
targetsMap["endpoint"] = targetsArg["endpoint"]
targetsMap["id"] = targetsArg["target_id"]
targetsMap["type"] = targetsArg["type"]
targetsMaps = append(targetsMaps, targetsMap)
paramListMaps := make([]map[string]interface{}, 0)
for _, paramList := range targetsArg["param_list"].(*schema.Set).List() {
paramListArg := paramList.(map[string]interface{})
paramListMap := map[string]interface{}{}
paramListMap["form"] = paramListArg["form"]
paramListMap["resourceKey"] = paramListArg["resource_key"]
if paramListMap["form"] == "TEMPLATE" {
paramListMap["template"] = paramListArg["template"]
paramListMap["value"] = paramListArg["value"]
}
if paramListMap["form"] == "JSONPATH" || paramListMap["form"] == "CONSTANT" {
paramListMap["value"] = paramListArg["value"]
}
paramListMaps = append(paramListMaps, paramListMap)
}
targetsMap["paramList"] = paramListMaps
}
if v, err := convertArrayObjectToJsonString(targetsMaps); err == nil {
request["Targets"] = v
} else {
return WrapError(err)
}
}
request["ClientToken"] = buildClientToken("CreateRule")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_event_bridge_rule", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return WrapError(fmt.Errorf("CreateRule failed, response: %v", response))
}
d.SetId(fmt.Sprint(request["EventBusName"], ":", request["RuleName"]))
return resourceAlicloudEventBridgeRuleUpdate(d, meta)
}
func resourceAlicloudEventBridgeRuleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
eventbridgeService := EventbridgeService{client}
object, err := eventbridgeService.DescribeEventBridgeRule(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_event_bridge_rule eventbridgeService.DescribeEventBridgeRule Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("event_bus_name", parts[0])
d.Set("rule_name", parts[1])
d.Set("description", object["Description"])
d.Set("filter_pattern", object["FilterPattern"])
d.Set("status", object["Status"])
if targetsList, ok := object["Targets"]; ok && targetsList != nil {
targetsMaps := make([]map[string]interface{}, 0)
for _, targetsListItem := range targetsList.([]interface{}) {
if targetsListItemMap, ok := targetsListItem.(map[string]interface{}); ok {
targetsListMap := make(map[string]interface{})
targetsListMap["endpoint"] = targetsListItemMap["Endpoint"]
targetsListMap["target_id"] = targetsListItemMap["Id"]
targetsListMap["type"] = targetsListItemMap["Type"]
if paramListMap, ok := targetsListItemMap["ParamList"]; ok && paramListMap != nil {
paramListMaps := make([]map[string]interface{}, 0)
for _, paramListMapItem := range paramListMap.([]interface{}) {
paramListMap := make(map[string]interface{})
if paramListMapItemMap, ok := paramListMapItem.(map[string]interface{}); ok {
paramListMap["form"] = paramListMapItemMap["Form"]
paramListMap["resource_key"] = paramListMapItemMap["ResourceKey"]
paramListMap["template"] = paramListMapItemMap["Template"]
paramListMap["value"] = paramListMapItemMap["Value"]
paramListMaps = append(paramListMaps, paramListMap)
}
}
targetsListMap["param_list"] = paramListMaps
}
targetsMaps = append(targetsMaps, targetsListMap)
}
}
err = d.Set("targets", targetsMaps)
if err != nil {
return WrapError(err)
}
}
return nil
}
func resourceAlicloudEventBridgeRuleUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
eventbridgeService := EventbridgeService{client}
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Partial(true)
update := false
request := map[string]interface{}{
"EventBusName": parts[0],
"RuleName": parts[1],
}
if d.HasChange("targets") {
update = true
targetsMaps := make([]map[string]interface{}, 0)
for _, targets := range d.Get("targets").(*schema.Set).List() {
targetsArg := targets.(map[string]interface{})
targetsMap := map[string]interface{}{}
targetsMap["endpoint"] = targetsArg["endpoint"]
targetsMap["id"] = targetsArg["target_id"]
targetsMap["type"] = targetsArg["type"]
targetsMaps = append(targetsMaps, targetsMap)
paramListMaps := make([]map[string]interface{}, 0)
for _, paramList := range targetsArg["param_list"].(*schema.Set).List() {
paramListArg := paramList.(map[string]interface{})
paramListMap := map[string]interface{}{}
paramListMap["form"] = paramListArg["form"]
paramListMap["resourceKey"] = paramListArg["resource_key"]
if paramListMap["form"] == "TEMPLATE" {
paramListMap["template"] = paramListArg["template"]
paramListMap["value"] = paramListArg["value"]
}
if paramListMap["form"] == "JSONPATH" || paramListMap["form"] == "CONSTANT" {
paramListMap["value"] = paramListArg["value"]
}
paramListMaps = append(paramListMaps, paramListMap)
}
targetsMap["paramList"] = paramListMaps
}
if v, err := convertArrayObjectToJsonString(targetsMaps); err == nil {
request["Targets"] = v
} else {
return WrapError(err)
}
}
if update {
action := "UpdateTargets"
conn, err := client.NewEventbridgeClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("UpdateTargets")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return WrapError(fmt.Errorf("UpdateTargets failed, response: %v", response))
}
d.SetPartial("targets")
}
update = false
updateRuleReq := map[string]interface{}{
"EventBusName": parts[0],
"RuleName": parts[1],
}
if !d.IsNewResource() && d.HasChange("description") {
update = true
updateRuleReq["Description"] = d.Get("description")
}
if !d.IsNewResource() && d.HasChange("filter_pattern") {
update = true
}
updateRuleReq["FilterPattern"] = d.Get("filter_pattern")
if update {
action := "UpdateRule"
conn, err := client.NewEventbridgeClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("UpdateRule")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-01"), StringPointer("AK"), nil, updateRuleReq, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, updateRuleReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return WrapError(fmt.Errorf("UpdateRule failed, response: %v", response))
}
d.SetPartial("description")
d.SetPartial("filter_pattern")
}
if d.HasChange("status") {
object, err := eventbridgeService.DescribeEventBridgeRule(d.Id())
if err != nil {
return WrapError(err)
}
target := d.Get("status").(string)
if object["Status"].(string) != target {
if target == "DISABLE" {
request := map[string]interface{}{
"EventBusName": parts[0],
"RuleName": parts[1],
}
action := "DisableRule"
conn, err := client.NewEventbridgeClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return WrapError(fmt.Errorf("DisableRule failed, response: %v", response))
}
stateConf := BuildStateConf([]string{}, []string{"DISABLE"}, d.Timeout(schema.TimeoutUpdate), 10*time.Second, eventbridgeService.EventBridgeRuleStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if target == "ENABLE" {
request := map[string]interface{}{
"EventBusName": parts[0],
"RuleName": parts[1],
}
action := "EnableRule"
conn, err := client.NewEventbridgeClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return WrapError(fmt.Errorf("EnableRule failed, response: %v", response))
}
stateConf := BuildStateConf([]string{}, []string{"ENABLE"}, d.Timeout(schema.TimeoutUpdate), 10*time.Second, eventbridgeService.EventBridgeRuleStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.SetPartial("status")
}
}
d.Partial(false)
return resourceAlicloudEventBridgeRuleRead(d, meta)
}
func resourceAlicloudEventBridgeRuleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
eventbridgeService := EventbridgeService{client}
action := "DeleteRule"
var response map[string]interface{}
conn, err := client.NewEventbridgeClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"EventBusName": parts[0],
"RuleName": parts[1],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if IsExpectedErrorCodes(fmt.Sprint(response["Code"]), []string{"EventRuleNotExisted"}) {
return nil
}
if fmt.Sprint(response["Code"]) != "Success" {
return WrapError(fmt.Errorf("DeleteRule failed, response: %v", response))
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, eventbridgeService.EventBridgeRuleStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudEventBridgeServiceLinkedRole() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEventBridgeServiceLinkedRoleCreate,
Read: resourceAlicloudEventBridgeServiceLinkedRoleRead,
Delete: resourceAlicloudEventBridgeServiceLinkedRoleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"product_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
"AliyunServiceRoleForEventBridgeSourceRocketMQ",
"AliyunServiceRoleForEventBridgeSourceActionTrail",
"AliyunServiceRoleForEventBridgeSourceRabbitMQ",
"AliyunServiceRoleForEventBridgeSendToMNS",
"AliyunServiceRoleForEventBridgeConnectVPC",
"AliyunServiceRoleForEventBridgeSendToFC",
"AliyunServiceRoleForEventBridgeSendToSMS",
"AliyunServiceRoleForEventBridgeSendToDirectMail",
"AliyunServiceRoleForEventBridgeSendToRabbitMQ",
"AliyunServiceRoleForEventBridgeSendToRocketMQ",
}, false),
},
},
}
}
func resourceAlicloudEventBridgeServiceLinkedRoleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
eventbridgeService := EventbridgeService{client}
var response map[string]interface{}
action := "CreateServiceLinkedRoleForProduct"
request := map[string]interface{}{
"ProductName": d.Get("product_name"),
}
conn, err := client.NewEventbridgeClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_event_bridge_service_linked_role", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return WrapError(fmt.Errorf("CreateServiceLinkedRoleForProduct failed, response: %v", response))
}
d.SetId(request["ProductName"].(string))
stateConf := BuildStateConf([]string{}, []string{"true"}, d.Timeout(schema.TimeoutCreate), 10*time.Second, eventbridgeService.CheckRoleForProductRefreshFunc(d.Id(), []string{"false"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudEventBridgeServiceLinkedRoleRead(d, meta)
}
func resourceAlicloudEventBridgeServiceLinkedRoleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
eventbridgeService := EventbridgeService{client}
object, err := eventbridgeService.DescribeEventBridgeServiceLinkedRole(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_event_bridge_event_bus eventbridgeService.DescribeEventBridgeServiceLinkedRole Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("product_name", object["StsRoleName"])
return nil
}
func resourceAlicloudEventBridgeServiceLinkedRoleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteServiceLinkedRole"
var response map[string]interface{}
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"RoleName": d.Id(),
}
wait := incrementalWait(3*time.Second, 0*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), request, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist.Role"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudExpressConnectPhysicalConnection() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudExpressConnectPhysicalConnectionCreate,
Read: resourceAlicloudExpressConnectPhysicalConnectionRead,
Update: resourceAlicloudExpressConnectPhysicalConnectionUpdate,
Delete: resourceAlicloudExpressConnectPhysicalConnectionDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(2 * time.Minute),
},
Schema: map[string]*schema.Schema{
"access_point_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"bandwidth": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"circuit_code": {
Type: schema.TypeString,
Optional: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"line_operator": {
Type: schema.TypeString,
Required: true,
},
"peer_location": {
Type: schema.TypeString,
Required: true,
},
"physical_connection_name": {
Type: schema.TypeString,
Optional: true,
},
"port_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"1000Base-LX", "1000Base-T", "100Base-T", "10GBase-LR", "10GBase-T"}, false),
},
"redundant_physical_connection_id": {
Type: schema.TypeString,
Optional: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Canceled", "Enabled", "Terminated"}, false),
},
"type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudExpressConnectPhysicalConnectionCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreatePhysicalConnection"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request["AccessPointId"] = d.Get("access_point_id")
if v, ok := d.GetOk("bandwidth"); ok {
request["bandwidth"] = v
}
if v, ok := d.GetOk("circuit_code"); ok {
request["CircuitCode"] = v
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["LineOperator"] = d.Get("line_operator")
request["PeerLocation"] = d.Get("peer_location")
if v, ok := d.GetOk("physical_connection_name"); ok {
request["Name"] = v
}
if v, ok := d.GetOk("port_type"); ok {
request["PortType"] = v
}
if v, ok := d.GetOk("redundant_physical_connection_id"); ok {
request["RedundantPhysicalConnectionId"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("type"); ok {
request["Type"] = v
}
request["ClientToken"] = buildClientToken("CreatePhysicalConnection")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_express_connect_physical_connection", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["PhysicalConnectionId"]))
vpcService := VpcService{client}
stateConf := BuildStateConf([]string{}, []string{"Allocated"}, d.Timeout(schema.TimeoutCreate), 1*time.Second, vpcService.ExpressConnectPhysicalConnectionStateRefreshFunc(d.Id(), []string{"Allocation Failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudExpressConnectPhysicalConnectionUpdate(d, meta)
}
func resourceAlicloudExpressConnectPhysicalConnectionRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeExpressConnectPhysicalConnection(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_express_connect_physical_connection vpcService.DescribeExpressConnectPhysicalConnection Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("access_point_id", object["AccessPointId"])
d.Set("bandwidth", fmt.Sprint(formatInt(object["Bandwidth"])))
d.Set("circuit_code", object["CircuitCode"])
d.Set("description", object["Description"])
d.Set("line_operator", object["LineOperator"])
d.Set("peer_location", object["PeerLocation"])
d.Set("physical_connection_name", object["Name"])
d.Set("port_type", object["PortType"])
d.Set("redundant_physical_connection_id", object["RedundantPhysicalConnectionId"])
d.Set("status", object["Status"])
d.Set("type", object["Type"])
return nil
}
func resourceAlicloudExpressConnectPhysicalConnectionUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"PhysicalConnectionId": d.Id(),
}
request["RegionId"] = client.RegionId
if !d.IsNewResource() && d.HasChange("bandwidth") {
update = true
if v, ok := d.GetOk("bandwidth"); ok {
request["bandwidth"] = v
}
}
if !d.IsNewResource() && d.HasChange("circuit_code") {
update = true
if v, ok := d.GetOk("circuit_code"); ok {
request["CircuitCode"] = v
}
}
if !d.IsNewResource() && d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
}
if !d.IsNewResource() && d.HasChange("line_operator") {
update = true
request["LineOperator"] = d.Get("line_operator")
}
if !d.IsNewResource() && d.HasChange("peer_location") {
update = true
request["PeerLocation"] = d.Get("peer_location")
}
if !d.IsNewResource() && d.HasChange("physical_connection_name") {
update = true
if v, ok := d.GetOk("physical_connection_name"); ok {
request["Name"] = v
}
}
if !d.IsNewResource() && d.HasChange("port_type") {
update = true
if v, ok := d.GetOk("port_type"); ok {
request["PortType"] = v
}
}
if !d.IsNewResource() && d.HasChange("redundant_physical_connection_id") {
update = true
if v, ok := d.GetOk("redundant_physical_connection_id"); ok {
request["RedundantPhysicalConnectionId"] = v
}
}
if update {
action := "ModifyPhysicalConnectionAttribute"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("ModifyPhysicalConnectionAttribute")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("bandwidth")
d.SetPartial("circuit_code")
d.SetPartial("description")
d.SetPartial("line_operator")
d.SetPartial("peer_location")
d.SetPartial("physical_connection_name")
d.SetPartial("port_type")
d.SetPartial("redundant_physical_connection_id")
}
if d.HasChange("status") {
object, err := vpcService.DescribeExpressConnectPhysicalConnection(d.Id())
if err != nil {
return WrapError(err)
}
target := d.Get("status").(string)
if object["Status"].(string) != target {
if target == "Canceled" {
request := map[string]interface{}{
"PhysicalConnectionId": d.Id(),
}
request["RegionId"] = client.RegionId
action := "CancelPhysicalConnection"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("CancelPhysicalConnection")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if target == "Enabled" {
request := map[string]interface{}{
"PhysicalConnectionId": d.Id(),
}
request["RegionId"] = client.RegionId
action := "EnablePhysicalConnection"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("EnablePhysicalConnection")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if target == "Terminated" {
request := map[string]interface{}{
"PhysicalConnectionId": d.Id(),
}
request["RegionId"] = client.RegionId
action := "TerminatePhysicalConnection"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("TerminatePhysicalConnection")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("status")
}
}
d.Partial(false)
return resourceAlicloudExpressConnectPhysicalConnectionRead(d, meta)
}
func resourceAlicloudExpressConnectPhysicalConnectionDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeletePhysicalConnection"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"PhysicalConnectionId": d.Id(),
}
request["RegionId"] = client.RegionId
request["ClientToken"] = buildClientToken("DeletePhysicalConnection")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudExpressConnectVirtualBorderRouter() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudExpressConnectVirtualBorderRouterCreate,
Read: resourceAlicloudExpressConnectVirtualBorderRouterRead,
Update: resourceAlicloudExpressConnectVirtualBorderRouterUpdate,
Delete: resourceAlicloudExpressConnectVirtualBorderRouterDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Update: schema.DefaultTimeout(2 * time.Minute),
},
Schema: map[string]*schema.Schema{
"associated_physical_connections": {
Type: schema.TypeString,
Optional: true,
},
"bandwidth": {
Type: schema.TypeInt,
Optional: true,
},
"circuit_code": {
Type: schema.TypeString,
Optional: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"detect_multiplier": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(3, 10),
},
"enable_ipv6": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"local_gateway_ip": {
Type: schema.TypeString,
Required: true,
},
"local_ipv6_gateway_ip": {
Type: schema.TypeString,
Optional: true,
},
"min_rx_interval": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(200, 1000),
},
"min_tx_interval": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(200, 1000),
},
"peer_gateway_ip": {
Type: schema.TypeString,
Required: true,
},
"peer_ipv6_gateway_ip": {
Type: schema.TypeString,
Optional: true,
},
"peering_ipv6_subnet_mask": {
Type: schema.TypeString,
Optional: true,
},
"peering_subnet_mask": {
Type: schema.TypeString,
Required: true,
},
"physical_connection_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"active", "deleting", "recovering", "terminated", "terminating", "unconfirmed"}, false),
},
"vbr_owner_id": {
Type: schema.TypeString,
Optional: true,
},
"virtual_border_router_name": {
Type: schema.TypeString,
Optional: true,
},
"vlan_id": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(0, 2999),
},
},
}
}
func resourceAlicloudExpressConnectVirtualBorderRouterCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateVirtualBorderRouter"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("bandwidth"); ok {
request["Bandwidth"] = v
}
if v, ok := d.GetOk("circuit_code"); ok {
request["CircuitCode"] = v
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOkExists("enable_ipv6"); ok {
request["EnableIpv6"] = v
}
request["LocalGatewayIp"] = d.Get("local_gateway_ip")
if v, ok := d.GetOk("local_ipv6_gateway_ip"); ok {
request["LocalIpv6GatewayIp"] = v
}
request["PeerGatewayIp"] = d.Get("peer_gateway_ip")
if v, ok := d.GetOk("peer_ipv6_gateway_ip"); ok {
request["PeerIpv6GatewayIp"] = v
}
if v, ok := d.GetOk("peering_ipv6_subnet_mask"); ok {
request["PeeringIpv6SubnetMask"] = v
}
request["PeeringSubnetMask"] = d.Get("peering_subnet_mask")
request["PhysicalConnectionId"] = d.Get("physical_connection_id")
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("vbr_owner_id"); ok {
request["VbrOwnerId"] = v
}
if v, ok := d.GetOk("virtual_border_router_name"); ok {
request["Name"] = v
}
request["VlanId"] = d.Get("vlan_id")
request["ClientToken"] = buildClientToken("CreateVirtualBorderRouter")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_express_connect_virtual_border_router", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["VbrId"]))
return resourceAlicloudExpressConnectVirtualBorderRouterUpdate(d, meta)
}
func resourceAlicloudExpressConnectVirtualBorderRouterRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeExpressConnectVirtualBorderRouter(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_express_connect_virtual_border_router vpcService.DescribeExpressConnectVirtualBorderRouter Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("circuit_code", object["CircuitCode"])
d.Set("description", object["Description"])
if v, ok := object["DetectMultiplier"]; ok && fmt.Sprint(v) != "0" {
d.Set("detect_multiplier", formatInt(v))
}
d.Set("enable_ipv6", object["EnableIpv6"])
d.Set("local_gateway_ip", object["LocalGatewayIp"])
d.Set("local_ipv6_gateway_ip", object["LocalIpv6GatewayIp"])
if v, ok := object["MinRxInterval"]; ok && fmt.Sprint(v) != "0" {
d.Set("min_rx_interval", formatInt(v))
}
if v, ok := object["MinTxInterval"]; ok && fmt.Sprint(v) != "0" {
d.Set("min_tx_interval", formatInt(v))
}
d.Set("peer_gateway_ip", object["PeerGatewayIp"])
d.Set("peer_ipv6_gateway_ip", object["PeerIpv6GatewayIp"])
d.Set("peering_ipv6_subnet_mask", object["PeeringIpv6SubnetMask"])
d.Set("peering_subnet_mask", object["PeeringSubnetMask"])
d.Set("physical_connection_id", object["PhysicalConnectionId"])
d.Set("status", object["Status"])
d.Set("virtual_border_router_name", object["Name"])
if v, ok := object["VlanId"]; ok && fmt.Sprint(v) != "0" {
d.Set("vlan_id", formatInt(v))
}
return nil
}
func resourceAlicloudExpressConnectVirtualBorderRouterUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"VbrId": d.Id(),
}
request["RegionId"] = client.RegionId
if !d.IsNewResource() && d.HasChange("circuit_code") {
update = true
if v, ok := d.GetOk("circuit_code"); ok {
request["CircuitCode"] = v
}
}
if !d.IsNewResource() && d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
}
if d.HasChange("detect_multiplier") {
update = true
if v, ok := d.GetOk("detect_multiplier"); ok {
request["DetectMultiplier"] = v
} else if v, ok := d.GetOk("min_rx_interval"); ok && fmt.Sprint(v) != "" {
if v, ok := d.GetOk("min_tx_interval"); ok && fmt.Sprint(v) != "" {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is %v and '%s' is %v ", "detect_multiplier", "min_rx_interval", d.Get("min_rx_interval"), "min_tx_interval", d.Get("min_tx_interval")))
}
}
request["MinRxInterval"] = d.Get("min_rx_interval")
request["MinTxInterval"] = d.Get("min_tx_interval")
}
if !d.IsNewResource() && d.HasChange("enable_ipv6") {
update = true
if v, ok := d.GetOkExists("enable_ipv6"); ok {
request["EnableIpv6"] = v
}
}
if !d.IsNewResource() && d.HasChange("local_gateway_ip") {
update = true
request["LocalGatewayIp"] = d.Get("local_gateway_ip")
}
if !d.IsNewResource() && d.HasChange("local_ipv6_gateway_ip") {
update = true
if v, ok := d.GetOk("local_ipv6_gateway_ip"); ok {
request["LocalIpv6GatewayIp"] = v
}
}
if d.HasChange("min_rx_interval") {
update = true
if v, ok := d.GetOk("min_rx_interval"); ok {
request["MinRxInterval"] = v
} else if v, ok := d.GetOk("detect_multiplier"); ok && fmt.Sprint(v) != "" {
if v, ok := d.GetOk("min_tx_interval"); ok && fmt.Sprint(v) != "" {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is %v and '%s' is %v ", "min_rx_interval", "detect_multiplier", d.Get("detect_multiplier"), "min_tx_interval", d.Get("min_tx_interval")))
}
}
request["DetectMultiplier"] = d.Get("detect_multiplier")
request["MinTxInterval"] = d.Get("min_tx_interval")
}
if d.HasChange("min_tx_interval") {
update = true
if v, ok := d.GetOk("min_tx_interval"); ok {
request["MinTxInterval"] = v
} else if v, ok := d.GetOk("detect_multiplier"); ok && fmt.Sprint(v) != "" {
if v, ok := d.GetOk("min_rx_interval"); ok && fmt.Sprint(v) != "" {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is %v and '%s' is %v ", "min_tx_interval", "detect_multiplier", d.Get("detect_multiplier"), "min_rx_interval", d.Get("min_rx_interval")))
}
}
request["DetectMultiplier"] = d.Get("detect_multiplier")
request["MinRxInterval"] = d.Get("min_rx_interval")
}
if !d.IsNewResource() && d.HasChange("peer_gateway_ip") {
update = true
request["PeerGatewayIp"] = d.Get("peer_gateway_ip")
}
if !d.IsNewResource() && d.HasChange("peer_ipv6_gateway_ip") {
update = true
if v, ok := d.GetOk("peer_ipv6_gateway_ip"); ok {
request["PeerIpv6GatewayIp"] = v
}
}
if !d.IsNewResource() && d.HasChange("peering_ipv6_subnet_mask") {
update = true
if v, ok := d.GetOk("peering_ipv6_subnet_mask"); ok {
request["PeeringIpv6SubnetMask"] = v
}
}
if !d.IsNewResource() && d.HasChange("peering_subnet_mask") {
update = true
request["PeeringSubnetMask"] = d.Get("peering_subnet_mask")
}
if !d.IsNewResource() && d.HasChange("virtual_border_router_name") {
update = true
if v, ok := d.GetOk("virtual_border_router_name"); ok {
request["Name"] = v
}
}
if !d.IsNewResource() && d.HasChange("vlan_id") {
update = true
request["VlanId"] = d.Get("vlan_id")
}
if update {
if v, ok := d.GetOk("associated_physical_connections"); ok {
request["AssociatedPhysicalConnections"] = v
}
if v, ok := d.GetOk("bandwidth"); ok {
request["Bandwidth"] = v
}
action := "ModifyVirtualBorderRouterAttribute"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("ModifyVirtualBorderRouterAttribute")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("circuit_code")
d.SetPartial("description")
d.SetPartial("detect_multiplier")
d.SetPartial("enable_ipv6")
d.SetPartial("local_gateway_ip")
d.SetPartial("local_ipv6_gateway_ip")
d.SetPartial("min_rx_interval")
d.SetPartial("min_tx_interval")
d.SetPartial("peer_gateway_ip")
d.SetPartial("peer_ipv6_gateway_ip")
d.SetPartial("peering_ipv6_subnet_mask")
d.SetPartial("peering_subnet_mask")
d.SetPartial("virtual_border_router_name")
d.SetPartial("vlan_id")
}
if d.HasChange("status") {
object, err := vpcService.DescribeExpressConnectVirtualBorderRouter(d.Id())
if err != nil {
return WrapError(err)
}
target := d.Get("status").(string)
if object["Status"].(string) != target {
if target == "active" {
request := map[string]interface{}{
"VbrId": d.Id(),
}
request["RegionId"] = client.RegionId
action := "RecoverVirtualBorderRouter"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("RecoverVirtualBorderRouter")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"active"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, vpcService.ExpressConnectVirtualBorderRouterStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if target == "terminated" {
request := map[string]interface{}{
"VbrId": d.Id(),
}
request["RegionId"] = client.RegionId
action := "TerminateVirtualBorderRouter"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("TerminateVirtualBorderRouter")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"terminated"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, vpcService.ExpressConnectVirtualBorderRouterStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.SetPartial("status")
}
}
d.Partial(false)
return resourceAlicloudExpressConnectVirtualBorderRouterRead(d, meta)
}
func resourceAlicloudExpressConnectVirtualBorderRouterDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteVirtualBorderRouter"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"VbrId": d.Id(),
}
request["RegionId"] = client.RegionId
request["ClientToken"] = buildClientToken("DeleteVirtualBorderRouter")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/aliyun/fc-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudFCAlias() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudFCAliasCreate,
Read: resourceAlicloudFCAliasRead,
Update: resourceAlicloudFCAliasUpdate,
Delete: resourceAlicloudFCAliasDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"service_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"alias_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"service_version": {
Type: schema.TypeString,
Required: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"routing_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"additional_version_weights": {
Type: schema.TypeMap,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeFloat},
},
},
},
},
},
}
}
func resourceAlicloudFCAliasCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
serviceName := d.Get("service_name").(string)
aliasName := d.Get("alias_name").(string)
serviceVersion := d.Get("service_version").(string)
request := fc.NewCreateAliasInput(serviceName).
WithAliasName(aliasName).
WithVersionID(serviceVersion)
if description, ok := d.GetOk("description"); ok {
request = request.WithDescription(description.(string))
}
if routingConfig, ok := d.GetOk("routing_config"); ok {
v := expandFCAliasRoutingConfig(routingConfig.([]interface{}))
request = request.WithAdditionalVersionWeight(v)
}
var response *fc.CreateAliasOutput
var requestInfo *fc.Client
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.CreateAlias(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"AccessDenied"}) {
return resource.RetryableError(WrapError(err))
}
return resource.NonRetryableError(WrapError(err))
}
addDebug("CreateAlias", raw, requestInfo, request)
response, _ = raw.(*fc.CreateAliasOutput)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_fc_alias", "CreateAlias", FcGoSdk)
}
if response == nil {
return WrapError(Error("Creating function compute alias got an empty response"))
}
d.SetId(fmt.Sprintf("%s:%s", serviceName, *response.AliasName))
return resourceAlicloudFCAliasRead(d, meta)
}
func resourceAlicloudFCAliasRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
fcService := FcService{client}
id := d.Id()
response, err := fcService.DescribeFcAlias(id)
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_fc_alias fcService.DescribeFcAlias Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(id, 2)
if err != nil {
return WrapError(err)
}
serviceName := parts[0]
d.Set("service_name", serviceName)
d.Set("alias_name", *response.AliasName)
d.Set("description", *response.Description)
d.Set("service_version", *response.VersionID)
if err := d.Set("routing_config", flattenFCAliasRoutingConfig(response.AdditionalVersionWeight)); err != nil {
return fmt.Errorf("error setting FC alias routing_config: %s", err)
}
return nil
}
func resourceAlicloudFCAliasUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return err
}
serviceName := parts[0]
aliasName := parts[1]
update := false
request := fc.NewUpdateAliasInput(serviceName, aliasName)
if d.HasChange("service_version") {
update = true
request = request.WithVersionID(d.Get("service_version").(string))
}
if d.HasChange("description") {
update = true
request = request.WithDescription(d.Get("description").(string))
}
if d.HasChange("routing_config") {
update = true
if routingConfig, ok := d.GetOk("routing_config"); ok {
v := expandFCAliasRoutingConfig(routingConfig.([]interface{}))
request = request.WithAdditionalVersionWeight(v)
}
}
if update {
var requestInfo *fc.Client
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.UpdateAlias(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "UpdateAlias", FcGoSdk)
}
addDebug("UpdateAlias", raw, requestInfo, request)
}
return resourceAlicloudFCAliasRead(d, meta)
}
func resourceAlicloudFCAliasDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return err
}
serviceName := parts[0]
aliasName := parts[1]
request := fc.NewDeleteAliasInput(serviceName, aliasName)
var requestInfo *fc.Client
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.DeleteAlias(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"AliasNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DeleteAlias", FcGoSdk)
}
addDebug("DeleteCustomDomain", raw, requestInfo, request)
return nil
}
func expandFCAliasRoutingConfig(l []interface{}) map[string]float64 {
if len(l) > 0 && l[0] != nil {
m := l[0].(map[string]interface{})
if v, ok := m["additional_version_weights"]; ok {
additionalVersionWeigth := expandFloat64Map(v.(map[string]interface{}))
return additionalVersionWeigth
}
}
return nil
}
func expandFloat64Map(m map[string]interface{}) map[string]float64 {
float64Map := make(map[string]float64, len(m))
for k, v := range m {
float64Map[k] = v.(float64)
}
return float64Map
}
func flattenFCAliasRoutingConfig(additionalVersionWeights map[string]float64) []interface{} {
if additionalVersionWeights == nil {
return []interface{}{}
}
m := map[string]interface{}{
"additional_version_weights": additionalVersionWeights,
}
return []interface{}{m}
}
package alicloud
import (
"encoding/json"
"fmt"
"log"
"time"
"github.com/aliyun/fc-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudFCCustomDomain() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudFCCustomDomainCreate,
Read: resourceAlicloudFCCustomDomainRead,
Update: resourceAlicloudFCCustomDomainUpdate,
Delete: resourceAlicloudFCCustomDomainDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"domain_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"protocol": {
Type: schema.TypeString,
Required: true,
},
"route_config": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"path": {
Type: schema.TypeString,
Required: true,
},
"service_name": {
Type: schema.TypeString,
Required: true,
},
"function_name": {
Type: schema.TypeString,
Required: true,
},
"qualifier": {
Type: schema.TypeString,
Optional: true,
},
"methods": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"cert_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cert_name": {
Type: schema.TypeString,
Required: true,
},
"private_key": {
Type: schema.TypeString,
Required: true,
Sensitive: true,
},
"certificate": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"account_id": {
Type: schema.TypeString,
Computed: true,
},
"api_version": {
Type: schema.TypeString,
Computed: true,
},
"created_time": {
Type: schema.TypeString,
Computed: true,
},
"last_modified_time": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudFCCustomDomainCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
name := d.Get("domain_name").(string)
request := &fc.CreateCustomDomainInput{
DomainName: StringPointer(name),
Protocol: StringPointer(d.Get("protocol").(string)),
}
request.WithRouteConfig(parseRouteConfig(d))
request.WithCertConfig(parseCertConfig(d))
var response *fc.CreateCustomDomainOutput
var requestInfo *fc.Client
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.CreateCustomDomain(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"AccessDenied"}) {
return resource.RetryableError(WrapError(err))
}
return resource.NonRetryableError(WrapError(err))
}
addDebug("CreateCusomDomain", raw, requestInfo, request)
response, _ = raw.(*fc.CreateCustomDomainOutput)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_fc_custom_domain", "CreateCustomDomain", FcGoSdk)
}
if response == nil {
return WrapError(Error("Creating function compute custom domain got a empty response"))
}
d.SetId(*response.DomainName)
return resourceAlicloudFCCustomDomainRead(d, meta)
}
func resourceAlicloudFCCustomDomainRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
fcService := FcService{client}
object, err := fcService.DescribeFcCustomDomain(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_fc_custom_domain fcService.DescribeFcCustomDomain Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("domain_name", object.DomainName)
d.Set("account_id", object.AccountID)
d.Set("protocol", object.Protocol)
d.Set("api_version", object.APIVersion)
d.Set("created_time", object.CreatedTime)
d.Set("last_modified_time", object.LastModifiedTime)
var routeConfig []map[string]interface{}
if object.RouteConfig != nil {
for _, v := range object.RouteConfig.Routes {
routeConfig = append(routeConfig, map[string]interface{}{
"path": *v.Path,
"service_name": *v.ServiceName,
"function_name": *v.FunctionName,
"qualifier": *v.Qualifier,
"methods": v.Methods,
})
}
}
if err := d.Set("route_config", routeConfig); err != nil {
return WrapError(err)
}
var certConfig []map[string]interface{}
if object.CertConfig != nil {
if object.CertConfig.CertName != nil && object.CertConfig.Certificate != nil {
oldConfig := d.Get("cert_config").([]interface{})
certConfig = append(certConfig, map[string]interface{}{
"cert_name": *object.CertConfig.CertName,
"certificate": *object.CertConfig.Certificate,
// The FC service will not return private key crendential for security reason.
// Read it from the terraform file.
"private_key": oldConfig[0].(map[string]interface{})["private_key"],
})
} else if object.CertConfig.CertName == nil && object.CertConfig.Certificate == nil {
// Skip the null cert config.
} else {
b, _ := json.Marshal(object)
return WrapError(Error(fmt.Sprintf("Illegal cert config: %s", string(b))))
}
}
if err := d.Set("cert_config", certConfig); err != nil {
return WrapError(err)
}
return nil
}
func resourceAlicloudFCCustomDomainUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
domainName := d.Id()
request := fc.NewUpdateCustomDomainInput(domainName)
update := false
if d.HasChange("protocol") {
update = true
request.Protocol = StringPointer(d.Get("protocol").(string))
}
if d.HasChange("route_config") {
update = true
request.WithRouteConfig(parseRouteConfig(d))
}
if d.HasChange("cert_config") {
update = true
request.WithCertConfig(parseCertConfig(d))
}
if update {
var requestInfo *fc.Client
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.UpdateCustomDomain(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "UpdateCustomDomain", FcGoSdk)
}
addDebug("UpdateCustomDomain", raw, requestInfo, request)
}
return resourceAlicloudFCCustomDomainRead(d, meta)
}
func resourceAlicloudFCCustomDomainDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
fcService := FcService{client}
domainName := d.Id()
request := fc.NewDeleteCustomDomainInput(domainName)
var requestInfo *fc.Client
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.DeleteCustomDomain(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"DomainNameNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, domainName, "DeleteCustomDomain", FcGoSdk)
}
addDebug("DeleteCustomDomain", raw, requestInfo, request)
return WrapError(fcService.WaitForFcCustomDomain(domainName, Deleted, DefaultTimeout))
}
func parseRouteConfig(d *schema.ResourceData) (config *fc.RouteConfig) {
if v, ok := d.GetOk("route_config"); ok {
routeList := v.([]interface{})
var pathConfigList []fc.PathConfig
for _, route := range routeList {
m := route.(map[string]interface{})
pathConfig := fc.NewPathConfig().
WithPath(m["path"].(string)).
WithServiceName(m["service_name"].(string)).
WithFunctionName(m["function_name"].(string)).
WithQualifier(m["qualifier"].(string)).
WithMethods(expandStringList(m["methods"].([]interface{})))
pathConfigList = append(pathConfigList, *pathConfig)
}
config = fc.NewRouteConfig().WithRoutes(pathConfigList)
}
return config
}
func parseCertConfig(d *schema.ResourceData) (config *fc.CertConfig) {
if v, ok := d.GetOk("cert_config"); ok {
m := v.([]interface{})[0].(map[string]interface{})
config = &fc.CertConfig{
CertName: StringPointer(m["cert_name"].(string)),
PrivateKey: StringPointer(m["private_key"].(string)),
Certificate: StringPointer(m["certificate"].(string)),
}
}
return config
}
package alicloud
import (
"encoding/json"
"fmt"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"strings"
"github.com/aliyun/fc-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudFCFunction() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudFCFunctionCreate,
Read: resourceAlicloudFCFunctionRead,
Update: resourceAlicloudFCFunctionUpdate,
Delete: resourceAlicloudFCFunctionDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"service": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"name_prefix"},
ValidateFunc: validation.StringLenBetween(1, 128),
},
"name_prefix": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(0, 122),
},
"oss_bucket": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"filename"},
},
"oss_key": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"filename"},
},
"filename": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"oss_bucket", "oss_key"},
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"code_checksum": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"environment_variables": {
Type: schema.TypeMap,
Optional: true,
},
"handler": {
Type: schema.TypeString,
Required: true,
},
"memory_size": {
Type: schema.TypeInt,
Optional: true,
Default: 128,
ValidateFunc: validation.IntBetween(128, 32768),
},
"runtime": {
Type: schema.TypeString,
Required: true,
},
"timeout": {
Type: schema.TypeInt,
Optional: true,
Default: 3,
},
"last_modified": {
Type: schema.TypeString,
Computed: true,
},
"function_id": {
Type: schema.TypeString,
Computed: true,
},
"initializer": {
Type: schema.TypeString,
Optional: true,
},
"initialization_timeout": {
Type: schema.TypeInt,
Optional: true,
Default: 3,
},
"instance_concurrency": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
},
"ca_port": {
Type: schema.TypeInt,
Optional: true,
},
"instance_type": {
Type: schema.TypeString,
Optional: true,
Default: "e1",
},
"custom_container_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"image": {
Type: schema.TypeString,
Required: true,
},
"command": {
Type: schema.TypeString,
Optional: true,
},
"args": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
},
}
}
func resourceAlicloudFCFunctionCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
serviceName := d.Get("service").(string)
var name string
if v, ok := d.GetOk("name"); ok {
name = v.(string)
} else if v, ok := d.GetOk("name_prefix"); ok {
name = resource.PrefixedUniqueId(v.(string))
} else {
name = resource.UniqueId()
}
request := &fc.CreateFunctionInput{
ServiceName: StringPointer(serviceName),
}
object := fc.FunctionCreateObject{
FunctionName: StringPointer(name),
Description: StringPointer(d.Get("description").(string)),
Runtime: StringPointer(d.Get("runtime").(string)),
Handler: StringPointer(d.Get("handler").(string)),
Timeout: Int32Pointer(int32(d.Get("timeout").(int))),
MemorySize: Int32Pointer(int32(d.Get("memory_size").(int))),
Initializer: StringPointer(d.Get("initializer").(string)),
InitializationTimeout: Int32Pointer(int32(d.Get("initialization_timeout").(int))),
InstanceType: StringPointer(d.Get("instance_type").(string)),
}
// Set function environment variables.
if variables := d.Get("environment_variables").(map[string]interface{}); len(variables) > 0 {
byteVar, err := json.Marshal(variables)
if err != nil {
return WrapError(err)
}
err = json.Unmarshal(byteVar, &object.EnvironmentVariables)
if err != nil {
return WrapError(err)
}
}
if strings.EqualFold(*object.Runtime, "custom-container") {
// Set custom container config.
cfg, err := parseCustomContainerConfig(d)
if err != nil {
return WrapError(err)
}
object.CustomContainerConfig = cfg
} else {
// Set function code.
code, err := getFunctionCode(d)
if err != nil {
return WrapError(err)
}
object.Code = code
}
// Set CA port if the runtime is custom runtime or custom container.
if strings.EqualFold(*object.Runtime, "custom") || strings.EqualFold(*object.Runtime, "custom-container") {
object.CAPort = Int32Pointer(int32(d.Get("ca_port").(int)))
}
// Disable instance concurrency for python runtime.
if !strings.EqualFold(*object.Runtime, "python2.7") && !strings.EqualFold(*object.Runtime, "python3") {
object.InstanceConcurrency = Int32Pointer(int32(d.Get("instance_concurrency").(int)))
}
request.FunctionCreateObject = object
var function *fc.CreateFunctionOutput
var requestInfo *fc.Client
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.CreateFunction(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"AccessDenied"}) {
return resource.RetryableError(WrapError(err))
}
return resource.NonRetryableError(WrapError(err))
}
addDebug("CreateFunction", raw, requestInfo, request)
function, _ = raw.(*fc.CreateFunctionOutput)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_fc_function", "CreateFunction", FcGoSdk)
}
if function == nil {
return WrapError(Error("Creating function compute function got a empty response"))
}
d.SetId(fmt.Sprintf("%s%s%s", serviceName, COLON_SEPARATED, *function.FunctionName))
return resourceAlicloudFCFunctionRead(d, meta)
}
func resourceAlicloudFCFunctionRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
fcService := FcService{client}
object, err := fcService.DescribeFcFunction(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("service", parts[0])
d.Set("code_checksum", object.CodeChecksum)
d.Set("name", object.FunctionName)
d.Set("function_id", object.FunctionID)
d.Set("description", object.Description)
d.Set("handler", object.Handler)
d.Set("memory_size", object.MemorySize)
d.Set("runtime", object.Runtime)
d.Set("timeout", object.Timeout)
d.Set("last_modified", object.LastModifiedTime)
d.Set("environment_variables", object.EnvironmentVariables)
d.Set("initializer", object.Initializer)
d.Set("initialization_timeout", object.InitializationTimeout)
d.Set("instance_concurrency", object.InstanceConcurrency)
d.Set("instance_type", object.InstanceType)
d.Set("ca_port", object.CAPort)
var customContainerConfig []map[string]interface{}
if object.CustomContainerConfig != nil {
customContainerConfig = append(customContainerConfig, map[string]interface{}{
"image": object.CustomContainerConfig.Image,
"command": object.CustomContainerConfig.Command,
"args": object.CustomContainerConfig.Args,
})
}
if err := d.Set("custom_container_config", customContainerConfig); err != nil {
return WrapError(err)
}
return nil
}
func resourceAlicloudFCFunctionUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := &fc.UpdateFunctionInput{}
update := false
if d.HasChange("filename") || d.HasChange("oss_bucket") || d.HasChange("oss_key") || d.HasChange("code_checksum") {
update = true
}
if d.HasChange("description") {
update = true
request.Description = StringPointer(d.Get("description").(string))
}
if d.HasChange("handler") {
update = true
request.Handler = StringPointer(d.Get("handler").(string))
}
if d.HasChange("memory_size") {
update = true
request.MemorySize = Int32Pointer(int32(d.Get("memory_size").(int)))
}
if d.HasChange("timeout") {
update = true
request.Timeout = Int32Pointer(int32(d.Get("timeout").(int)))
}
runtime := StringPointer(d.Get("runtime").(string))
if d.HasChange("runtime") {
update = true
request.Runtime = runtime
}
if d.HasChange("environment_variables") {
update = true
byteVar, err := json.Marshal(d.Get("environment_variables").(map[string]interface{}))
if err != nil {
return WrapError(err)
}
err = json.Unmarshal(byteVar, &request.EnvironmentVariables)
if err != nil {
return WrapError(err)
}
}
if d.HasChange("initializer") {
update = true
request.Initializer = StringPointer(d.Get("initializer").(string))
}
if d.HasChange("initialization_timeout") {
update = true
request.InitializationTimeout = Int32Pointer(int32(d.Get("initialization_timeout").(int)))
}
if d.HasChange("instance_concurrency") {
update = true
request.InstanceConcurrency = Int32Pointer(int32(d.Get("instance_concurrency").(int)))
}
if d.HasChange("instance_type") {
update = true
request.InstanceType = StringPointer(d.Get("instance_type").(string))
}
if d.HasChange("ca_port") {
update = true
request.CAPort = Int32Pointer(int32(d.Get("ca_port").(int)))
}
if d.HasChange("custom_container_config") {
update = true
config, err := parseCustomContainerConfig(d)
if err != nil {
return WrapError(err)
}
request.CustomContainerConfig = config
}
if update {
split := strings.Split(d.Id(), COLON_SEPARATED)
request.ServiceName = StringPointer(split[0])
request.FunctionName = StringPointer(split[1])
if !strings.EqualFold(*runtime, "custom-container") {
code, err := getFunctionCode(d)
if err != nil {
return WrapError(err)
}
request.Code = code
}
var requestInfo *fc.Client
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.UpdateFunction(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "UpdateFunction", FcGoSdk)
}
addDebug("UpdateFunction", raw, requestInfo, request)
}
return resourceAlicloudFCFunctionRead(d, meta)
}
func resourceAlicloudFCFunctionDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
fcService := FcService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request := &fc.DeleteFunctionInput{
ServiceName: StringPointer(parts[0]),
FunctionName: StringPointer(parts[1]),
}
var requestInfo *fc.Client
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.DeleteFunction(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ServiceNotFound", "FunctionNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DeleteFunction", FcGoSdk)
}
addDebug("DeleteFunction", raw, requestInfo, request)
return WrapError(fcService.WaitForFcFunction(d.Id(), Deleted, DefaultTimeout))
}
func getFunctionCode(d *schema.ResourceData) (*fc.Code, error) {
code := fc.NewCode()
if filename, ok := d.GetOk("filename"); ok && filename.(string) != "" {
file, err := loadFileContent(filename.(string))
if err != nil {
return code, WrapError(err)
}
code.WithZipFile(file)
} else {
bucket, bucketOk := d.GetOk("oss_bucket")
key, keyOk := d.GetOk("oss_key")
if !bucketOk || !keyOk {
return code, nil
}
code.WithOSSBucketName(bucket.(string)).WithOSSObjectName(key.(string))
}
return code, nil
}
// The first return value is nil when the "custom_container_config" is not been set.
func parseCustomContainerConfig(d *schema.ResourceData) (config *fc.CustomContainerConfig, err error) {
c := fc.NewCustomContainerConfig()
if v, ok := d.GetOk("custom_container_config"); ok {
config, ok := v.([]interface{})[0].(map[string]interface{})
if ok {
return c.WithImage(config["image"].(string)).WithCommand(config["command"].(string)).WithArgs(config["args"].(string)), nil
} else {
return nil, Error("Failed to parse custom_container_config")
}
}
// The "custom_container_config" has not been set.
return nil, nil
}
package alicloud
import (
"encoding/json"
"fmt"
"log"
"strings"
"time"
"github.com/aliyun/fc-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudFCFunctionAsyncInvokeConfig() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudFCAsyncInvokeConfigCreate,
Read: resourceAlicloudFCAsyncInvokeConfigRead,
Update: resourceAlicloudFCAsyncInvokeConfigUpdate,
Delete: resourceAlicloudFCAsyncInvokeConfigDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"service_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.NoZeroValues,
},
"function_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.NoZeroValues,
},
"qualifier": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "LATEST",
ValidateFunc: validation.NoZeroValues,
},
"maximum_event_age_in_seconds": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(60, 21600),
},
"maximum_retry_attempts": {
Type: schema.TypeInt,
Optional: true,
Default: 2,
ValidateFunc: validation.IntBetween(0, 2),
},
"destination_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"on_failure": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"destination": {
Type: schema.TypeString,
Required: true,
// TODO: Implement validateArn
//ValidateFunc: validateArn,
},
},
},
},
"on_success": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"destination": {
Type: schema.TypeString,
Required: true,
// TODO: Implement validateArn
//ValidateFunc: validateArn,
},
},
},
},
},
},
},
"created_time": {
Type: schema.TypeString,
Computed: true,
},
"last_modified_time": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudFCAsyncInvokeConfigCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
serviceName := d.Get("service_name").(string)
functionName := d.Get("function_name").(string)
qualifier := d.Get("qualifier").(string)
id := fmt.Sprintf("%s:%s:%s", serviceName, functionName, qualifier)
request := &fc.PutFunctionAsyncInvokeConfigInput{
ServiceName: StringPointer(serviceName),
FunctionName: StringPointer(functionName),
}
if v, ok := d.GetOk("maximum_retry_attempts"); ok {
request.MaxAsyncRetryAttempts = Int64Pointer(int64(v.(int)))
}
if v, ok := d.GetOk("destination_config"); ok {
request.DestinationConfig = parseFCDestinationConfig(v.([]interface{}))
}
if qualifier != "" {
request.Qualifier = StringPointer(qualifier)
}
if v, ok := d.GetOk("maximum_event_age_in_seconds"); ok {
request.MaxAsyncEventAgeInSeconds = Int64Pointer(int64(v.(int)))
}
var response *fc.PutFunctionAsyncInvokeConfigOutput
var requestInfo *fc.Client
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.PutFunctionAsyncInvokeConfig(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"AccessDenied"}) {
return resource.RetryableError(WrapError(err))
}
return resource.NonRetryableError(WrapError(err))
}
addDebug("PutFunctionAsyncInvokeConfig", raw, requestInfo, request)
response, _ = raw.(*fc.PutFunctionAsyncInvokeConfigOutput)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_fc_function_async_invoke_config", "PutFunctionAsyncInvokeConfig", FcGoSdk)
}
if response == nil {
return WrapError(Error("Putting function async invoke config got an empty response"))
}
d.SetId(id)
return resourceAlicloudFCAsyncInvokeConfigRead(d, meta)
}
func resourceAlicloudFCAsyncInvokeConfigRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
fcService := FcService{client}
object, err := fcService.DescribeFcFunctionAsyncInvokeConfig(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_fc_function_async_invoke_config: fcService.DescribeFcFunctionAsyncInvokeConfig Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
if err := d.Set("destination_config", flattenFCFunctionEventInvokeConfigDestinationConfig(object.DestinationConfig)); err != nil {
return WrapError(err)
}
d.Set("service_name", object.Service)
d.Set("function_name", object.Function)
d.Set("qualifier", object.Qualifier)
d.Set("maximum_event_age_in_seconds", object.MaxAsyncEventAgeInSeconds)
d.Set("maximum_retry_attempts", object.MaxAsyncRetryAttempts)
d.Set("created_time", object.CreatedTime)
d.Set("last_modified_time", object.LastModifiedTime)
return nil
}
func resourceAlicloudFCAsyncInvokeConfigUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
serviceName, functionName, qualifier, err := parseFCDestinationConfigId(d.Id())
if err != nil {
return WrapError(err)
}
request := &fc.PutFunctionAsyncInvokeConfigInput{
ServiceName: StringPointer(serviceName),
FunctionName: StringPointer(functionName),
}
request.MaxAsyncRetryAttempts = Int64Pointer(int64(d.Get("maximum_retry_attempts").(int)))
request.DestinationConfig = parseFCDestinationConfig(d.Get("destination_config").([]interface{}))
request.Qualifier = StringPointer(qualifier)
if v, ok := d.GetOk("maximum_event_age_in_seconds"); ok {
request.MaxAsyncEventAgeInSeconds = Int64Pointer(int64(v.(int)))
}
var response *fc.PutFunctionAsyncInvokeConfigOutput
var requestInfo *fc.Client
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.PutFunctionAsyncInvokeConfig(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"AccessDenied"}) {
return resource.RetryableError(WrapError(err))
}
return resource.NonRetryableError(WrapError(err))
}
addDebug("PutFunctionAsyncInvokeConfig", raw, requestInfo, request)
response, _ = raw.(*fc.PutFunctionAsyncInvokeConfigOutput)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_fc_function_async_invoke_config", "PutFunctionAsyncInvokeConfig", FcGoSdk)
}
if response == nil {
return WrapError(Error("Putting function async invoke config got an empty response"))
}
return resourceAlicloudFCAsyncInvokeConfigRead(d, meta)
}
func resourceAlicloudFCAsyncInvokeConfigDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
fcService := FcService{client}
serviceName, functionName, qualifier, err := parseFCDestinationConfigId(d.Id())
if err != nil {
return WrapError(err)
}
request := &fc.DeleteFunctionAsyncInvokeConfigInput{
ServiceName: &serviceName,
FunctionName: &functionName,
Qualifier: &qualifier,
}
var requestInfo *fc.Client
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.DeleteFunctionAsyncInvokeConfig(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"AsyncConfigNotExists"}) {
return nil
}
b, _ := json.Marshal(request)
return WrapErrorf(err, DefaultErrorMsg, string(b), "DeleteFunctionAsyncInvokeConfig", FcGoSdk)
}
addDebug("DeleteFunctionAsyncInvokeConfig", raw, requestInfo, request)
return WrapError(fcService.WaitForFcFunctionAsyncInvokeConfig(d.Id(), Deleted, DefaultTimeout))
}
func parseFCDestinationConfig(l []interface{}) *fc.DestinationConfig {
if len(l) == 0 || l[0] == nil {
return nil
}
config := &fc.DestinationConfig{}
m := l[0].(map[string]interface{})
if v, ok := m["on_failure"].([]interface{}); ok {
config.OnFailure = expandFCDestinationConfigOnFailure(v)
}
if v, ok := m["on_success"].([]interface{}); ok {
config.OnSuccess = expandFCDestinationConfigOnSuccess(v)
}
return config
}
func expandFCDestinationConfigOnSuccess(l []interface{}) *fc.Destination {
if len(l) == 0 || l[0] == nil {
return nil
}
m := l[0].(map[string]interface{})
var onSuccess *fc.Destination
if v, ok := m["destination"].(string); ok {
onSuccess = &fc.Destination{
Destination: StringPointer(v),
}
}
return onSuccess
}
func expandFCDestinationConfigOnFailure(l []interface{}) *fc.Destination {
if len(l) == 0 || l[0] == nil {
return nil
}
m := l[0].(map[string]interface{})
var onFailure *fc.Destination
if v, ok := m["destination"].(string); ok {
onFailure = &fc.Destination{
Destination: StringPointer(v),
}
}
return onFailure
}
func parseFCDestinationConfigId(id string) (serviceName string, functionName string, qualifier string, err error) {
idParts := strings.Split(id, ":")
if len(idParts) == 2 && idParts[0] != "" && idParts[1] != "" {
serviceName = idParts[0]
functionName = idParts[1]
return
}
if len(idParts) == 3 && idParts[0] != "" && idParts[1] != "" && idParts[2] != "" {
serviceName = idParts[0]
functionName = idParts[1]
qualifier = idParts[2]
return
}
return "", "", "", fmt.Errorf("unexpected format of ID (%s), expected service_name:function_name or service_name:function_name:qualifier", id)
}
func flattenFCFunctionEventInvokeConfigDestinationConfig(destinationConfig *fc.DestinationConfig) []interface{} {
// The API will respond with empty OnFailure and OnSuccess destinations when unconfigured:
// "DestinationConfig":{"OnFailure":{"Destination":null},"OnSuccess":{"Destination":null}}
// Return no destination configuration to prevent Terraform state difference
if destinationConfig == nil {
return []interface{}{}
}
if destinationConfig.OnFailure == nil && destinationConfig.OnSuccess == nil {
return []interface{}{}
}
if (destinationConfig.OnFailure != nil && destinationConfig.OnFailure.Destination == nil) && (destinationConfig.OnSuccess != nil && destinationConfig.OnSuccess.Destination == nil) {
return []interface{}{}
}
m := map[string]interface{}{
"on_failure": flattenFCFunctionEventInvokeConfigDestinationConfigOnFailure(destinationConfig.OnFailure),
"on_success": flattenFCFunctionEventInvokeConfigDestinationConfigOnSuccess(destinationConfig.OnSuccess),
}
return []interface{}{m}
}
func flattenFCFunctionEventInvokeConfigDestinationConfigOnFailure(onFailure *fc.Destination) []interface{} {
// The API will respond with empty OnFailure destination when unconfigured:
// "DestinationConfig":{"OnFailure":{"Destination":null},"OnSuccess":{"Destination":null}}
// Return no on failure configuration to prevent Terraform state difference
if onFailure == nil || onFailure.Destination == nil {
return []interface{}{}
}
m := map[string]interface{}{
"destination": *onFailure.Destination,
}
return []interface{}{m}
}
func flattenFCFunctionEventInvokeConfigDestinationConfigOnSuccess(onSuccess *fc.Destination) []interface{} {
// The API will respond with empty OnSuccess destination when unconfigured:
// "DestinationConfig":{"OnFailure":{"Destination":null},"OnSuccess":{"Destination":null}}
// Return no on success configuration to prevent Terraform state difference
if onSuccess == nil || onSuccess.Destination == nil {
return []interface{}{}
}
m := map[string]interface{}{
"destination": *onSuccess.Destination,
}
return []interface{}{m}
}
package alicloud
import (
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
sls "github.com/aliyun/aliyun-log-go-sdk"
"github.com/aliyun/fc-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudFCService() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudFCServiceCreate,
Read: resourceAlicloudFCServiceRead,
Update: resourceAlicloudFCServiceUpdate,
Delete: resourceAlicloudFCServiceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"name_prefix"},
ValidateFunc: validation.StringLenBetween(1, 128),
},
"name_prefix": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(0, 122),
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"internet_access": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"role": {
Type: schema.TypeString,
Optional: true,
},
"log_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"project": {
Type: schema.TypeString,
Required: true,
},
"logstore": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"vpc_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"vswitch_ids": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"security_group_id": {
Type: schema.TypeString,
Required: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"nas_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"user_id": {
Type: schema.TypeInt,
Required: true,
},
"group_id": {
Type: schema.TypeInt,
Required: true,
},
"mount_points": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"server_addr": {
Type: schema.TypeString,
Required: true,
},
"mount_dir": {
Type: schema.TypeString,
Required: true,
},
},
},
},
},
},
},
"publish": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"version": {
Type: schema.TypeString,
Computed: true,
},
"last_modified": {
Type: schema.TypeString,
Computed: true,
},
"service_id": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudFCServiceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var name string
if v, ok := d.GetOk("name"); ok {
name = v.(string)
} else if v, ok := d.GetOk("name_prefix"); ok {
name = resource.PrefixedUniqueId(v.(string))
} else {
name = resource.UniqueId()
}
project, logstore, err := parseLogConfig(d, meta)
if err != nil {
return WrapError(err)
}
request := &fc.CreateServiceInput{
ServiceName: StringPointer(name),
Description: StringPointer(d.Get("description").(string)),
InternetAccess: BoolPointer(d.Get("internet_access").(bool)),
Role: StringPointer(d.Get("role").(string)),
LogConfig: &fc.LogConfig{
Project: StringPointer(project),
Logstore: StringPointer(logstore),
},
}
vpcConfig, err := parseVpcConfig(d, meta)
if err != nil {
return WrapError(err)
}
request.VPCConfig = vpcConfig
nasConfig, err := parseNasConfig(d)
if err != nil {
return WrapError(err)
}
request.NASConfig = nasConfig
var requestInfo *fc.Client
var response *fc.CreateServiceOutput
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.CreateService(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"AccessDenied", "does not exist"}) {
return resource.RetryableError(err)
}
// Work around the "log project doest not exist" error since SLS log project CRUD is not strong consistency.
if e, ok := err.(*fc.ServiceError); ok {
if r := regexp.MustCompile("project.*does not exist"); e.ErrorCode == "InvalidArgument" && r.MatchString(e.ErrorMessage) {
return resource.RetryableError(err)
}
}
return resource.NonRetryableError(err)
}
addDebug("CreateService", raw, requestInfo, request)
response, _ = raw.(*fc.CreateServiceOutput)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_fc_service", "CreateService", FcGoSdk)
}
d.SetId(*response.ServiceName)
etag := response.Header.Get("ETag")
if d.Get("publish").(bool) {
input := &fc.PublishServiceVersionInput{
ServiceName: response.ServiceName,
IfMatch: &etag,
}
input.Description = response.Description
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.PublishServiceVersion(input)
})
if err != nil {
if IsExpectedErrors(err, []string{"AccessDenied", "ServiceNotFound"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug("PublishServiceVersion", raw, requestInfo, request)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_fc_service", "PublishServiceVersion", FcGoSdk)
}
}
return resourceAlicloudFCServiceRead(d, meta)
}
func resourceAlicloudFCServiceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
fcService := FcService{client}
object, err := fcService.DescribeFcService(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", object.ServiceName)
d.Set("service_id", object.ServiceID)
d.Set("description", object.Description)
d.Set("internet_access", object.InternetAccess)
d.Set("role", object.Role)
var logConfigs []map[string]interface{}
if logconfig := object.LogConfig; logconfig != nil && *logconfig.Project != "" {
logConfigs = append(logConfigs, map[string]interface{}{
"project": *logconfig.Project,
"logstore": *logconfig.Logstore,
})
}
if err := d.Set("log_config", logConfigs); err != nil {
return WrapError(err)
}
var vpcConfigs []map[string]interface{}
if vpcConfig := object.VPCConfig; vpcConfig != nil && *vpcConfig.VPCID != "" {
vpcConfigs = append(vpcConfigs, map[string]interface{}{
"vswitch_ids": schema.NewSet(schema.HashString, convertListStringToListInterface(vpcConfig.VSwitchIDs)),
"security_group_id": *vpcConfig.SecurityGroupID,
"vpc_id": *vpcConfig.VPCID,
})
}
if err := d.Set("vpc_config", vpcConfigs); err != nil {
return WrapError(err)
}
var nasConfigs []map[string]interface{}
if cfg := object.NASConfig; cfg != nil && len(cfg.MountPoints) != 0 {
dstCfg := make(map[string]interface{})
dstCfg["user_id"] = cfg.UserID
dstCfg["group_id"] = cfg.GroupID
var mps []map[string]interface{}
for _, v := range cfg.MountPoints {
mps = append(mps, map[string]interface{}{
"server_addr": v.ServerAddr,
"mount_dir": v.MountDir,
})
}
dstCfg["mount_points"] = mps
nasConfigs = append(nasConfigs, dstCfg)
}
if err := d.Set("nas_config", nasConfigs); err != nil {
return WrapError(err)
}
d.Set("last_modified", object.LastModifiedTime)
// Get the latest version of the service.
input := &fc.ListServiceVersionsInput{
ServiceName: object.ServiceName,
Limit: Int32Pointer(1),
Direction: StringPointer("BACKWARD"),
}
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
var requestInfo *fc.Client
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.ListServiceVersions(input)
})
if err != nil {
if IsExpectedErrors(err, []string{"AccessDenied", "ServiceNotFound"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug("ListServiceVersions", raw, requestInfo, input)
output, _ := raw.(*fc.ListServiceVersionsOutput)
if len(output.Versions) > 0 {
d.Set("version", output.Versions[0].VersionID)
}
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_fc_service", "PublishServiceVersion", FcGoSdk)
}
return nil
}
func resourceAlicloudFCServiceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
d.Partial(true)
request := &fc.UpdateServiceInput{}
if d.HasChange("role") {
request.Role = StringPointer(d.Get("role").(string))
d.SetPartial("role")
}
if d.HasChange("internet_access") {
request.InternetAccess = BoolPointer(d.Get("internet_access").(bool))
d.SetPartial("internet_access")
}
if d.HasChange("description") {
request.Description = StringPointer(d.Get("description").(string))
d.SetPartial("description")
}
if d.HasChange("log_config") {
project, logstore, err := parseLogConfig(d, meta)
if err != nil {
return WrapError(err)
}
request.LogConfig = &fc.LogConfig{
Project: StringPointer(project),
Logstore: StringPointer(logstore),
}
d.SetPartial("log_config")
}
if d.HasChange("vpc_config") {
vpcConfig, err := parseVpcConfig(d, meta)
if err != nil {
return WrapError(err)
}
request.VPCConfig = vpcConfig
d.SetPartial("vpc_config")
}
if d.HasChange("nas_config") {
nasConfig, err := parseNasConfig(d)
if err != nil {
return WrapError(err)
}
request.NASConfig = nasConfig
d.SetPartial("nas_config")
}
if request != nil {
request.ServiceName = StringPointer(d.Id())
var requestInfo *fc.Client
var response *fc.UpdateServiceOutput
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.UpdateService(request)
})
if err != nil {
// Work around the "log project doest not exist" error since SLS log project CRUD is not strong consistency.
if e, ok := err.(*fc.ServiceError); ok {
if r := regexp.MustCompile("project.*does not exist"); e.ErrorCode == "InvalidArgument" && r.MatchString(e.ErrorMessage) {
return resource.RetryableError(err)
}
}
return resource.NonRetryableError(err)
}
addDebug("UpdateService", raw, requestInfo, request)
response, _ = raw.(*fc.UpdateServiceOutput)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_fc_service", "UpdateService", FcGoSdk)
}
etag := response.Header.Get("ETag")
if d.Get("publish").(bool) {
input := &fc.PublishServiceVersionInput{
ServiceName: response.ServiceName,
IfMatch: &etag,
}
input.Description = response.Description
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.PublishServiceVersion(input)
})
if err != nil {
if IsExpectedErrors(err, []string{"AccessDenied", "ServiceNotFound"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug("PublishServiceVersion", raw, requestInfo, request)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_fc_service", "PublishServiceVersion", FcGoSdk)
}
}
}
d.Partial(false)
return resourceAlicloudFCServiceRead(d, meta)
}
func resourceAlicloudFCServiceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
fcService := FcService{client}
// Delete the service versions.
var nextToken *string
for {
input := &fc.ListServiceVersionsInput{
ServiceName: StringPointer(d.Id()),
Limit: Int32Pointer(100),
NextToken: nextToken,
}
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
return fcClient.ListServiceVersions(input)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "ListServiceVersions", FcGoSdk)
}
output := raw.(*fc.ListServiceVersionsOutput)
nextToken = output.NextToken
for _, v := range output.Versions {
// Delete the service version.
input := &fc.DeleteServiceVersionInput{
ServiceName: StringPointer(d.Id()),
VersionID: v.VersionID,
}
_, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
return fcClient.DeleteServiceVersion(input)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), v.VersionID, "DeleteServiceVersion", FcGoSdk)
}
}
if nextToken == nil || *nextToken == "" {
break
}
}
// Delete the service.
request := &fc.DeleteServiceInput{
ServiceName: StringPointer(d.Id()),
}
var requestInfo *fc.Client
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.DeleteService(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ServiceNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DeleteService", FcGoSdk)
}
addDebug("DeleteService", raw, requestInfo, request)
return WrapError(fcService.WaitForFcService(d.Id(), Deleted, DefaultTimeout))
}
func parseVpcConfig(d *schema.ResourceData, meta interface{}) (config *fc.VPCConfig, err error) {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
if v, ok := d.GetOk("vpc_config"); ok {
confs := v.([]interface{})
conf, ok := confs[0].(map[string]interface{})
if !ok {
return
}
if role, ok := d.GetOk("role"); !ok || role.(string) == "" {
err = WrapError(Error("'role' is required when 'vpc_config' is set."))
return
}
if conf != nil {
vswitchIds := conf["vswitch_ids"].(*schema.Set).List()
vsw, e := vpcService.DescribeVSwitch(vswitchIds[0].(string))
if e != nil {
err = WrapError(e)
return
}
config = &fc.VPCConfig{
VSwitchIDs: expandStringList(vswitchIds),
SecurityGroupID: StringPointer(conf["security_group_id"].(string)),
VPCID: StringPointer(vsw.VpcId),
}
}
}
return
}
func parseLogConfig(d *schema.ResourceData, meta interface{}) (project, logstore string, err error) {
client := meta.(*connectivity.AliyunClient)
if v, ok := d.GetOk("log_config"); ok {
configs := v.([]interface{})
config, ok := configs[0].(map[string]interface{})
if !ok {
return
}
if config != nil {
project = config["project"].(string)
logstore = config["logstore"].(string)
}
}
if project != "" {
var requestInfo *sls.Client
err = resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, e := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return slsClient.CheckProjectExist(project)
})
if e != nil {
if NotFoundError(e) {
return resource.RetryableError(e)
}
return resource.NonRetryableError(e)
}
addDebug("CheckProjectExist", raw, requestInfo, project)
return nil
})
}
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, d.Id(), "CheckProjectExist", FcGoSdk)
return
}
if logstore != "" {
err = resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, e := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
return slsClient.CheckLogstoreExist(project, logstore)
})
if e != nil {
if NotFoundError(e) {
return resource.RetryableError(e)
}
return resource.NonRetryableError(e)
}
addDebug("CheckLogstoreExist", raw)
return nil
})
}
return
}
func parseNasConfig(d *schema.ResourceData) (config *fc.NASConfig, err error) {
if v, ok := d.GetOk("nas_config"); ok {
config = fc.NewNASConfig()
c, ok := v.([]interface{})[0].(map[string]interface{})
if !ok {
return nil, Error("Failed to parse nas config.")
}
config.UserID = Int32Pointer(int32(c["user_id"].(int)))
config.GroupID = Int32Pointer(int32(c["group_id"].(int)))
if mps, ok := c["mount_points"].([]interface{}); ok {
for _, mp := range mps {
m := mp.(map[string]interface{})
config.MountPoints = append(config.MountPoints, fc.NASMountConfig{
ServerAddr: m["server_addr"].(string),
MountDir: m["mount_dir"].(string),
})
}
} else {
return nil, Error("Failed to parse mount points.")
}
}
return
}
package alicloud
import (
"encoding/json"
"fmt"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/fc-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudFCTrigger() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudFCTriggerCreate,
Read: resourceAlicloudFCTriggerRead,
Update: resourceAlicloudFCTriggerUpdate,
Delete: resourceAlicloudFCTriggerDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"service": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"function": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"name_prefix"},
ValidateFunc: validation.StringLenBetween(1, 128),
},
"name_prefix": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(0, 122),
},
"role": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("type").(string) == "timer"
},
},
"source_arn": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"config": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
// The read config is json rawMessage and it does not contains space and enter.
if d.Get("type").(string) == string(fc.TRIGGER_TYPE_MNS_TOPIC) {
return true
}
if d.Get("type").(string) == string(fc.TRIGGER_TYPE_TIMER) {
resolvedNew, err := delEmptyPayloadIfExist(removeSpaceAndEnter(new))
if err != nil {
panic(err)
}
resolvedOld, err := delEmptyPayloadIfExist(removeSpaceAndEnter(old))
if err != nil {
panic(err)
}
return resolvedOld == resolvedNew
}
resolvedNew, err := resolveFcTriggerConfig(removeSpaceAndEnter(new))
if err != nil {
panic(err)
}
resolvedOld, err := resolveFcTriggerConfig(removeSpaceAndEnter(old))
if err != nil {
panic(err)
}
return resolvedNew == resolvedOld
},
ValidateFunc: validation.ValidateJsonString,
},
//Modifying config is not supported when type is mns_topic
"config_mns": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
// The read config is json rawMessage and it does not contains space and enter.
return old == removeSpaceAndEnter(new)
},
ValidateFunc: validation.ValidateJsonString,
ConflictsWith: []string{"config"},
},
"type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{fc.TRIGGER_TYPE_HTTP, fc.TRIGGER_TYPE_LOG, fc.TRIGGER_TYPE_OSS, fc.TRIGGER_TYPE_TIMER, fc.TRIGGER_TYPE_MNS_TOPIC, fc.TRIGGER_TYPE_CDN_EVENTS}, false),
},
"last_modified": {
Type: schema.TypeString,
Computed: true,
},
"trigger_id": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudFCTriggerCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
serviceName := d.Get("service").(string)
fcName := d.Get("function").(string)
var name string
if v, ok := d.GetOk("name"); ok {
name = v.(string)
} else if v, ok := d.GetOk("name_prefix"); ok {
name = resource.PrefixedUniqueId(v.(string))
} else {
name = resource.UniqueId()
}
var config interface{}
if d.Get("type").(string) == string(fc.TRIGGER_TYPE_MNS_TOPIC) {
if v, ok := d.GetOk("config_mns"); ok {
if err := json.Unmarshal([]byte(v.(string)), &config); err != nil {
return WrapError(err)
}
}
} else {
if v, ok := d.GetOk("config"); ok {
if err := json.Unmarshal([]byte(v.(string)), &config); err != nil {
return WrapError(err)
}
}
}
object := fc.TriggerCreateObject{
TriggerName: StringPointer(name),
TriggerType: StringPointer(d.Get("type").(string)),
InvocationRole: StringPointer(d.Get("role").(string)),
TriggerConfig: config,
}
if v, ok := d.GetOk("source_arn"); ok && v.(string) != "" {
object.SourceARN = StringPointer(v.(string))
}
request := &fc.CreateTriggerInput{
ServiceName: StringPointer(serviceName),
FunctionName: StringPointer(fcName),
TriggerCreateObject: object,
}
var response *fc.CreateTriggerOutput
var requestInfo *fc.Client
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.CreateTrigger(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"AccessDenied"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug("CreateTrigger", raw, requestInfo, request)
response, _ = raw.(*fc.CreateTriggerOutput)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_fc_trigger", "CreateTrigger", FcGoSdk)
}
d.SetId(fmt.Sprintf("%s%s%s%s%s", serviceName, COLON_SEPARATED, fcName, COLON_SEPARATED, *response.TriggerName))
return resourceAlicloudFCTriggerRead(d, meta)
}
func resourceAlicloudFCTriggerRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
fcService := FcService{client}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
trigger, err := fcService.DescribeFcTrigger(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("service", parts[0])
d.Set("function", parts[1])
d.Set("name", trigger.TriggerName)
d.Set("trigger_id", trigger.TriggerID)
d.Set("role", trigger.InvocationRole)
d.Set("source_arn", trigger.SourceARN)
data, err := trigger.RawTriggerConfig.MarshalJSON()
if err != nil {
return WrapError(err)
}
if d.Get("type").(string) == string(fc.TRIGGER_TYPE_MNS_TOPIC) {
if err := d.Set("config_mns", string(data)); err != nil {
return WrapError(err)
}
} else {
if err := d.Set("config", string(data)); err != nil {
return WrapError(err)
}
}
d.Set("type", trigger.TriggerType)
d.Set("last_modified", trigger.LastModifiedTime)
return nil
}
func resourceAlicloudFCTriggerUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
updateInput := &fc.UpdateTriggerInput{}
if d.HasChange("role") {
updateInput.InvocationRole = StringPointer(d.Get("role").(string))
}
if d.HasChange("config") {
var config interface{}
if err := json.Unmarshal([]byte(d.Get("config").(string)), &config); err != nil {
return WrapError(err)
}
updateInput.TriggerConfig = config
}
if updateInput != nil {
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
updateInput.ServiceName = StringPointer(parts[0])
updateInput.FunctionName = StringPointer(parts[1])
updateInput.TriggerName = StringPointer(parts[2])
var requestInfo *fc.Client
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.UpdateTrigger(updateInput)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "UpdateTrigger", FcGoSdk)
}
addDebug("UpdateTrigger", raw, requestInfo, updateInput)
}
return resourceAlicloudFCTriggerRead(d, meta)
}
func resourceAlicloudFCTriggerDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
fcService := FcService{client}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
request := &fc.DeleteTriggerInput{
ServiceName: StringPointer(parts[0]),
FunctionName: StringPointer(parts[1]),
TriggerName: StringPointer(parts[2]),
}
var requestInfo *fc.Client
raw, err := client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.DeleteTrigger(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ServiceNotFound", "FunctionNotFound", "TriggerNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DeleteTrigger", FcGoSdk)
}
addDebug("DeleteTrigger", raw, requestInfo, request)
return WrapError(fcService.WaitForFcTrigger(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudFnFExecution() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudFnFExecutionCreate,
Read: resourceAlicloudFnFExecutionRead,
Update: resourceAlicloudFnFExecutionUpdate,
Delete: resourceAlicloudFnFExecutionDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
Update: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"execution_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"flow_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"input": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.ValidateJsonString,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
equal, _ := compareJsonTemplateAreEquivalent(old, new)
return equal
},
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Stopped"}, false),
},
},
}
}
func resourceAlicloudFnFExecutionCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "StartExecution"
request := make(map[string]interface{})
conn, err := client.NewFnfClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("execution_name"); ok {
request["ExecutionName"] = v
}
request["FlowName"] = d.Get("flow_name")
if v, ok := d.GetOk("input"); ok {
request["Input"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_fnf_execution", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["FlowName"], ":", request["ExecutionName"]))
fnfService := FnfService{client}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, fnfService.FnFExecutionStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudFnFExecutionUpdate(d, meta)
}
func resourceAlicloudFnFExecutionRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
fnfService := FnfService{client}
object, err := fnfService.DescribeFnFExecution(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_fnf_execution fnfService.DescribeFnFExecution Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("execution_name", parts[1])
d.Set("flow_name", parts[0])
d.Set("input", object["Input"])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudFnFExecutionUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
fnfService := FnfService{client}
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Partial(true)
if d.HasChange("status") {
object, err := fnfService.DescribeFnFExecution(d.Id())
if err != nil {
return WrapError(err)
}
target := d.Get("status").(string)
if object["Status"].(string) != target {
if target == "Stopped" {
request := map[string]interface{}{
"ExecutionName": parts[1],
"FlowName": parts[0],
}
action := "StopExecution"
conn, err := client.NewFnfClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Stopped"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, fnfService.FnFExecutionStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.SetPartial("status")
}
}
d.Partial(false)
return resourceAlicloudFnFExecutionRead(d, meta)
}
func resourceAlicloudFnFExecutionDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudFnFExecution. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudFnfFlow() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudFnfFlowCreate,
Read: resourceAlicloudFnfFlowRead,
Update: resourceAlicloudFnfFlowUpdate,
Delete: resourceAlicloudFnfFlowDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
Delete: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"definition": {
Type: schema.TypeString,
Required: true,
},
"description": {
Type: schema.TypeString,
Required: true,
},
"flow_id": {
Type: schema.TypeString,
Computed: true,
},
"last_modified_time": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"role_arn": {
Type: schema.TypeString,
Optional: true,
},
"type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"DEFAULT", "FDL"}, false),
},
},
}
}
func resourceAlicloudFnfFlowCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateFlow"
request := make(map[string]interface{})
conn, err := client.NewFnfClient()
if err != nil {
return WrapError(err)
}
request["Definition"] = d.Get("definition")
request["Description"] = d.Get("description")
request["Name"] = d.Get("name")
if v, ok := d.GetOk("role_arn"); ok {
request["RoleArn"] = v
}
request["Type"] = d.Get("type")
wait := incrementalWait(3*time.Second, 1*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"InternalServerError"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_fnf_flow", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["Name"]))
return resourceAlicloudFnfFlowRead(d, meta)
}
func resourceAlicloudFnfFlowRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
fnfService := FnfService{client}
object, err := fnfService.DescribeFnfFlow(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_fnf_flow fnfService.DescribeFnfFlow Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", d.Id())
d.Set("definition", object["Definition"])
d.Set("description", object["Description"])
d.Set("flow_id", object["Id"])
d.Set("last_modified_time", object["LastModifiedTime"])
d.Set("role_arn", object["RoleArn"])
d.Set("type", object["Type"])
return nil
}
func resourceAlicloudFnfFlowUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"Name": d.Id(),
}
if d.HasChange("definition") {
update = true
request["Definition"] = d.Get("definition")
}
if d.HasChange("description") {
update = true
request["Description"] = d.Get("description")
}
if d.HasChange("role_arn") {
update = true
request["RoleArn"] = d.Get("role_arn")
}
if d.HasChange("type") {
update = true
request["Type"] = d.Get("type")
}
if update {
action := "UpdateFlow"
conn, err := client.NewFnfClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 1*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ConcurrentUpdateError", "InternalServerError"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudFnfFlowRead(d, meta)
}
func resourceAlicloudFnfFlowDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteFlow"
var response map[string]interface{}
conn, err := client.NewFnfClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"Name": d.Id(),
}
wait := incrementalWait(3*time.Second, 1*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-03-15"), StringPointer("AK"), request, nil, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"InternalServerError"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"FlowNotExists"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudFnfSchedule() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudFnfScheduleCreate,
Read: resourceAlicloudFnfScheduleRead,
Update: resourceAlicloudFnfScheduleUpdate,
Delete: resourceAlicloudFnfScheduleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
Delete: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"cron_expression": {
Type: schema.TypeString,
Required: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"enable": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"flow_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"last_modified_time": {
Type: schema.TypeString,
Computed: true,
},
"payload": {
Type: schema.TypeString,
Optional: true,
},
"schedule_id": {
Type: schema.TypeString,
Computed: true,
},
"schedule_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudFnfScheduleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateSchedule"
request := make(map[string]interface{})
conn, err := client.NewFnfClient()
if err != nil {
return WrapError(err)
}
request["CronExpression"] = d.Get("cron_expression")
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOkExists("enable"); ok {
request["Enable"] = v
}
request["FlowName"] = d.Get("flow_name")
if v, ok := d.GetOk("payload"); ok {
request["Payload"] = v
}
request["ScheduleName"] = d.Get("schedule_name")
wait := incrementalWait(3*time.Second, 1*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ConcurrentUpdateError", "InternalServerError"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_fnf_schedule", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["FlowName"], ":", response["ScheduleName"]))
return resourceAlicloudFnfScheduleRead(d, meta)
}
func resourceAlicloudFnfScheduleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
fnfService := FnfService{client}
object, err := fnfService.DescribeFnfSchedule(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_fnf_schedule fnfService.DescribeFnfSchedule Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("flow_name", parts[0])
d.Set("schedule_name", parts[1])
d.Set("cron_expression", object["CronExpression"])
d.Set("description", object["Description"])
d.Set("enable", object["Enable"])
d.Set("last_modified_time", object["LastModifiedTime"])
d.Set("payload", object["Payload"])
d.Set("schedule_id", object["ScheduleId"])
return nil
}
func resourceAlicloudFnfScheduleUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"FlowName": parts[0],
"ScheduleName": parts[1],
}
if d.HasChange("cron_expression") {
update = true
request["CronExpression"] = d.Get("cron_expression")
}
if d.HasChange("description") {
update = true
request["Description"] = d.Get("description")
}
if d.HasChange("enable") {
update = true
request["Enable"] = d.Get("enable")
}
if d.HasChange("payload") {
update = true
request["Payload"] = d.Get("payload")
}
if update {
action := "UpdateSchedule"
conn, err := client.NewFnfClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 1*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ConcurrentUpdateError", "InternalServerError"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudFnfScheduleRead(d, meta)
}
func resourceAlicloudFnfScheduleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteSchedule"
var response map[string]interface{}
conn, err := client.NewFnfClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"FlowName": parts[0],
"ScheduleName": parts[1],
}
wait := incrementalWait(3*time.Second, 1*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-03-15"), StringPointer("AK"), request, nil, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ConcurrentUpdateError", "InternalServerError"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ExecutionNotExists", "FlowNotExists", "ScheduleNotExists"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudForwardEntry() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudForwardEntryCreate,
Read: resourceAlicloudForwardEntryRead,
Update: resourceAlicloudForwardEntryUpdate,
Delete: resourceAlicloudForwardEntryDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"external_ip": {
Type: schema.TypeString,
Required: true,
},
"external_port": {
Type: schema.TypeString,
Required: true,
},
"forward_entry_id": {
Type: schema.TypeString,
Computed: true,
},
"forward_entry_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"name"},
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Field 'name' has been deprecated from provider version 1.119.1. New field 'forward_entry_name' instead.",
ConflictsWith: []string{"forward_entry_name"},
},
"forward_table_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"internal_ip": {
Type: schema.TypeString,
Required: true,
},
"internal_port": {
Type: schema.TypeString,
Required: true,
},
"ip_protocol": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"any", "tcp", "udp"}, false),
},
"port_break": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudForwardEntryCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
action := "CreateForwardEntry"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request["ExternalIp"] = d.Get("external_ip")
request["ExternalPort"] = d.Get("external_port")
if v, ok := d.GetOk("forward_entry_name"); ok {
request["ForwardEntryName"] = v
} else if v, ok := d.GetOk("name"); ok {
request["ForwardEntryName"] = v
}
request["ForwardTableId"] = d.Get("forward_table_id")
request["InternalIp"] = d.Get("internal_ip")
request["InternalPort"] = d.Get("internal_port")
request["IpProtocol"] = d.Get("ip_protocol")
if v, ok := d.GetOkExists("port_break"); ok {
request["PortBreak"] = v
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidIp.NotInNatgw"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_forward_entry", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["ForwardTableId"], ":", response["ForwardEntryId"]))
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, vpcService.ForwardEntryStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudForwardEntryRead(d, meta)
}
func resourceAlicloudForwardEntryRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
if !strings.Contains(d.Id(), COLON_SEPARATED) {
d.SetId(d.Get("forward_table_id").(string) + COLON_SEPARATED + d.Id())
}
object, err := vpcService.DescribeForwardEntry(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_forward_entry vpcService.DescribeForwardEntry Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("forward_entry_id", parts[1])
d.Set("forward_table_id", parts[0])
d.Set("external_ip", object["ExternalIp"])
d.Set("external_port", object["ExternalPort"])
d.Set("forward_entry_name", object["ForwardEntryName"])
d.Set("name", object["ForwardEntryName"])
d.Set("internal_ip", object["InternalIp"])
d.Set("internal_port", object["InternalPort"])
d.Set("ip_protocol", object["IpProtocol"])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudForwardEntryUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if !strings.Contains(d.Id(), COLON_SEPARATED) {
d.SetId(d.Get("forward_table_id").(string) + COLON_SEPARATED + d.Id())
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"ForwardEntryId": parts[1],
"ForwardTableId": parts[0],
}
request["RegionId"] = client.RegionId
if d.HasChange("external_ip") {
update = true
request["ExternalIp"] = d.Get("external_ip")
}
if d.HasChange("external_port") {
update = true
request["ExternalPort"] = d.Get("external_port")
}
if d.HasChange("forward_entry_name") {
update = true
request["ForwardEntryName"] = d.Get("forward_entry_name")
}
if d.HasChange("name") {
update = true
request["ForwardEntryName"] = d.Get("name")
}
if d.HasChange("internal_ip") {
update = true
request["InternalIp"] = d.Get("internal_ip")
}
if d.HasChange("internal_port") {
update = true
request["InternalPort"] = d.Get("internal_port")
}
if d.HasChange("ip_protocol") {
update = true
request["IpProtocol"] = d.Get("ip_protocol")
}
if update {
if _, ok := d.GetOkExists("port_break"); ok {
request["PortBreak"] = d.Get("port_break")
}
action := "ModifyForwardEntry"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, vpcService.ForwardEntryStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudForwardEntryRead(d, meta)
}
func resourceAlicloudForwardEntryDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
if !strings.Contains(d.Id(), COLON_SEPARATED) {
d.SetId(d.Get("forward_table_id").(string) + COLON_SEPARATED + d.Id())
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
vpcService := VpcService{client}
action := "DeleteForwardEntry"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ForwardEntryId": parts[1],
"ForwardTableId": parts[0],
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"UnknownError"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidForwardEntryId.NotFound", "InvalidForwardTableId.NotFound", "InvalidRegionId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, vpcService.ForwardEntryStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudGaAccelerator() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudGaAcceleratorCreate,
Read: resourceAlicloudGaAcceleratorRead,
Update: resourceAlicloudGaAcceleratorUpdate,
Delete: resourceAlicloudGaAcceleratorDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(6 * time.Minute),
},
Schema: map[string]*schema.Schema{
"accelerator_name": {
Type: schema.TypeString,
Optional: true,
},
"auto_renew_duration": {
Type: schema.TypeInt,
Optional: true,
},
"auto_use_coupon": {
Type: schema.TypeBool,
Optional: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"duration": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(1, 9),
},
"pricing_cycle": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Month", "Year"}, false),
},
"renewal_status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{
string(RenewAutoRenewal),
string(RenewNormal),
string(RenewNotRenewal)}, false),
},
"spec": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"1", "10", "2", "3", "5", "8"}, false),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudGaAcceleratorCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
var response map[string]interface{}
action := "CreateAccelerator"
request := make(map[string]interface{})
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
// there is an api bug that the name can not effect
//if v, ok := d.GetOk("accelerator_name"); ok {
// request["Name"] = v
//}
request["AutoPay"] = true
if v, ok := d.GetOkExists("auto_use_coupon"); ok {
request["AutoUseCoupon"] = v
}
request["Duration"] = d.Get("duration")
if v, ok := d.GetOk("pricing_cycle"); ok {
request["PricingCycle"] = v
} else {
request["PricingCycle"] = "Month"
}
request["RegionId"] = client.RegionId
request["Spec"] = d.Get("spec")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("CreateAccelerator")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ga_accelerator", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetId(fmt.Sprint(response["AcceleratorId"]))
stateConf := BuildStateConf([]string{}, []string{"active"}, d.Timeout(schema.TimeoutCreate), 30*time.Second, gaService.GaAcceleratorStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudGaAcceleratorUpdate(d, meta)
}
func resourceAlicloudGaAcceleratorRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
object, err := gaService.DescribeGaAccelerator(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ga_accelerator gaService.DescribeGaAccelerator Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("accelerator_name", object["Name"])
d.Set("description", object["Description"])
d.Set("spec", object["Spec"])
d.Set("status", object["State"])
describeAcceleratorAutoRenewAttributeObject, err := gaService.DescribeAcceleratorAutoRenewAttribute(d.Id())
if err != nil {
return WrapError(err)
}
if v, ok := describeAcceleratorAutoRenewAttributeObject["AutoRenewDuration"]; ok && fmt.Sprint(v) != "0" {
d.Set("auto_renew_duration", formatInt(v))
}
d.Set("renewal_status", describeAcceleratorAutoRenewAttributeObject["RenewalStatus"])
return nil
}
func resourceAlicloudGaAcceleratorUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
var response map[string]interface{}
d.Partial(true)
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"AcceleratorId": d.Id(),
}
if d.HasChange("auto_renew_duration") {
update = true
}
if v, ok := d.GetOk("auto_renew_duration"); ok {
request["AutoRenewDuration"] = v
}
request["RegionId"] = client.RegionId
if d.HasChange("renewal_status") {
update = true
}
if v, ok := d.GetOk("renewal_status"); ok {
request["RenewalStatus"] = v
}
if update {
action := "UpdateAcceleratorAutoRenewAttribute"
request["ClientToken"] = buildClientToken("UpdateAcceleratorAutoRenewAttribute")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("auto_renew_duration")
d.SetPartial("renewal_status")
}
update = false
updateAcceleratorReq := map[string]interface{}{
"AcceleratorId": d.Id(),
}
if d.HasChange("accelerator_name") {
update = true
if v, ok := d.GetOk("accelerator_name"); ok {
updateAcceleratorReq["Name"] = v
}
}
updateAcceleratorReq["AutoPay"] = true
if d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
updateAcceleratorReq["Description"] = v
}
}
updateAcceleratorReq["RegionId"] = client.RegionId
if !d.IsNewResource() && d.HasChange("spec") {
update = true
updateAcceleratorReq["Spec"] = d.Get("spec")
}
if update {
if v, ok := d.GetOkExists("auto_use_coupon"); ok {
updateAcceleratorReq["AutoUseCoupon"] = v
}
action := "UpdateAccelerator"
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("UpdateAccelerator")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, updateAcceleratorReq, &runtime)
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"active"}, d.Timeout(schema.TimeoutUpdate), 30*time.Second, gaService.GaAcceleratorStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("accelerator_name")
d.SetPartial("description")
d.SetPartial("spec")
}
d.Partial(false)
return resourceAlicloudGaAcceleratorRead(d, meta)
}
func resourceAlicloudGaAcceleratorDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudGaAccelerator. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudGaAcl() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudGaAclCreate,
Read: resourceAlicloudGaAclRead,
Update: resourceAlicloudGaAclUpdate,
Delete: resourceAlicloudGaAclDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
Delete: schema.DefaultTimeout(5 * time.Minute),
Update: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"acl_entries": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"entry": {
Type: schema.TypeString,
Optional: true,
},
"entry_description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[A-Za-z0-9._/-]{1,256}$`), "The description of the IP entry. The description must be 1 to 256 characters in length, and can contain letters, digits, hyphens (-), forward slashes (/), periods (.),and underscores (_)."),
},
},
},
},
"acl_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-zA-Z][A-Za-z0-9._-]{2,128}$`), "The name must be `2` to `128` characters in length, and can contain letters, digits, periods (.), hyphens (-) and underscores (_). It must start with a letter."),
},
"address_ip_version": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"IPv4", "IPv6"}, false),
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudGaAclCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateAcl"
request := make(map[string]interface{})
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
if m, ok := d.GetOk("acl_entries"); ok {
for k, aclEntries := range m.(*schema.Set).List() {
aclEntriesArg := aclEntries.(map[string]interface{})
request[fmt.Sprintf("AclEntries.%d.Entry", k+1)] = aclEntriesArg["entry"].(string)
request[fmt.Sprintf("AclEntries.%d.EntryDescription", k+1)] = aclEntriesArg["entry_description"].(string)
}
}
if v, ok := d.GetOk("acl_name"); ok {
request["AclName"] = v
}
request["AddressIPVersion"] = d.Get("address_ip_version")
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["RegionId"] = client.RegionId
request["ClientToken"] = buildClientToken("CreateAcl")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ga_acl", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["AclId"]))
gaService := GaService{client}
stateConf := BuildStateConf([]string{}, []string{"active"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, gaService.GaAclStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudGaAclRead(d, meta)
}
func resourceAlicloudGaAclRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
object, err := gaService.DescribeGaAcl(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ga_acl gaService.DescribeGaAcl Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
if v, ok := object["AclEntries"].([]interface{}); ok {
aclEntries := make([]map[string]interface{}, 0)
for _, val := range v {
item := val.(map[string]interface{})
temp := map[string]interface{}{
"entry": item["Entry"],
"entry_description": item["EntryDescription"],
}
aclEntries = append(aclEntries, temp)
}
if err := d.Set("acl_entries", aclEntries); err != nil {
return WrapError(err)
}
}
d.Set("acl_name", object["AclName"])
d.Set("address_ip_version", object["AddressIPVersion"])
d.Set("status", object["AclStatus"])
return nil
}
func resourceAlicloudGaAclUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"AclId": d.Id(),
}
if d.HasChange("acl_name") {
update = true
}
if v, ok := d.GetOk("acl_name"); ok {
request["AclName"] = v
}
request["RegionId"] = client.RegionId
if update {
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
action := "UpdateAclAttribute"
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("UpdateAclAttribute")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 20*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"StateError.Acl"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("acl_name")
}
if d.HasChange("acl_entries") {
oraw, nraw := d.GetChange("acl_entries")
remove := oraw.(*schema.Set).Difference(nraw.(*schema.Set)).List()
create := nraw.(*schema.Set).Difference(oraw.(*schema.Set)).List()
if len(remove) > 0 {
removeEntriesFromAclReq := map[string]interface{}{
"AclId": d.Id(),
}
for k, aclEntries := range remove {
aclEntriesArg := aclEntries.(map[string]interface{})
removeEntriesFromAclReq[fmt.Sprintf("AclEntries.%d.Entry", k+1)] = aclEntriesArg["entry"].(string)
}
removeEntriesFromAclReq["RegionId"] = client.RegionId
if v, ok := d.GetOkExists("dry_run"); ok {
removeEntriesFromAclReq["DryRun"] = v
}
action := "RemoveEntriesFromAcl"
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("RemoveEntriesFromAcl")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 20*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, removeEntriesFromAclReq, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"StateError.Acl"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, removeEntriesFromAclReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"active"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, gaService.GaAclStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if len(create) > 0 {
addEntriesToAclReq := map[string]interface{}{
"AclId": d.Id(),
}
for k, aclEntries := range create {
aclEntriesArg := aclEntries.(map[string]interface{})
addEntriesToAclReq[fmt.Sprintf("AclEntries.%d.Entry", k+1)] = aclEntriesArg["entry"].(string)
addEntriesToAclReq[fmt.Sprintf("AclEntries.%d.EntryDescription", k+1)] = aclEntriesArg["entry_description"].(string)
}
addEntriesToAclReq["RegionId"] = client.RegionId
if v, ok := d.GetOkExists("dry_run"); ok {
addEntriesToAclReq["DryRun"] = v
}
action := "AddEntriesToAcl"
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("AddEntriesToAcl")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 20*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, addEntriesToAclReq, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"StateError.Acl"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, addEntriesToAclReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"active"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, gaService.GaAclStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.SetPartial("acl_entries")
}
d.Partial(false)
return resourceAlicloudGaAclRead(d, meta)
}
func resourceAlicloudGaAclDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
action := "DeleteAcl"
var response map[string]interface{}
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AclId": d.Id(),
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["RegionId"] = client.RegionId
request["ClientToken"] = buildClientToken("DeleteAcl")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 20*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"StateError.Acl"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"NotExist.Acl"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, gaService.GaAclStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudGaAclAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudGaAclAttachmentCreate,
Read: resourceAlicloudGaAclAttachmentRead,
Update: resourceAlicloudGaAclAttachmentUpdate,
Delete: resourceAlicloudGaAclAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
Delete: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"acl_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"acl_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"black", "white"}, false),
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"listener_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudGaAclAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AssociateAclsWithListener"
request := make(map[string]interface{})
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
request["AclIds.1"] = d.Get("acl_id")
request["AclType"] = d.Get("acl_type")
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["ListenerId"] = d.Get("listener_id")
request["RegionId"] = client.RegionId
request["ClientToken"] = buildClientToken("AssociateAclsWithListener")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ga_acl_attachment", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["ListenerId"], ":", d.Get("acl_id")))
gaService := GaService{client}
stateConf := BuildStateConf([]string{}, []string{"Associated"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, gaService.GaAclAttachmentStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudGaAclAttachmentRead(d, meta)
}
func resourceAlicloudGaAclAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
object, err := gaService.DescribeGaAclAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ga_acl_attachment gaService.DescribeGaAclAttachment Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("acl_id", parts[1])
d.Set("listener_id", parts[0])
d.Set("acl_type", object["AclType"])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudGaAclAttachmentUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return resourceAlicloudGaAclAttachmentRead(d, meta)
}
func resourceAlicloudGaAclAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
gaService := GaService{client}
action := "DissociateAclsFromListener"
var response map[string]interface{}
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ListenerId": parts[0],
}
request["AclIds.1"] = parts[1]
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["RegionId"] = client.RegionId
request["ClientToken"] = buildClientToken("DissociateAclsFromListener")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, gaService.GaAclAttachmentStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudGaAdditionalCertificate() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudGaAdditionalCertificateCreate,
Read: resourceAlicloudGaAdditionalCertificateRead,
Delete: resourceAlicloudGaAdditionalCertificateDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"accelerator_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"certificate_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"domain": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"listener_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudGaAdditionalCertificateCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AssociateAdditionalCertificatesWithListener"
request := make(map[string]interface{})
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
request["AcceleratorId"] = d.Get("accelerator_id")
request["Certificates.1.Domain"] = d.Get("domain")
request["Certificates.1.Id"] = d.Get("certificate_id")
request["ListenerId"] = d.Get("listener_id")
request["RegionId"] = client.RegionId
request["ClientToken"] = buildClientToken("AssociateAdditionalCertificatesWithListener")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ga_additional_certificate", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["AcceleratorId"], ":", request["ListenerId"], ":", request["Certificates.1.Domain"]))
return resourceAlicloudGaAdditionalCertificateRead(d, meta)
}
func resourceAlicloudGaAdditionalCertificateRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
object, err := gaService.DescribeGaAdditionalCertificate(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ga_additional_certificate gaService.DescribeGaAdditionalCertificate Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
d.Set("accelerator_id", parts[0])
d.Set("domain", parts[2])
d.Set("listener_id", parts[1])
d.Set("certificate_id", object["CertificateId"])
return nil
}
func resourceAlicloudGaAdditionalCertificateDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
action := "DissociateAdditionalCertificatesFromListener"
var response map[string]interface{}
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AcceleratorId": parts[0],
"ListenerId": parts[1],
}
request["Domains.1"] = parts[2]
request["RegionId"] = client.RegionId
request["ClientToken"] = buildClientToken("DissociateAdditionalCertificatesFromListener")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudGaBandwidthPackage() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudGaBandwidthPackageCreate,
Read: resourceAlicloudGaBandwidthPackageRead,
Update: resourceAlicloudGaBandwidthPackageUpdate,
Delete: resourceAlicloudGaBandwidthPackageDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(2 * time.Minute),
},
Schema: map[string]*schema.Schema{
"auto_pay": {
Type: schema.TypeBool,
Optional: true,
},
"auto_use_coupon": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"bandwidth": {
Type: schema.TypeInt,
Required: true,
},
"bandwidth_package_name": {
Type: schema.TypeString,
Optional: true,
},
"bandwidth_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Advanced", "Basic", "Enhanced"}, false),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("type").(string) != "Basic"
},
},
"billing_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PayBy95", "PayByTraffic"}, false),
},
"cbn_geographic_region_ida": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "China-mainland",
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("type").(string) != "CrossDomain"
},
},
"cbn_geographic_region_idb": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "Global",
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("type").(string) != "CrossDomain"
},
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"duration": {
Type: schema.TypeString,
Optional: true,
},
"payment_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo", "Subscription"}, false),
Default: "Subscription",
},
"ratio": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Basic", "CrossDomain"}, false),
},
},
}
}
func resourceAlicloudGaBandwidthPackageCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
var response map[string]interface{}
action := "CreateBandwidthPackage"
request := make(map[string]interface{})
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("auto_pay"); ok {
request["AutoPay"] = v
}
if v, ok := d.GetOkExists("auto_use_coupon"); ok {
request["AutoUseCoupon"] = v
}
request["Bandwidth"] = d.Get("bandwidth")
if v, ok := d.GetOk("bandwidth_type"); ok {
request["BandwidthType"] = v
}
if v, ok := d.GetOk("billing_type"); ok {
request["BillingType"] = v
}
if v, ok := d.GetOk("cbn_geographic_region_ida"); ok {
request["CbnGeographicRegionIdA"] = v
}
if v, ok := d.GetOk("cbn_geographic_region_idb"); ok {
request["CbnGeographicRegionIdB"] = v
}
if v, ok := d.GetOk("duration"); ok {
request["Duration"] = v
}
if v, ok := d.GetOk("payment_type"); ok {
request["ChargeType"] = convertGaBandwidthPackagePaymentTypeRequest(v.(string))
if request["ChargeType"].(string) == "PREPAY" {
request["PricingCycle"] = "Month"
}
}
if v, ok := d.GetOk("ratio"); ok {
request["Ratio"] = v
}
request["RegionId"] = client.RegionId
request["Type"] = d.Get("type")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("CreateBandwidthPackage")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ga_bandwidth_package", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetId(fmt.Sprint(response["BandwidthPackageId"]))
stateConf := BuildStateConf([]string{}, []string{"active"}, d.Timeout(schema.TimeoutCreate), 30*time.Second, gaService.GaBandwidthPackageStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudGaBandwidthPackageUpdate(d, meta)
}
func resourceAlicloudGaBandwidthPackageRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
object, err := gaService.DescribeGaBandwidthPackage(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ga_bandwidth_package gaService.DescribeGaBandwidthPackage Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("bandwidth", formatInt(object["Bandwidth"]))
d.Set("bandwidth_package_name", object["Name"])
d.Set("bandwidth_type", object["BandwidthType"])
d.Set("cbn_geographic_region_ida", object["CbnGeographicRegionIdA"])
d.Set("cbn_geographic_region_idb", object["CbnGeographicRegionIdB"])
d.Set("description", object["Description"])
d.Set("payment_type", convertGaBandwidthPackagePaymentTypeResponse(object["ChargeType"].(string)))
d.Set("status", object["State"])
d.Set("type", object["Type"])
if val, ok := d.GetOk("auto_use_coupon"); ok {
d.Set("auto_use_coupon", val)
}
return nil
}
func resourceAlicloudGaBandwidthPackageUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
var response map[string]interface{}
update := false
request := map[string]interface{}{
"BandwidthPackageId": d.Id(),
}
request["RegionId"] = client.RegionId
if !d.IsNewResource() && d.HasChange("bandwidth") {
update = true
request["Bandwidth"] = d.Get("bandwidth")
}
if d.HasChange("bandwidth_package_name") {
update = true
request["Name"] = d.Get("bandwidth_package_name")
}
if !d.IsNewResource() && d.HasChange("bandwidth_type") {
update = true
request["BandwidthType"] = d.Get("bandwidth_type")
}
if d.HasChange("description") {
update = true
request["Description"] = d.Get("description")
}
if update {
if _, ok := d.GetOkExists("auto_pay"); ok {
request["AutoPay"] = d.Get("auto_pay")
}
if _, ok := d.GetOkExists("auto_use_coupon"); ok {
request["AutoUseCoupon"] = d.Get("auto_use_coupon")
}
action := "UpdateBandwidthPackage"
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"NotExist.BandwidthPackage", "StateError.BandwidthPackage", "UpgradeError.BandwidthPackage", "GreaterThanGa.IpSetBandwidth"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"active", "binded"}, d.Timeout(schema.TimeoutUpdate), 30*time.Second, gaService.GaBandwidthPackageStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudGaBandwidthPackageRead(d, meta)
}
func resourceAlicloudGaBandwidthPackageDelete(d *schema.ResourceData, meta interface{}) error {
if d.Get("payment_type") == "Subscription" {
log.Printf("[WARN] Cannot destroy resourceAlicloudGaBandwidthPackage prepay type. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
client := meta.(*connectivity.AliyunClient)
action := "DeleteBandwidthPackage"
var response map[string]interface{}
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"BandwidthPackageId": d.Id(),
}
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("DeleteBandwidthPackage")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func convertGaBandwidthPackagePaymentTypeRequest(source string) string {
switch source {
case "PayAsYouGo":
return "POSTPAY"
case "Subscription":
return "PREPAY"
}
return source
}
func convertGaBandwidthPackagePaymentTypeResponse(source string) string {
switch source {
case "POSTPAY":
return "PayAsYouGo"
case "PREPAY":
return "Subscription"
}
return source
}
package alicloud
import (
"fmt"
"log"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudGaBandwidthPackageAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudGaBandwidthPackageAttachmentCreate,
Read: resourceAlicloudGaBandwidthPackageAttachmentRead,
Delete: resourceAlicloudGaBandwidthPackageAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
Delete: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"accelerator_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"accelerators": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"bandwidth_package_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudGaBandwidthPackageAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
var response map[string]interface{}
action := "BandwidthPackageAddAccelerator"
request := make(map[string]interface{})
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
request["AcceleratorId"] = d.Get("accelerator_id")
request["BandwidthPackageId"] = d.Get("bandwidth_package_id")
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"StateError.BandwidthPackage"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ga_bandwidth_package_attachment", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["AcceleratorId"], ":", response["BandwidthPackageId"]))
stateConf := BuildStateConf([]string{}, []string{"active"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, gaService.GaBandwidthPackageAttachmentStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudGaBandwidthPackageAttachmentRead(d, meta)
}
func resourceAlicloudGaBandwidthPackageAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
if !strings.Contains(d.Id(), ":") {
d.SetId(fmt.Sprint(d.Get("accelerator_id"), ":", d.Id()))
}
object, err := gaService.DescribeGaBandwidthPackageAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ga_bandwidth_package_attachment gaService.DescribeGaBandwidthPackageAttachment Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("bandwidth_package_id", parts[1])
d.Set("accelerator_id", parts[0])
d.Set("accelerators", []string{parts[0]})
d.Set("status", object["State"])
return nil
}
func resourceAlicloudGaBandwidthPackageAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
if !strings.Contains(d.Id(), ":") {
d.SetId(fmt.Sprint(d.Get("accelerator_id"), ":", d.Id()))
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "BandwidthPackageRemoveAccelerator"
var response map[string]interface{}
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"BandwidthPackageId": parts[1],
}
request["AcceleratorId"] = parts[0]
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"StateError.BandwidthPackage"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"NotExist.BandwidthPackage", "Exist.EndpointGroup"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, gaService.GaBandwidthPackageAttachmentStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudGaEndpointGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudGaEndpointGroupCreate,
Read: resourceAlicloudGaEndpointGroupRead,
Update: resourceAlicloudGaEndpointGroupUpdate,
Delete: resourceAlicloudGaEndpointGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(6 * time.Minute),
Update: schema.DefaultTimeout(2 * time.Minute),
},
Schema: map[string]*schema.Schema{
"accelerator_id": {
Type: schema.TypeString,
Required: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"endpoint_configurations": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enable_clientip_preservation": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"endpoint": {
Type: schema.TypeString,
Required: true,
},
"type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"Domain", "Ip", "PublicIp", "ECS", "SLB"}, false),
},
"weight": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(0, 255),
},
},
},
},
"endpoint_group_region": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"endpoint_group_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"default", "virtual"}, false),
Default: "default",
},
"endpoint_request_protocol": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"HTTP", "HTTPS"}, false),
},
"health_check_interval_seconds": {
Type: schema.TypeInt,
Optional: true,
},
"health_check_path": {
Type: schema.TypeString,
Optional: true,
},
"health_check_port": {
Type: schema.TypeInt,
Optional: true,
},
"health_check_protocol": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"http", "https", "tcp"}, false),
},
"listener_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
},
"port_overrides": {
Type: schema.TypeList,
MaxItems: 1,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"endpoint_port": {
Type: schema.TypeInt,
Optional: true,
},
"listener_port": {
Type: schema.TypeInt,
Optional: true,
},
},
},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"threshold_count": {
Type: schema.TypeInt,
Optional: true,
Default: 3,
},
"traffic_percentage": {
Type: schema.TypeInt,
Optional: true,
},
},
}
}
func resourceAlicloudGaEndpointGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
var response map[string]interface{}
action := "CreateEndpointGroup"
request := make(map[string]interface{})
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
request["AcceleratorId"] = d.Get("accelerator_id")
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
EndpointConfigurations := make([]map[string]interface{}, len(d.Get("endpoint_configurations").([]interface{})))
for i, EndpointConfigurationsValue := range d.Get("endpoint_configurations").([]interface{}) {
EndpointConfigurationsMap := EndpointConfigurationsValue.(map[string]interface{})
EndpointConfigurations[i] = make(map[string]interface{})
EndpointConfigurations[i]["EnableClientIPPreservation"] = EndpointConfigurationsMap["enable_clientip_preservation"]
EndpointConfigurations[i]["Endpoint"] = EndpointConfigurationsMap["endpoint"]
EndpointConfigurations[i]["Type"] = EndpointConfigurationsMap["type"]
EndpointConfigurations[i]["Weight"] = EndpointConfigurationsMap["weight"]
}
request["EndpointConfigurations"] = EndpointConfigurations
request["EndpointGroupRegion"] = d.Get("endpoint_group_region")
if v, ok := d.GetOk("endpoint_group_type"); ok {
request["EndpointGroupType"] = v
}
if v, ok := d.GetOk("endpoint_request_protocol"); ok {
request["EndpointRequestProtocol"] = v
}
if v, ok := d.GetOk("health_check_interval_seconds"); ok {
request["HealthCheckIntervalSeconds"] = v
}
if v, ok := d.GetOk("health_check_path"); ok {
request["HealthCheckPath"] = v
}
if v, ok := d.GetOk("health_check_port"); ok {
request["HealthCheckPort"] = v
}
if v, ok := d.GetOk("health_check_protocol"); ok {
request["HealthCheckProtocol"] = v
}
request["ListenerId"] = d.Get("listener_id")
if v, ok := d.GetOk("name"); ok {
request["Name"] = v
}
if v, ok := d.GetOk("port_overrides"); ok {
PortOverrides := make([]map[string]interface{}, len(v.([]interface{})))
for i, PortOverridesValue := range v.([]interface{}) {
PortOverridesMap := PortOverridesValue.(map[string]interface{})
PortOverrides[i] = make(map[string]interface{})
PortOverrides[i]["EndpointPort"] = PortOverridesMap["endpoint_port"]
PortOverrides[i]["ListenerPort"] = PortOverridesMap["listener_port"]
}
request["PortOverrides"] = PortOverrides
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("threshold_count"); ok {
request["ThresholdCount"] = v
}
if v, ok := d.GetOk("traffic_percentage"); ok {
request["TrafficPercentage"] = v
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("CreateEndpointGroup")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"GA_NOT_STEADY", "StateError.Accelerator", "StateError.EndPointGroup"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ga_endpoint_group", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["EndpointGroupId"]))
stateConf := BuildStateConf([]string{}, []string{"active"}, d.Timeout(schema.TimeoutCreate), 30*time.Second, gaService.GaEndpointGroupStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudGaEndpointGroupRead(d, meta)
}
func resourceAlicloudGaEndpointGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
object, err := gaService.DescribeGaEndpointGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ga_endpoint_group gaService.DescribeGaEndpointGroup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", object["Description"])
endpointConfigurations := make([]map[string]interface{}, 0)
if endpointConfigurationsList, ok := object["EndpointConfigurations"].([]interface{}); ok {
for _, v := range endpointConfigurationsList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"enable_clientip_preservation": m1["EnableClientIPPreservation"],
"endpoint": m1["Endpoint"],
"type": m1["Type"],
"weight": m1["Weight"],
}
endpointConfigurations = append(endpointConfigurations, temp1)
}
}
}
if err := d.Set("endpoint_configurations", endpointConfigurations); err != nil {
return WrapError(err)
}
d.Set("endpoint_group_region", object["EndpointGroupRegion"])
d.Set("health_check_interval_seconds", formatInt(object["HealthCheckIntervalSeconds"]))
d.Set("health_check_path", object["HealthCheckPath"])
d.Set("health_check_port", formatInt(object["HealthCheckPort"]))
d.Set("health_check_protocol", object["HealthCheckProtocol"])
d.Set("listener_id", object["ListenerId"])
d.Set("name", object["Name"])
portOverrides := make([]map[string]interface{}, 0)
if portOverridesList, ok := object["PortOverrides"].([]interface{}); ok {
for _, v := range portOverridesList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"endpoint_port": m1["EndpointPort"],
"listener_port": m1["ListenerPort"],
}
portOverrides = append(portOverrides, temp1)
}
}
}
if err := d.Set("port_overrides", portOverrides); err != nil {
return WrapError(err)
}
d.Set("status", object["State"])
d.Set("threshold_count", formatInt(object["ThresholdCount"]))
d.Set("traffic_percentage", formatInt(object["TrafficPercentage"]))
return nil
}
func resourceAlicloudGaEndpointGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
var response map[string]interface{}
update := false
request := map[string]interface{}{
"EndpointGroupId": d.Id(),
}
if d.HasChange("endpoint_configurations") {
update = true
}
EndpointConfigurations := make([]map[string]interface{}, len(d.Get("endpoint_configurations").([]interface{})))
for i, EndpointConfigurationsValue := range d.Get("endpoint_configurations").([]interface{}) {
EndpointConfigurationsMap := EndpointConfigurationsValue.(map[string]interface{})
EndpointConfigurations[i] = make(map[string]interface{})
EndpointConfigurations[i]["EnableClientIPPreservation"] = EndpointConfigurationsMap["enable_clientip_preservation"]
EndpointConfigurations[i]["Endpoint"] = EndpointConfigurationsMap["endpoint"]
EndpointConfigurations[i]["Type"] = EndpointConfigurationsMap["type"]
EndpointConfigurations[i]["Weight"] = EndpointConfigurationsMap["weight"]
}
request["EndpointConfigurations"] = EndpointConfigurations
request["EndpointGroupRegion"] = d.Get("endpoint_group_region")
request["RegionId"] = client.RegionId
if d.HasChange("description") {
update = true
request["Description"] = d.Get("description")
}
if d.HasChange("health_check_interval_seconds") {
update = true
request["HealthCheckIntervalSeconds"] = d.Get("health_check_interval_seconds")
}
if d.HasChange("health_check_path") {
update = true
request["HealthCheckPath"] = d.Get("health_check_path")
}
if d.HasChange("health_check_port") {
update = true
request["HealthCheckPort"] = d.Get("health_check_port")
}
if d.HasChange("health_check_protocol") {
update = true
request["HealthCheckProtocol"] = d.Get("health_check_protocol")
}
if d.HasChange("name") {
update = true
request["Name"] = d.Get("name")
}
if d.HasChange("port_overrides") {
update = true
}
PortOverrides := make([]map[string]interface{}, len(d.Get("port_overrides").([]interface{})))
for i, PortOverridesValue := range d.Get("port_overrides").([]interface{}) {
PortOverridesMap := PortOverridesValue.(map[string]interface{})
PortOverrides[i] = make(map[string]interface{})
PortOverrides[i]["EndpointPort"] = PortOverridesMap["endpoint_port"]
PortOverrides[i]["ListenerPort"] = PortOverridesMap["listener_port"]
}
request["PortOverrides"] = PortOverrides
if d.HasChange("threshold_count") {
update = true
}
request["ThresholdCount"] = d.Get("threshold_count")
if d.HasChange("traffic_percentage") {
update = true
request["TrafficPercentage"] = d.Get("traffic_percentage")
}
if update {
if _, ok := d.GetOk("endpoint_request_protocol"); ok {
request["EndpointRequestProtocol"] = d.Get("endpoint_request_protocol")
}
action := "UpdateEndpointGroup"
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("UpdateEndpointGroup")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"StateError.Accelerator", "StateError.EndPointGroup"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"active"}, d.Timeout(schema.TimeoutUpdate), 30*time.Second, gaService.GaEndpointGroupStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudGaEndpointGroupRead(d, meta)
}
func resourceAlicloudGaEndpointGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
action := "DeleteEndpointGroup"
var response map[string]interface{}
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"EndpointGroupId": d.Id(),
}
request["AcceleratorId"] = d.Get("accelerator_id")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("DeleteEndpointGroup")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"StateError.Accelerator", "StateError.EndPointGroup"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, gaService.GaEndpointGroupStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/PaesslerAG/jsonpath"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudGaForwardingRule() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudGaForwardingRuleCreate,
Read: resourceAlicloudGaForwardingRuleRead,
Update: resourceAlicloudGaForwardingRuleUpdate,
Delete: resourceAlicloudGaForwardingRuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(3 * time.Minute),
Update: schema.DefaultTimeout(3 * time.Minute),
Delete: schema.DefaultTimeout(3 * time.Minute),
},
Schema: map[string]*schema.Schema{
"priority": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"forwarding_rule_id": {
Type: schema.TypeString,
Computed: true,
},
"forwarding_rule_name": {
Type: schema.TypeString,
Optional: true,
},
"forwarding_rule_status": {
Type: schema.TypeString,
Computed: true,
},
"rule_conditions": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"rule_condition_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"Host", "Path"}, false),
},
"path_config": {
Type: schema.TypeSet,
MaxItems: 1,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"values": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
},
},
"host_config": {
Type: schema.TypeSet,
MinItems: 1,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"values": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
},
},
},
},
},
"rule_actions": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"order": {
Type: schema.TypeInt,
Required: true,
},
"rule_action_type": {
Type: schema.TypeString,
Required: true,
},
"forward_group_config": {
Type: schema.TypeSet,
MaxItems: 1,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"server_group_tuples": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"endpoint_group_id": {
Type: schema.TypeString,
Required: true,
},
},
},
},
},
},
},
},
},
},
"accelerator_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"listener_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
},
}
}
func resourceAlicloudGaForwardingRuleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
var response map[string]interface{}
action := "CreateForwardingRules"
request := make(map[string]interface{})
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
request["AcceleratorId"] = d.Get("accelerator_id")
request["ListenerId"] = d.Get("listener_id")
forwardingRule := make(map[string]interface{})
if val, ok := d.GetOk("priority"); ok {
forwardingRule["Priority"] = val
}
ruleConditions := d.Get("rule_conditions").(*schema.Set).List()
ruleConditionsMap := make([]map[string]interface{}, 0)
for _, ruleCondition := range ruleConditions {
ruleCondition := ruleCondition.(map[string]interface{})
ruleConditionMap := map[string]interface{}{}
ruleConditionMap["RuleConditionType"] = ruleCondition["rule_condition_type"]
if len(ruleCondition["path_config"].(*schema.Set).List()) > 0 {
ruleConditionMap["PathConfig"] = map[string]interface{}{
"Values": ruleCondition["path_config"].(*schema.Set).List()[0].(map[string]interface{})["values"],
}
}
if len(ruleCondition["host_config"].(*schema.Set).List()) > 0 {
ruleConditionMap["HostConfig"] = map[string]interface{}{
"Values": ruleCondition["host_config"].(*schema.Set).List()[0].(map[string]interface{})["values"],
}
}
ruleConditionsMap = append(ruleConditionsMap, ruleConditionMap)
}
forwardingRule["RuleConditions"] = ruleConditionsMap
ruleActions := d.Get("rule_actions").(*schema.Set).List()
ruleActionsMap := make([]map[string]interface{}, 0)
for _, ruleAction := range ruleActions {
ruleAction := ruleAction.(map[string]interface{})
ruleActionMap := map[string]interface{}{}
ruleActionMap["Order"] = ruleAction["order"]
ruleActionMap["RuleActionType"] = ruleAction["rule_action_type"]
forwardGroupConfigMap := map[string]interface{}{}
serverGroupTuplesMap := make([]map[string]interface{}, 0)
for _, serverGroupTuple := range ruleAction["forward_group_config"].(*schema.Set).List()[0].(map[string]interface{})["server_group_tuples"].(*schema.Set).List() {
serverGroupTuplesMap = append(serverGroupTuplesMap, map[string]interface{}{
"EndpointGroupId": serverGroupTuple.(map[string]interface{})["endpoint_group_id"],
})
}
forwardGroupConfigMap["ServerGroupTuples"] = serverGroupTuplesMap
ruleActionMap["ForwardGroupConfig"] = forwardGroupConfigMap
ruleActionsMap = append(ruleActionsMap, ruleActionMap)
}
forwardingRule["RuleActions"] = ruleActionsMap
if val, ok := d.GetOk("forwarding_rule_name"); ok {
forwardingRule["ForwardingRuleName"] = val
}
request["ForwardingRules"] = []interface{}{forwardingRule}
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken(action)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"StateError.Accelerator"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ga_forwarding_rule", action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.ForwardingRules", response)
if err != nil || len(v.([]interface{})) < 1 {
return WrapErrorf(err, IdMsg, d.Id())
}
response = v.([]interface{})[0].(map[string]interface{})
d.SetId(fmt.Sprintf("%s:%s:%s", request["AcceleratorId"].(string), request["ListenerId"].(string), fmt.Sprint(response["ForwardingRuleId"])))
stateConf := BuildStateConf([]string{}, []string{"active"}, d.Timeout(schema.TimeoutCreate), 30*time.Second, gaService.GaForwardingRuleStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudGaForwardingRuleRead(d, meta)
}
func resourceAlicloudGaForwardingRuleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
object, err := gaService.DescribeGaForwardingRule(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ga_ip_set gaService.DescribeGaForwardingRule Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
d.Set("accelerator_id", parts[0])
d.Set("listener_id", parts[1])
d.Set("priority", object["Priority"])
d.Set("forwarding_rule_id", object["ForwardingRuleId"])
d.Set("forwarding_rule_name", object["ForwardingRuleName"])
d.Set("forwarding_rule_status", object["ForwardingRuleStatus"])
ruleConditionsMap := make([]map[string]interface{}, 0)
for _, ruleCondition := range object["RuleConditions"].([]interface{}) {
ruleCondition := ruleCondition.(map[string]interface{})
ruleConditionMap := map[string]interface{}{}
ruleConditionMap["rule_condition_type"] = ruleCondition["RuleConditionType"]
if ruleCondition["PathConfig"].(map[string]interface{})["Values"] != nil {
ruleConditionMap["path_config"] = []map[string]interface{}{
{
"values": ruleCondition["PathConfig"].(map[string]interface{})["Values"],
},
}
}
if ruleCondition["HostConfig"].(map[string]interface{})["Values"] != nil {
ruleConditionMap["host_config"] = []map[string]interface{}{
{
"values": ruleCondition["HostConfig"].(map[string]interface{})["Values"],
},
}
}
ruleConditionsMap = append(ruleConditionsMap, ruleConditionMap)
}
d.Set("rule_conditions", ruleConditionsMap)
ruleActionsMap := make([]map[string]interface{}, 0)
for _, ruleAction := range object["RuleActions"].([]interface{}) {
ruleAction := ruleAction.(map[string]interface{})
ruleActionMap := map[string]interface{}{}
ruleActionMap["order"] = ruleAction["Order"]
ruleActionMap["rule_action_type"] = ruleAction["RuleActionType"]
serverGroupTuplesMap := make([]map[string]interface{}, 0)
for _, serverGroupTuple := range ruleAction["ForwardGroupConfig"].(map[string]interface{})["ServerGroupTuples"].([]interface{}) {
serverGroupTuplesMap = append(serverGroupTuplesMap, map[string]interface{}{
"endpoint_group_id": serverGroupTuple.(map[string]interface{})["EndpointGroupId"],
})
}
ruleActionMap["forward_group_config"] = []map[string]interface{}{
{
"server_group_tuples": serverGroupTuplesMap,
},
}
ruleActionsMap = append(ruleActionsMap, ruleActionMap)
}
d.Set("rule_actions", ruleActionsMap)
return nil
}
func resourceAlicloudGaForwardingRuleUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AcceleratorId": parts[0],
"ListenerId": parts[1],
}
forwardingRule := make(map[string]interface{})
forwardingRule["ForwardingRuleId"] = parts[2]
forwardingRule["Priority"] = d.Get("priority")
ruleConditions := d.Get("rule_conditions").(*schema.Set).List()
ruleConditionsMap := make([]map[string]interface{}, 0)
for _, ruleCondition := range ruleConditions {
ruleCondition := ruleCondition.(map[string]interface{})
ruleConditionMap := map[string]interface{}{}
ruleConditionMap["RuleConditionType"] = ruleCondition["rule_condition_type"]
if len(ruleCondition["path_config"].(*schema.Set).List()) > 0 {
ruleConditionMap["PathConfig"] = map[string]interface{}{
"Values": ruleCondition["path_config"].(*schema.Set).List()[0].(map[string]interface{})["values"],
}
}
if len(ruleCondition["host_config"].(*schema.Set).List()) > 0 {
ruleConditionMap["HostConfig"] = map[string]interface{}{
"Values": ruleCondition["host_config"].(*schema.Set).List()[0].(map[string]interface{})["values"],
}
}
ruleConditionsMap = append(ruleConditionsMap, ruleConditionMap)
}
forwardingRule["RuleConditions"] = ruleConditionsMap
ruleActions := d.Get("rule_actions").(*schema.Set).List()
ruleActionsMap := make([]map[string]interface{}, 0)
for _, ruleAction := range ruleActions {
ruleAction := ruleAction.(map[string]interface{})
ruleActionMap := map[string]interface{}{}
ruleActionMap["Order"] = ruleAction["order"]
ruleActionMap["RuleActionType"] = ruleAction["rule_action_type"]
forwardGroupConfigMap := map[string]interface{}{}
serverGroupTuplesMap := make([]map[string]interface{}, 0)
for _, serverGroupTuple := range ruleAction["forward_group_config"].(*schema.Set).List()[0].(map[string]interface{})["server_group_tuples"].(*schema.Set).List() {
serverGroupTuplesMap = append(serverGroupTuplesMap, map[string]interface{}{
"EndpointGroupId": serverGroupTuple.(map[string]interface{})["endpoint_group_id"],
})
}
forwardGroupConfigMap["ServerGroupTuples"] = serverGroupTuplesMap
ruleActionMap["ForwardGroupConfig"] = forwardGroupConfigMap
ruleActionsMap = append(ruleActionsMap, ruleActionMap)
}
forwardingRule["RuleActions"] = ruleActionsMap
if val, ok := d.GetOk("forwarding_rule_name"); ok {
forwardingRule["ForwardingRuleName"] = val
}
request["ForwardingRules"] = []interface{}{forwardingRule}
request["RegionId"] = client.RegionId
action := "UpdateForwardingRules"
request["ClientToken"] = buildClientToken(action)
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken(action)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"StateError.Accelerator", "StateError.ForwardingRule"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"active"}, d.Timeout(schema.TimeoutUpdate), 30*time.Second, gaService.GaForwardingRuleStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudGaForwardingRuleRead(d, meta)
}
func resourceAlicloudGaForwardingRuleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteForwardingRules"
var response map[string]interface{}
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AcceleratorId": parts[0],
"ListenerId": parts[1],
}
request["ForwardingRuleIds"] = []string{parts[2]}
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
request["ClientToken"] = buildClientToken(action)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"StateError.Accelerator", "StateError.ForwardingRule"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudGaIpSet() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudGaIpSetCreate,
Read: resourceAlicloudGaIpSetRead,
Update: resourceAlicloudGaIpSetUpdate,
Delete: resourceAlicloudGaIpSetDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(2 * time.Minute),
},
Schema: map[string]*schema.Schema{
"accelerate_region_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"accelerator_id": {
Type: schema.TypeString,
Required: true,
},
"bandwidth": {
Type: schema.TypeInt,
Optional: true,
},
"ip_address_list": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"ip_version": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"IPv4", "IPv6"}, false),
Default: "IPv4",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudGaIpSetCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
var response map[string]interface{}
action := "CreateIpSets"
request := make(map[string]interface{})
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
request["AccelerateRegion.1.AccelerateRegionId"] = d.Get("accelerate_region_id")
request["AcceleratorId"] = d.Get("accelerator_id")
if v, ok := d.GetOk("bandwidth"); ok {
request["AccelerateRegion.1.Bandwidth"] = v
}
if v, ok := d.GetOk("ip_version"); ok {
request["AccelerateRegion.1.IpVersion"] = v
}
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("CreateIpSets")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"StateError.Accelerator", "StateError.IpSet"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ga_ip_set", action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.IpSets", response)
if err != nil || len(v.([]interface{})) < 1 {
return WrapErrorf(err, IdMsg, d.Id())
}
response = v.([]interface{})[0].(map[string]interface{})
d.SetId(fmt.Sprint(response["IpSetId"]))
stateConf := BuildStateConf([]string{}, []string{"active"}, d.Timeout(schema.TimeoutCreate), 30*time.Second, gaService.GaIpSetStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudGaIpSetRead(d, meta)
}
func resourceAlicloudGaIpSetRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
object, err := gaService.DescribeGaIpSet(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ga_ip_set gaService.DescribeGaIpSet Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("accelerate_region_id", object["AccelerateRegionId"])
d.Set("bandwidth", formatInt(object["Bandwidth"]))
d.Set("ip_address_list", object["IpAddressList"])
d.Set("ip_version", object["IpVersion"])
d.Set("status", object["State"])
return nil
}
func resourceAlicloudGaIpSetUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
var response map[string]interface{}
update := false
request := map[string]interface{}{
"IpSetId": d.Id(),
}
if d.HasChange("bandwidth") {
update = true
}
request["Bandwidth"] = d.Get("bandwidth")
request["RegionId"] = client.RegionId
if update {
action := "UpdateIpSet"
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("UpdateIpSet")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"StateError.Accelerator", "StateError.IpSet", "GreaterThanGa.IpSetBandwidth"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"active"}, d.Timeout(schema.TimeoutUpdate), 30*time.Second, gaService.GaIpSetStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudGaIpSetRead(d, meta)
}
func resourceAlicloudGaIpSetDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
action := "DeleteIpSet"
var response map[string]interface{}
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"IpSetId": d.Id(),
}
request["AcceleratorId"] = d.Get("accelerator_id")
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("DeleteIpSet")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"StateError.Accelerator", "StateError.IpSet"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 30*time.Second, gaService.GaIpSetStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudGaListener() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudGaListenerCreate,
Read: resourceAlicloudGaListenerRead,
Update: resourceAlicloudGaListenerUpdate,
Delete: resourceAlicloudGaListenerDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(6 * time.Minute),
Update: schema.DefaultTimeout(3 * time.Minute),
},
Schema: map[string]*schema.Schema{
"accelerator_id": {
Type: schema.TypeString,
Required: true,
},
"certificates": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"client_affinity": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"NONE", "SOURCE_IP"}, false),
Default: "NONE",
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if d.Get("protocol") == "UDP" && new == "SOURCE_IP" {
return true
}
return false
},
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
},
"port_ranges": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"from_port": {
Type: schema.TypeInt,
Required: true,
},
"to_port": {
Type: schema.TypeInt,
Required: true,
},
},
},
},
"protocol": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"TCP", "UDP", "HTTP", "HTTPS"}, false),
Default: "TCP",
},
"proxy_protocol": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudGaListenerCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
var response map[string]interface{}
action := "CreateListener"
request := make(map[string]interface{})
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
request["AcceleratorId"] = d.Get("accelerator_id")
if v, ok := d.GetOk("certificates"); ok {
Certificates := make([]map[string]interface{}, len(v.([]interface{})))
for i, CertificatesValue := range v.([]interface{}) {
CertificatesMap := CertificatesValue.(map[string]interface{})
Certificates[i] = make(map[string]interface{})
Certificates[i]["Id"] = CertificatesMap["id"]
}
request["Certificates"] = Certificates
}
if v, ok := d.GetOk("client_affinity"); ok {
request["ClientAffinity"] = v
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("name"); ok {
request["Name"] = v
}
PortRanges := make([]map[string]interface{}, len(d.Get("port_ranges").([]interface{})))
for i, PortRangesValue := range d.Get("port_ranges").([]interface{}) {
PortRangesMap := PortRangesValue.(map[string]interface{})
PortRanges[i] = make(map[string]interface{})
PortRanges[i]["FromPort"] = PortRangesMap["from_port"]
PortRanges[i]["ToPort"] = PortRangesMap["to_port"]
}
request["PortRanges"] = PortRanges
if v, ok := d.GetOk("protocol"); ok {
request["Protocol"] = v
}
if v, ok := d.GetOkExists("proxy_protocol"); ok {
request["ProxyProtocol"] = v
}
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("CreateListener")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"StateError.Accelerator"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ga_listener", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["ListenerId"]))
stateConf := BuildStateConf([]string{}, []string{"active"}, d.Timeout(schema.TimeoutCreate), 30*time.Second, gaService.GaListenerStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudGaListenerRead(d, meta)
}
func resourceAlicloudGaListenerRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
object, err := gaService.DescribeGaListener(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ga_listener gaService.DescribeGaListener Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
certificates := make([]map[string]interface{}, 0)
if certificatesList, ok := object["Certificates"].([]interface{}); ok {
for _, v := range certificatesList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"id": m1["Id"],
}
certificates = append(certificates, temp1)
}
}
}
if err := d.Set("certificates", certificates); err != nil {
return WrapError(err)
}
d.Set("client_affinity", object["ClientAffinity"])
d.Set("description", object["Description"])
d.Set("name", object["Name"])
if val, ok := d.GetOk("proxy_protocol"); ok {
d.Set("proxy_protocol", val)
}
portRanges := make([]map[string]interface{}, 0)
if portRangesList, ok := object["PortRanges"].([]interface{}); ok {
for _, v := range portRangesList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"from_port": m1["FromPort"],
"to_port": m1["ToPort"],
}
portRanges = append(portRanges, temp1)
}
}
}
if err := d.Set("port_ranges", portRanges); err != nil {
return WrapError(err)
}
d.Set("protocol", object["Protocol"])
d.Set("status", object["State"])
return nil
}
func resourceAlicloudGaListenerUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
var response map[string]interface{}
update := false
request := map[string]interface{}{
"ListenerId": d.Id(),
}
if d.HasChange("certificates") {
update = true
Certificates := make([]map[string]interface{}, len(d.Get("certificates").([]interface{})))
for i, CertificatesValue := range d.Get("certificates").([]interface{}) {
CertificatesMap := CertificatesValue.(map[string]interface{})
Certificates[i] = make(map[string]interface{})
Certificates[i]["Id"] = CertificatesMap["id"]
}
request["Certificates"] = Certificates
}
if d.HasChange("client_affinity") {
update = true
request["ClientAffinity"] = d.Get("client_affinity")
}
if d.HasChange("description") {
update = true
request["Description"] = d.Get("description")
}
if d.HasChange("name") {
update = true
request["Name"] = d.Get("name")
}
if d.HasChange("port_ranges") {
update = true
PortRanges := make([]map[string]interface{}, len(d.Get("port_ranges").([]interface{})))
for i, PortRangesValue := range d.Get("port_ranges").([]interface{}) {
PortRangesMap := PortRangesValue.(map[string]interface{})
PortRanges[i] = make(map[string]interface{})
PortRanges[i]["FromPort"] = PortRangesMap["from_port"]
PortRanges[i]["ToPort"] = PortRangesMap["to_port"]
}
request["PortRanges"] = PortRanges
}
if d.HasChange("protocol") {
update = true
request["Protocol"] = d.Get("protocol")
}
request["RegionId"] = client.RegionId
if update {
if _, ok := d.GetOkExists("proxy_protocol"); ok {
request["ProxyProtocol"] = d.Get("proxy_protocol")
}
action := "UpdateListener"
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("UpdateListener")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"StateError.Accelerator"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"active"}, d.Timeout(schema.TimeoutUpdate), 30*time.Second, gaService.GaListenerStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudGaListenerRead(d, meta)
}
func resourceAlicloudGaListenerDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gaService := GaService{client}
action := "DeleteListener"
var response map[string]interface{}
conn, err := client.NewGaplusClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ListenerId": d.Id(),
}
request["AcceleratorId"] = d.Get("accelerator_id")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("DeleteListener")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"StateError.Accelerator"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, gaService.GaListenerStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudGpdbAccount() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudGpdbAccountCreate,
Read: resourceAlicloudGpdbAccountRead,
Update: resourceAlicloudGpdbAccountUpdate,
Delete: resourceAlicloudGpdbAccountDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"account_description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[A-Za-z][\w\\_]{2,255}$`), "The description of the account. The description must be 2 to 256 characters in length and can contain letters, digits, underscores (_)."),
},
"account_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-z][a-z0-9_]{1,14}[a-z0-9]$`), "The name of the account. The name must be 2 to 16 characters in length and can contain lower letters, digits, underscores (_)."),
},
"account_password": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(8, 32),
},
"db_instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudGpdbAccountCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateAccount"
request := make(map[string]interface{})
conn, err := client.NewGpdbClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("account_description"); ok {
request["AccountDescription"] = v
}
request["AccountName"] = d.Get("account_name")
request["DBInstanceId"] = d.Get("db_instance_id")
request["AccountPassword"] = d.Get("account_password")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-05-03"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_gpdb_account", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["DBInstanceId"], ":", request["AccountName"]))
gpdbService := GpdbService{client}
stateConf := BuildStateConf([]string{}, []string{"1"}, d.Timeout(schema.TimeoutCreate), 60*time.Second, gpdbService.GpdbAccountStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudGpdbAccountRead(d, meta)
}
func resourceAlicloudGpdbAccountRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gpdbService := GpdbService{client}
object, err := gpdbService.DescribeGpdbAccount(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_gpdb_account gpdbService.DescribeGpdbAccount Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("account_name", parts[1])
d.Set("db_instance_id", parts[0])
d.Set("account_description", object["AccountDescription"])
d.Set("status", convertGpdbAccountStatusResponse(object["AccountStatus"]))
return nil
}
func resourceAlicloudGpdbAccountUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AccountName": parts[1],
"DBInstanceId": parts[0],
}
update := false
if d.HasChange("account_password") {
update = true
if v, ok := d.GetOk("account_password"); ok {
request["AccountPassword"] = v
}
}
if update {
action := "ResetAccountPassword"
conn, err := client.NewGpdbClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-05-03"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudGpdbAccountRead(d, meta)
}
func resourceAlicloudGpdbAccountDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudGpdbAccount. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
func convertGpdbAccountStatusResponse(source interface{}) interface{} {
switch source {
case "Creating":
return "0"
case "Active":
return "1"
case "Deleting":
return "3"
}
return source
}
package alicloud
import (
"fmt"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/gpdb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudGpdbConnection() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudGpdbConnectionCreate,
Read: resourceAlicloudGpdbConnectionRead,
Update: resourceAlicloudGpdbConnectionUpdate,
Delete: resourceAlicloudGpdbConnectionDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"connection_prefix": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(1, 31),
},
"port": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateDBConnectionPort,
Default: "3306",
},
"connection_string": {
Type: schema.TypeString,
Computed: true,
},
"ip_address": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudGpdbConnectionCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gpdbService := GpdbService{client}
instanceId := d.Get("instance_id").(string)
prefix := d.Get("connection_prefix").(string)
if prefix == "" {
prefix = fmt.Sprintf("%s-tf", instanceId)
}
request := gpdb.CreateAllocateInstancePublicConnectionRequest()
request.RegionId = client.RegionId
request.DBInstanceId = instanceId
request.ConnectionStringPrefix = prefix
request.Port = d.Get("port").(string)
err := resource.Retry(8*time.Minute, func() *resource.RetryError {
raw, err := client.WithGpdbClient(func(gpdbClient *gpdb.Client) (interface{}, error) {
return gpdbClient.AllocateInstancePublicConnection(request)
})
if err != nil {
if IsExpectedErrors(err, OperationDeniedDBStatus) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_gpdb_connection", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprintf("%s%s%s", instanceId, COLON_SEPARATED, request.ConnectionStringPrefix))
// wait instance running after allocating
stateConf := BuildStateConf([]string{"Creating", "NetAddressCreating"}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, gpdbService.GpdbInstanceStateRefreshFunc(instanceId, []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudGpdbConnectionRead(d, meta)
}
func resourceAlicloudGpdbConnectionRead(d *schema.ResourceData, meta interface{}) error {
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
client := meta.(*connectivity.AliyunClient)
gpdbService := GpdbService{client}
object, err := gpdbService.DescribeGpdbConnection(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_id", parts[0])
d.Set("connection_prefix", parts[1])
d.Set("port", object.Port)
d.Set("connection_string", object.ConnectionString)
d.Set("ip_address", object.IPAddress)
return nil
}
func resourceAlicloudGpdbConnectionUpdate(d *schema.ResourceData, meta interface{}) error {
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
if d.HasChange("port") {
client := meta.(*connectivity.AliyunClient)
gpdbService := GpdbService{client}
request := gpdb.CreateModifyDBInstanceConnectionStringRequest()
request.RegionId = client.RegionId
request.DBInstanceId = parts[0]
object, err := gpdbService.DescribeGpdbConnection(d.Id())
if err != nil {
return WrapError(err)
}
request.CurrentConnectionString = object.ConnectionString
request.ConnectionStringPrefix = parts[1]
request.Port = d.Get("port").(string)
if err := resource.Retry(8*time.Minute, func() *resource.RetryError {
raw, err := client.WithGpdbClient(func(gpdbClient *gpdb.Client) (interface{}, error) {
return gpdbClient.ModifyDBInstanceConnectionString(request)
})
if err != nil {
if IsExpectedErrors(err, OperationDeniedDBStatus) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
// wait instance running after modifying
stateConf := BuildStateConf([]string{"NET_MODIFYING"}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 3*time.Minute, gpdbService.GpdbInstanceStateRefreshFunc(request.DBInstanceId, []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudGpdbConnectionRead(d, meta)
}
func resourceAlicloudGpdbConnectionDelete(d *schema.ResourceData, meta interface{}) error {
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request := gpdb.CreateReleaseInstancePublicConnectionRequest()
request.DBInstanceId = parts[0]
client := meta.(*connectivity.AliyunClient)
gpdbService := GpdbService{client}
request.RegionId = client.RegionId
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
object, err := gpdbService.DescribeGpdbConnection(d.Id())
if err != nil {
return resource.NonRetryableError(WrapError(err))
}
request.CurrentConnectionString = object.ConnectionString
var raw interface{}
raw, err = client.WithGpdbClient(func(gpdbClient *gpdb.Client) (interface{}, error) {
return gpdbClient.ReleaseInstancePublicConnection(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"OperationDenied.DBInstanceStatus"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound", "InvalidCurrentConnectionString.NotFound", "AtLeastOneNetTypeExists"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"NetAddressDeleting"}, []string{"Running"}, d.Timeout(schema.TimeoutDelete), 5*time.Second, gpdbService.GpdbInstanceStateRefreshFunc(request.DBInstanceId, []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return WrapError(gpdbService.WaitForGpdbConnection(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"fmt"
"strconv"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudGpdbElasticInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudGpdbElasticInstanceCreate,
Read: resourceAlicloudGpdbElasticInstanceRead,
Update: resourceAlicloudGpdbElasticInstanceUpdate,
Delete: resourceAlicloudGpdbElasticInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(50 * time.Minute),
Update: schema.DefaultTimeout(30 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"engine": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"gpdb"}, false),
},
"engine_version": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"6.0"}, false),
},
"seg_storage_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"cloud_essd", "cloud_efficiency"}, false),
},
"seg_node_num": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
ValidateFunc: func(val interface{}, key string) (warns []string, errs []error) {
v := val.(int)
if v < 4 || v > 256 || v%4 != 0 {
errs = append(errs, fmt.Errorf("%q must be between 0 and 256 inclusive, and multiple of 4, got: %d", key, v))
}
return
},
},
"storage_size": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
ValidateFunc: func(val interface{}, key string) (warns []string, errs []error) {
v := val.(int)
if v < 50 || v > 4000 || v%50 != 0 {
errs = append(errs, fmt.Errorf("%q must be between 50 and 4000 inclusive, and multiple of 50, got: %d", key, v))
}
return
},
},
"instance_spec": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"2C16G", "4C32G", "16C128G"}, false),
},
"db_instance_description": {
Type: schema.TypeString,
Optional: true,
},
"instance_network_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"VPC"}, false),
Default: "VPC",
},
"payment_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo", "Subscription"}, false),
Default: "PayAsYouGo",
},
"payment_duration_unit": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Month", "Year"}, false),
DiffSuppressFunc: PostPaidDiffSuppressFunc,
},
"payment_duration": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(1, 12),
DiffSuppressFunc: PostPaidDiffSuppressFunc,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"connection_string": {
Type: schema.TypeString,
Computed: true,
},
"security_ip_list": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
Optional: true,
},
},
}
}
func resourceAlicloudGpdbElasticInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gpdbService := GpdbService{client}
var response map[string]interface{}
action := "CreateECSDBInstance"
request := make(map[string]interface{})
conn, err := client.NewGpdbClient()
if err != nil {
return WrapError(err)
}
request["Engine"] = d.Get("engine")
request["EngineVersion"] = d.Get("engine_version")
request["SegStorageType"] = d.Get("seg_storage_type")
request["SegNodeNum"] = d.Get("seg_node_num")
request["StorageSize"] = d.Get("storage_size")
request["InstanceSpec"] = d.Get("instance_spec")
request["PayType"] = convertGpdbInstancePaymentTypeRequest(d.Get("payment_type").(string))
if request["PayType"].(string) == "Prepaid" {
request["Period"] = d.Get("payment_duration_unit")
paymentDuration := d.Get("payment_duration").(int)
request["UsedTime"] = strconv.Itoa(paymentDuration)
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("zone_id"); ok {
request["ZoneId"] = v
}
vswitchId := Trim(d.Get("vswitch_id").(string))
if vswitchId != "" {
vpcService := VpcService{client}
vsw, err := vpcService.DescribeVSwitchWithTeadsl(vswitchId)
if err != nil {
return WrapError(err)
}
request["VPCId"] = vsw["VpcId"]
request["VSwitchId"] = vswitchId
if v, ok := request["ZoneId"].(string); !ok || v == "" {
request["ZoneId"] = vsw["ZoneId"]
}
}
request["ClientToken"] = buildClientToken("CreateECSDBInstance")
wait := incrementalWait(3*time.Second, 3*time.Second)
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-05-03"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_gpdb_elastic_instance", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["DBInstanceId"]))
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 10*time.Minute, gpdbService.GpdbElasticInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudGpdbElasticInstanceUpdate(d, meta)
}
func resourceAlicloudGpdbElasticInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gpdbService := GpdbService{client}
instance, err := gpdbService.DescribeGpdbElasticInstance(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("engine", instance["Engine"])
d.Set("engine_version", instance["EngineVersion"])
d.Set("seg_storage_type", instance["StorageType"])
d.Set("seg_node_num", instance["SegNodeNum"])
d.Set("storage_size", instance["StorageSize"])
d.Set("status", instance["DBInstanceStatus"])
d.Set("db_instance_description", instance["DBInstanceDescription"])
d.Set("instance_network_type", instance["InstanceNetworkType"])
d.Set("vswitch_id", instance["VSwitchId"])
d.Set("zone_id", instance["ZoneId"])
d.Set("connection_string", instance["ConnectionString"])
if v, exist := instance["DBInstanceClass"]; exist {
d.Set("instance_spec", convertDBInstanceClassToInstanceSpec(v.(string)))
}
if v, exist := instance["PayType"]; exist {
d.Set("payment_type", convertGpdbInstancePaymentTypeResponse(v.(string)))
}
securityIps, err := gpdbService.DescribeGpdbSecurityIps(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("security_ip_list", securityIps)
return nil
}
func resourceAlicloudGpdbElasticInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gpdbService := GpdbService{client}
d.Partial(true)
conn, err := client.NewGpdbClient()
if err != nil {
return WrapError(err)
}
if d.HasChange("db_instance_description") {
action := "ModifyDBInstanceDescription"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": d.Id(),
"DBInstanceDescription": d.Get("db_instance_description"),
"SourceIp": client.SourceIp,
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-05-03"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("db_instance_description")
}
if d.HasChange("security_ip_list") {
ipList := expandStringList(d.Get("security_ip_list").([]interface{}))
ipStr := strings.Join(ipList[:], COMMA_SEPARATED)
if ipStr == "" {
ipStr = LOCAL_HOST_IP
}
if err := gpdbService.ModifyGpdbSecurityIps(d.Id(), ipStr); err != nil {
return WrapError(err)
}
d.SetPartial("security_ip_list")
}
d.Partial(false)
return resourceAlicloudGpdbElasticInstanceRead(d, meta)
}
func resourceAlicloudGpdbElasticInstanceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteDBInstance"
var response map[string]interface{}
conn, err := client.NewGpdbClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DBInstanceId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-05-03"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"OperationDenied.DBInstancePayType"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func convertGpdbInstancePaymentTypeRequest(source string) string {
switch source {
case "PayAsYouGo":
return "Postpaid"
case "Subscription":
return "Prepaid"
}
return source
}
func convertGpdbInstancePaymentTypeResponse(source string) string {
switch source {
case "Postpaid":
return "PayAsYouGo"
case "Prepaid":
return "Subscription"
}
return source
}
func convertDBInstanceClassToInstanceSpec(instanceClass string) string {
splitClass := strings.Split(instanceClass, ".")
return strings.ToUpper(splitClass[len(splitClass)-1])
}
package alicloud
import (
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/aliyun/alibaba-cloud-sdk-go/services/gpdb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudGpdbInstance() *schema.Resource {
return &schema.Resource{
Read: resourceAlicloudGpdbInstanceRead,
Create: resourceAlicloudGpdbInstanceCreate,
Update: resourceAlicloudGpdbInstanceUpdate,
Delete: resourceAlicloudGpdbInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
},
Schema: map[string]*schema.Schema{
"availability_zone": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"instance_class": {
Type: schema.TypeString,
Required: true,
},
"instance_group_count": {
Type: schema.TypeString,
Required: true,
},
"instance_charge_type": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"PostPaid"}, false),
Optional: true,
ForceNew: true,
Computed: true,
},
"description": {
Type: schema.TypeString,
ValidateFunc: validation.StringLenBetween(2, 256),
Optional: true,
},
"vswitch_id": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
Computed: true,
},
"security_ip_list": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
Optional: true,
},
"engine": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"gpdb"}, false),
Optional: true,
Computed: true,
ForceNew: true,
},
"engine_version": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"tags": tagsSchema(),
},
}
}
func resourceAlicloudGpdbInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gpdbService := GpdbService{client}
instance, err := gpdbService.DescribeGpdbInstance(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_id", instance.DBInstanceId)
d.Set("region_id", instance.RegionId)
d.Set("availability_zone", instance.ZoneId)
d.Set("engine", instance.Engine)
d.Set("engine_version", instance.EngineVersion)
d.Set("status", instance.DBInstanceStatus)
d.Set("description", instance.DBInstanceDescription)
d.Set("instance_class", instance.DBInstanceClass)
d.Set("instance_group_count", instance.DBInstanceGroupCount)
d.Set("instance_network_type", instance.InstanceNetworkType)
security_ips, err := gpdbService.DescribeGpdbSecurityIps(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("security_ip_list", security_ips)
d.Set("create_time", instance.CreationTime)
d.Set("tags", gpdbService.tagsToMap(instance.Tags.Tag))
d.Set("instance_charge_type", convertGpdbPayTypeResponse(instance.PayType))
return nil
}
func resourceAlicloudGpdbInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gpdbService := GpdbService{client}
request, err := buildGpdbCreateRequest(d, meta)
if err != nil {
return WrapError(err)
}
var raw interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = client.WithGpdbClient(func(client *gpdb.Client) (interface{}, error) {
return client.CreateDBInstance(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"SYSTEM.CONCURRENT_OPERATE"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
response, _ := raw.(*gpdb.CreateDBInstanceResponse)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_gpdb_instance", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetId(response.DBInstanceId)
stateConf := BuildStateConf([]string{"Creating"}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 10*time.Minute, gpdbService.GpdbInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudGpdbInstanceUpdate(d, meta)
}
func resourceAlicloudGpdbInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gpdbService := GpdbService{client}
// Begin Update
d.Partial(true)
// Update Instance Description
if d.HasChange("description") {
request := gpdb.CreateModifyDBInstanceDescriptionRequest()
request.RegionId = client.RegionId
request.DBInstanceId = d.Id()
request.DBInstanceDescription = d.Get("description").(string)
raw, err := client.WithGpdbClient(func(gpdbClient *gpdb.Client) (interface{}, error) {
return gpdbClient.ModifyDBInstanceDescription(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("description")
}
// Update Security Ips
if d.HasChange("security_ip_list") {
ipList := expandStringList(d.Get("security_ip_list").(*schema.Set).List())
ipStr := strings.Join(ipList[:], COMMA_SEPARATED)
// default disable connect from outside
if ipStr == "" {
ipStr = LOCAL_HOST_IP
}
if err := gpdbService.ModifyGpdbSecurityIps(d.Id(), ipStr); err != nil {
return WrapError(err)
}
d.SetPartial("security_ip_list")
}
if err := gpdbService.setInstanceTags(d); err != nil {
return WrapError(err)
}
// Finish Update
d.Partial(false)
return resourceAlicloudGpdbInstanceRead(d, meta)
}
func resourceAlicloudGpdbInstanceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := gpdb.CreateDeleteDBInstanceRequest()
request.RegionId = client.RegionId
request.DBInstanceId = d.Id()
err := resource.Retry(10*5*time.Minute, func() *resource.RetryError {
raw, err := client.WithGpdbClient(func(client *gpdb.Client) (interface{}, error) {
return client.DeleteDBInstance(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"OperationDenied.DBInstanceStatus"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
// because DeleteDBInstance is called synchronously, there is no wait or describe here.
return nil
}
func buildGpdbCreateRequest(d *schema.ResourceData, meta interface{}) (*gpdb.CreateDBInstanceRequest, error) {
client := meta.(*connectivity.AliyunClient)
request := gpdb.CreateCreateDBInstanceRequest()
request.RegionId = string(client.Region)
request.ZoneId = Trim(d.Get("availability_zone").(string))
request.VSwitchId = Trim(d.Get("vswitch_id").(string))
request.DBInstanceDescription = d.Get("description").(string)
request.DBInstanceClass = Trim(d.Get("instance_class").(string))
request.DBInstanceGroupCount = Trim(d.Get("instance_group_count").(string))
request.Engine = Trim(d.Get("engine").(string))
request.EngineVersion = Trim(d.Get("engine_version").(string))
request.PayType = convertGpdbPayTypeRequest(d.Get("instance_charge_type").(string))
// Instance NetWorkType
request.InstanceNetworkType = string(Classic)
if request.VSwitchId != "" {
// check vswitchId in zone
vpcService := VpcService{client}
object, err := vpcService.DescribeVSwitch(request.VSwitchId)
if err != nil {
return nil, WrapError(err)
}
if request.ZoneId == "" {
request.ZoneId = object.ZoneId
} else if strings.Contains(request.ZoneId, MULTI_IZ_SYMBOL) {
zoneStr := strings.Split(strings.SplitAfter(request.ZoneId, "(")[1], ")")[0]
if !strings.Contains(zoneStr, string([]byte(object.ZoneId)[len(object.ZoneId)-1])) {
return nil, WrapError(Error("The specified vswitch %s isn't in the multi zone %s.", object.VSwitchId, request.ZoneId))
}
} else if request.ZoneId != object.ZoneId {
return nil, WrapError(Error("The specified vswitch %s isn't in the zone %s.", object.VSwitchId, request.ZoneId))
}
request.VPCId = object.VpcId
request.InstanceNetworkType = strings.ToUpper(string(Vpc))
}
// Security Ips
request.SecurityIPList = LOCAL_HOST_IP
if len(d.Get("security_ip_list").(*schema.Set).List()) > 0 {
request.SecurityIPList = strings.Join(expandStringList(d.Get("security_ip_list").(*schema.Set).List())[:], COMMA_SEPARATED)
}
// ClientToken
request.ClientToken = buildClientToken(request.GetActionName())
return request, nil
}
func convertGpdbPayTypeRequest(source string) string {
switch source {
case string(PostPaid):
return string(Postpaid)
case string(PrePaid):
return string(Prepaid)
}
return source
}
func convertGpdbPayTypeResponse(source string) string {
switch source {
case string(Postpaid):
return string(PostPaid)
case string(Prepaid):
return string(PrePaid)
}
return source
}
package alicloud
import (
"fmt"
"log"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudGraphDatabaseDbInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudGraphDatabaseDbInstanceCreate,
Read: resourceAlicloudGraphDatabaseDbInstanceRead,
Update: resourceAlicloudGraphDatabaseDbInstanceUpdate,
Delete: resourceAlicloudGraphDatabaseDbInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
Delete: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(60 * time.Minute),
},
Schema: map[string]*schema.Schema{
"db_instance_ip_array": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"db_instance_ip_array_attribute": {
Type: schema.TypeString,
Optional: true,
},
"db_instance_ip_array_name": {
Type: schema.TypeString,
Optional: true,
},
"security_ips": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"db_instance_category": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"HA"}, false),
},
"db_instance_description": {
Type: schema.TypeString,
Optional: true,
},
"db_instance_network_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"vpc"}, false),
},
"db_instance_storage_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"cloud_essd", "cloud_ssd"}, false),
},
"db_node_class": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"gdb.r.xlarge", "gdb.r.2xlarge", "gdb.r.4xlarge", "gdb.r.8xlarge", "gdb.r.16xlarge"}, false),
},
"db_node_storage": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(20, 32000),
},
"db_version": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"1.0", "1.0-OpenCypher"}, false),
},
"payment_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo"}, false),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudGraphDatabaseDbInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateDBInstance"
request := make(map[string]interface{})
conn, err := client.NewGdsClient()
if err != nil {
return WrapError(err)
}
request["DBInstanceCategory"] = strings.ToLower(d.Get("db_instance_category").(string))
if v, ok := d.GetOk("db_instance_description"); ok {
request["DBInstanceDescription"] = v
}
request["DBInstanceNetworkType"] = d.Get("db_instance_network_type")
request["DBNodeStorageType"] = d.Get("db_instance_storage_type")
request["DBInstanceClass"] = d.Get("db_node_class")
request["DBNodeStorage"] = d.Get("db_node_storage")
request["DBInstanceVersion"] = d.Get("db_version")
request["PayType"] = convertGraphDatabaseDbInstancePaymentTypeRequest(d.Get("payment_type").(string))
request["RegionId"] = client.RegionId
request["ClientToken"] = buildClientToken("CreateDBInstance")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-03"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_graph_database_db_instance", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["DBInstanceId"]))
gdbService := GdbService{client}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, gdbService.GraphDatabaseDbInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudGraphDatabaseDbInstanceUpdate(d, meta)
}
func resourceAlicloudGraphDatabaseDbInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gdbService := GdbService{client}
object, err := gdbService.DescribeGraphDatabaseDbInstance(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_graph_database_db_instance gdbService.DescribeGraphDatabaseDbInstance Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("db_instance_category", object["Category"])
d.Set("db_instance_description", object["DBInstanceDescription"])
d.Set("db_instance_network_type", object["DBInstanceNetworkType"])
d.Set("db_instance_storage_type", object["DBInstanceStorageType"])
d.Set("db_node_class", object["DBNodeClass"])
d.Set("db_node_storage", formatInt(object["DBNodeStorage"]))
d.Set("db_version", object["DBVersion"])
d.Set("payment_type", convertGraphDatabaseDbInstancePaymentTypeResponse(object["PayType"]))
d.Set("status", object["DBInstanceStatus"])
d.Set("vswitch_id", object["VSwitchId"])
d.Set("zone_id", object["ZoneId"])
if DBInstanceIPArray, ok := object["DBInstanceIPArray"]; ok {
DBInstanceIPArrayAry, ok := DBInstanceIPArray.([]interface{})
if ok && len(DBInstanceIPArrayAry) > 0 {
DBInstanceIPArraySli := make([]map[string]interface{}, 0)
for _, DBInstanceIPArrayArg := range DBInstanceIPArrayAry {
DBInstanceIPArrayMap := make(map[string]interface{})
DBInstanceIPArrayMap["security_ips"] = DBInstanceIPArrayArg.(map[string]interface{})["SecurityIps"]
DBInstanceIPArrayMap["db_instance_ip_array_name"] = DBInstanceIPArrayArg.(map[string]interface{})["DBInstanceIPArrayName"]
if v, ok := DBInstanceIPArrayArg.(map[string]interface{})["DBInstanceIPArrayAttribute"]; ok {
DBInstanceIPArrayMap["db_instance_ip_array_attribute"] = v
}
DBInstanceIPArraySli = append(DBInstanceIPArraySli, DBInstanceIPArrayMap)
}
d.Set("db_instance_ip_array", DBInstanceIPArraySli)
}
}
return nil
}
func resourceAlicloudGraphDatabaseDbInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gdbService := GdbService{client}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"DBInstanceId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("db_instance_description") {
update = true
}
if v, ok := d.GetOk("db_instance_description"); ok {
request["DBInstanceDescription"] = v
}
if update {
action := "ModifyDBInstanceDescription"
conn, err := client.NewGdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-03"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, gdbService.GraphDatabaseDbInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("db_instance_description")
}
update = false
modifyDBInstanceAccessWhiteListReq := map[string]interface{}{
"DBInstanceId": d.Id(),
}
if d.HasChange("db_instance_ip_array") {
oraw, nraw := d.GetChange("db_instance_ip_array")
o := oraw.(*schema.Set)
n := nraw.(*schema.Set)
remove := o.Difference(n).List()
create := n.Difference(o).List()
if len(remove) > 0 {
for _, dBInstanceIPArray := range remove {
dBInstanceIPArrayArg := dBInstanceIPArray.(map[string]interface{})
action := "ModifyDBInstanceAccessWhiteList"
conn, err := client.NewGdsClient()
if err != nil {
return WrapError(err)
}
if v, ok := dBInstanceIPArrayArg["db_instance_ip_array_name"]; !ok || v.(string) == "default" {
continue
}
modifyDBInstanceAccessWhiteListReq["DBInstanceIPArrayName"] = dBInstanceIPArrayArg["db_instance_ip_array_name"]
modifyDBInstanceAccessWhiteListReq["SecurityIps"] = "Empty"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-03"), StringPointer("AK"), nil, modifyDBInstanceAccessWhiteListReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyDBInstanceAccessWhiteListReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
}
if len(create) > 0 {
for _, dBInstanceIPArray := range create {
dBInstanceIPArrayArg := dBInstanceIPArray.(map[string]interface{})
action := "ModifyDBInstanceAccessWhiteList"
conn, err := client.NewGdsClient()
if err != nil {
return WrapError(err)
}
modifyDBInstanceAccessWhiteListReq["DBInstanceIPArrayAttribute"] = dBInstanceIPArrayArg["db_instance_ip_array_attribute"]
modifyDBInstanceAccessWhiteListReq["DBInstanceIPArrayName"] = dBInstanceIPArrayArg["db_instance_ip_array_name"]
modifyDBInstanceAccessWhiteListReq["SecurityIps"] = dBInstanceIPArrayArg["security_ips"]
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-03"), StringPointer("AK"), nil, modifyDBInstanceAccessWhiteListReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyDBInstanceAccessWhiteListReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
}
d.SetPartial("db_instance_ip_array")
}
modifyDBInstanceSpecReq := map[string]interface{}{
"DBInstanceId": d.Id(),
}
modifyDBInstanceSpecReq["DBInstanceClass"] = d.Get("db_node_class")
if !d.IsNewResource() && d.HasChange("db_node_class") {
update = true
}
modifyDBInstanceSpecReq["DBInstanceStorage"] = d.Get("db_node_storage")
if !d.IsNewResource() && d.HasChange("db_node_storage") {
update = true
}
modifyDBInstanceSpecReq["RegionId"] = client.RegionId
if update {
modifyDBInstanceSpecReq["DBInstanceStorageType"] = d.Get("db_instance_storage_type")
action := "ModifyDBInstanceSpec"
conn, err := client.NewGdsClient()
if err != nil {
return WrapError(err)
}
modifyDBInstanceSpecReq["ClientToken"] = buildClientToken("ModifyDBInstanceSpec")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-03"), StringPointer("AK"), nil, modifyDBInstanceSpecReq, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyDBInstanceSpecReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, gdbService.GraphDatabaseDbInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("db_instance_storage_type")
d.SetPartial("db_node_class")
d.SetPartial("db_node_storage")
}
d.Partial(false)
return resourceAlicloudGraphDatabaseDbInstanceRead(d, meta)
}
func resourceAlicloudGraphDatabaseDbInstanceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
gdbService := GdbService{client}
action := "DeleteDBInstance"
var response map[string]interface{}
conn, err := client.NewGdsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DBInstanceId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-03"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstance.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, gdbService.GraphDatabaseDbInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
func convertGraphDatabaseDbInstancePaymentTypeRequest(source interface{}) interface{} {
switch source {
case "PayAsYouGo":
return "Postpaid"
}
return source
}
func convertGraphDatabaseDbInstancePaymentTypeResponse(source interface{}) interface{} {
switch source {
case "Postpaid":
return "PayAsYouGo"
}
return source
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudHavip() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudHavipCreate,
Read: resourceAlicloudHavipRead,
Update: resourceAlicloudHavipUpdate,
Delete: resourceAlicloudHavipDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"havip_name": {
Type: schema.TypeString,
Optional: true,
},
"ip_address": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudHavipCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
action := "CreateHaVip"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("havip_name"); ok {
request["Name"] = v
}
if v, ok := d.GetOk("ip_address"); ok {
request["IpAddress"] = v
}
request["RegionId"] = client.RegionId
request["VSwitchId"] = d.Get("vswitch_id")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_havip", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["HaVipId"]))
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, vpcService.HavipStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudHavipRead(d, meta)
}
func resourceAlicloudHavipRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeHavip(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_havip vpcService.DescribeHavip Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", object["Description"])
d.Set("havip_name", object["Name"])
d.Set("ip_address", object["IpAddress"])
d.Set("status", object["Status"])
d.Set("vswitch_id", object["VSwitchId"])
return nil
}
func resourceAlicloudHavipUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"HaVipId": d.Id(),
}
request["RegionId"] = client.RegionId
if d.HasChange("description") {
update = true
request["Description"] = d.Get("description")
}
if d.HasChange("havip_name") {
update = true
request["Name"] = d.Get("havip_name")
}
if update {
action := "ModifyHaVipAttribute"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudHavipRead(d, meta)
}
func resourceAlicloudHavipDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteHaVip"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"HaVipId": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidHaVipId.NotFound", "InvalidRegionId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliyunHaVipAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunHaVipAttachmentCreate,
Read: resourceAliyunHaVipAttachmentRead,
Delete: resourceAliyunHaVipAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"havip_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAliyunHaVipAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
haVipService := HaVipService{client}
request := vpc.CreateAssociateHaVipRequest()
request.RegionId = client.RegionId
request.HaVipId = Trim(d.Get("havip_id").(string))
request.InstanceId = Trim(d.Get("instance_id").(string))
if err := resource.Retry(5*time.Minute, func() *resource.RetryError {
ar := request
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.AssociateHaVip(ar)
})
if err != nil {
if IsExpectedErrors(err, []string{"TaskConflict", "IncorrectHaVipStatus", "InvalidVip.Status"}) {
return resource.RetryableError(fmt.Errorf("AssociateHaVip got an error: %#v", err))
}
return resource.NonRetryableError(fmt.Errorf("AssociateHaVip got an error: %#v", err))
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}); err != nil {
return err
}
//check the havip attachment
if err := haVipService.WaitForHaVipAttachment(request.HaVipId, request.InstanceId, 5*DefaultTimeout); err != nil {
return fmt.Errorf("Wait for havip attachment got error: %#v", err)
}
d.SetId(request.HaVipId + COLON_SEPARATED + request.InstanceId)
return resourceAliyunHaVipAttachmentRead(d, meta)
}
func resourceAliyunHaVipAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
haVipService := HaVipService{client}
haVipId, instanceId, err := getHaVipIdAndInstanceId(d, meta)
err = haVipService.DescribeHaVipAttachment(haVipId, instanceId)
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return fmt.Errorf("Error Describe HaVip Attribute: %#v", err)
}
d.Set("havip_id", haVipId)
d.Set("instance_id", instanceId)
return nil
}
func resourceAliyunHaVipAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
haVipService := HaVipService{client}
haVipId, instanceId, err := getHaVipIdAndInstanceId(d, meta)
if err != nil {
return err
}
request := vpc.CreateUnassociateHaVipRequest()
request.RegionId = client.RegionId
request.HaVipId = haVipId
request.InstanceId = instanceId
return resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.UnassociateHaVip(request)
})
//Waiting for unassociate the havip
if err != nil {
if IsExpectedErrors(err, []string{"TaskConflict"}) {
return resource.RetryableError(fmt.Errorf("Unassociate HaVip timeout and got an error:%#v.", err))
}
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
//Eusure the instance has been unassociated truly.
err = haVipService.DescribeHaVipAttachment(haVipId, instanceId)
if err != nil {
if NotFoundError(err) {
return nil
}
return resource.NonRetryableError(err)
}
return resource.RetryableError(fmt.Errorf("Unassociate HaVip timeout."))
})
}
package alicloud
import (
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/hbase"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudHBaseInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudHBaseInstanceCreate,
Read: resourceAlicloudHBaseInstanceRead,
Update: resourceAlicloudHBaseInstanceUpdate,
Delete: resourceAlicloudHBaseInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
Update: schema.DefaultTimeout(30 * time.Minute),
Delete: schema.DefaultTimeout(30 * time.Minute),
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(2, 128),
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"engine": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"hbase", "hbaseue", "bds"}, false),
Default: "hbase",
},
"engine_version": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"master_instance_type": {
Type: schema.TypeString,
Required: true,
},
"master_instance_quantity": {
Type: schema.TypeInt,
Computed: true,
},
"core_instance_type": {
Type: schema.TypeString,
Required: true,
},
"core_instance_quantity": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(1, 200),
Optional: true,
Default: 2,
},
"core_disk_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"cloud_ssd", "cloud_essd_pl1", "cloud_efficiency", "local_hdd_pro", "local_ssd_pro", ""}, false),
DiffSuppressFunc: engineDiffSuppressFunc,
},
"core_disk_size": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.Any(validation.IntBetween(20, 64000), validation.IntInSlice([]int{0})),
Default: 400,
DiffSuppressFunc: engineDiffSuppressFunc,
},
"pay_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{string(PostPaid), string(PrePaid)}, false),
Default: PostPaid,
},
"duration": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 24, 36}),
DiffSuppressFunc: payTypePostPaidDiffSuppressFunc,
},
"auto_renew": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Computed: true,
DiffSuppressFunc: payTypePostPaidDiffSuppressFunc,
},
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"cold_storage_size": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.Any(validation.IntBetween(800, 1000000), validation.IntInSlice([]int{0})),
Default: 0,
},
"maintain_start_time": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"maintain_end_time": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"deletion_protection": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"immediate_delete_flag": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"tags": tagsSchema(),
"account": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(0, 128),
},
"password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
ValidateFunc: validation.StringLenBetween(0, 128),
},
"ip_white": {
Type: schema.TypeString,
Optional: true,
Computed: true,
DiffSuppressFunc: whiteIpListDiffSuppressFunc,
},
"security_groups": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"ui_proxy_conn_addrs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"conn_addr_port": {
Type: schema.TypeString,
Computed: true,
},
"conn_addr": {
Type: schema.TypeString,
Computed: true,
},
"net_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"zk_conn_addrs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"conn_addr_port": {
Type: schema.TypeString,
Computed: true,
},
"conn_addr": {
Type: schema.TypeString,
Computed: true,
},
"net_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"slb_conn_addrs": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"conn_addr_port": {
Type: schema.TypeString,
Computed: true,
},
"conn_addr": {
Type: schema.TypeString,
Computed: true,
},
"net_type": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func checkParams(request *hbase.CreateClusterRequest) error {
if request.Engine == "bds" && request.VSwitchId == "" {
return WrapError(Error("bds is not support classic"))
}
return nil
}
func buildHBaseCreateRequest(d *schema.ResourceData, meta interface{}) (*hbase.CreateClusterRequest, error) {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
request := hbase.CreateCreateClusterRequest()
request.ClusterName = Trim(d.Get("name").(string))
request.RegionId = string(client.Region)
request.ZoneId = Trim(d.Get("zone_id").(string))
request.Engine = Trim(d.Get("engine").(string))
request.EngineVersion = Trim(d.Get("engine_version").(string))
request.MasterInstanceType = Trim(d.Get("master_instance_type").(string))
request.CoreInstanceType = Trim(d.Get("core_instance_type").(string))
request.NodeCount = requests.NewInteger(d.Get("core_instance_quantity").(int))
request.DiskType = Trim(d.Get("core_disk_type").(string))
request.DiskSize = requests.NewInteger(d.Get("core_disk_size").(int))
request.PayType = Trim(d.Get("pay_type").(string))
if d.Get("duration").(int) > 9 {
request.PeriodUnit = "year"
request.Period = requests.NewInteger(d.Get("duration").(int) / 12)
} else {
request.PeriodUnit = "month"
request.Period = requests.NewInteger(d.Get("duration").(int))
}
if d.Get("auto_renew").(bool) {
request.AutoRenewPeriod = requests.NewInteger(1)
}
vswitchId := Trim(d.Get("vswitch_id").(string))
if vswitchId != "" {
request.VSwitchId = vswitchId
// check vswitchId in zone
vsw, err := vpcService.DescribeVSwitch(vswitchId)
if err != nil {
return nil, WrapError(err)
}
if request.ZoneId == "" {
request.ZoneId = vsw.ZoneId
} else if strings.Contains(request.ZoneId, MULTI_IZ_SYMBOL) {
zonestr := strings.Split(strings.SplitAfter(request.ZoneId, "(")[1], ")")[0]
if !strings.Contains(zonestr, string([]byte(vsw.ZoneId)[len(vsw.ZoneId)-1])) {
return nil, WrapError(Error("The specified vswitch %s isn't in the multi zone %s.", vsw.VSwitchId, request.ZoneId))
}
} else if request.ZoneId != vsw.ZoneId {
return nil, WrapError(Error("The specified vswitch %s isn't in the zone %s.", vsw.VSwitchId, request.ZoneId))
}
request.VpcId = vsw.VpcId
}
if d.Get("cold_storage_size").(int) < 0 {
return nil, WrapError(Error("cold_storage_size=%s is invalid", d.Get("cold_storage_size")))
}
request.ColdStorageSize = requests.NewInteger(d.Get("cold_storage_size").(int))
request.SecurityIPList = d.Get("ip_white").(string)
return request, checkParams(request)
}
func resourceAlicloudHBaseInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
hBaseService := HBaseService{client}
request, err := buildHBaseCreateRequest(d, meta)
if err != nil {
return WrapError(err)
}
raw, err := client.WithHbaseClient(func(client *hbase.Client) (interface{}, error) {
return client.CreateCluster(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_hbase_instance", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*hbase.CreateClusterResponse)
d.SetId(response.ClusterId)
stateConf := BuildStateConf([]string{Hb_LAUNCHING, Hb_CREATING}, []string{Hb_ACTIVATION}, d.Timeout(schema.TimeoutCreate),
5*time.Minute, hBaseService.HBaseClusterStateRefreshFunc(d.Id(), []string{Hb_CREATE_FAILED}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapError(err)
}
return resourceAlicloudHBaseInstanceUpdate(d, meta)
}
func resourceAlicloudHBaseInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
hbaseService := HBaseService{client}
instance, err := hbaseService.DescribeHBaseInstance(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", instance["InstanceName"])
d.Set("zone_id", instance["ZoneId"])
d.Set("engine", instance["Engine"])
d.Set("engine_version", instance["MajorVersion"])
d.Set("master_instance_type", instance["MasterInstanceType"])
d.Set("master_instance_quantity", instance["MasterNodeCount"])
d.Set("core_instance_type", instance["CoreInstanceType"])
d.Set("core_instance_quantity", instance["CoreNodeCount"])
d.Set("core_disk_size", formatInt(instance["CoreDiskCount"])*formatInt(instance["CoreDiskSize"]))
d.Set("core_disk_type", instance["CoreDiskType"])
// Postpaid -> PostPaid
if instance["PayType"] == string(Postpaid) {
d.Set("pay_type", string(PostPaid))
} else if instance["PayType"] == string(Prepaid) {
d.Set("pay_type", string(PrePaid))
period, err := computePeriodByUnit(instance["CreatedTimeUTC"], instance["ExpireTimeUTC"], d.Get("duration").(int), "Month")
if err != nil {
return WrapError(err)
}
d.Set("duration", period)
}
// now sdk can not get right value, "auto_renew", "is_cold_storage".
d.Set("auto_renew", instance["AutoRenewal"])
d.Set("cold_storage_size", instance["ColdStorageSize"])
d.Set("vpc_id", instance["VpcId"])
d.Set("vswitch_id", instance["VswitchId"])
d.Set("maintain_start_time", instance["MaintainStartTime"])
d.Set("maintain_end_time", instance["MaintainEndTime"])
d.Set("deletion_protection", instance["IsDeletionProtection"])
d.Set("tags", tagsToMap(instance["Tags"]))
ipWhitelist, err := hbaseService.DescribeIpWhitelist(d.Id())
if err != nil {
return WrapError(err)
}
ipWhite := LOCAL_HOST_IP
for _, value := range ipWhitelist.Groups.Group {
if value.GroupName == "default" {
ipWhite = strings.Join(value.IpList.Ip, ",")
}
}
d.Set("ip_white", ipWhite)
securityGroups, err := hbaseService.DescribeSecurityGroups(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("security_groups", securityGroups.SecurityGroupIds.SecurityGroupId)
conns, err := hbaseService.DescribeClusterConnection(d.Id())
if err != nil {
return WrapError(err)
}
// UiProxyConnAddrInfo
var uiConnAddrs []map[string]interface{}
e := map[string]interface{}{
"conn_addr_port": conns.UiProxyConnAddrInfo.ConnAddrPort,
"conn_addr": conns.UiProxyConnAddrInfo.ConnAddr,
"net_type": conns.UiProxyConnAddrInfo.NetType,
}
uiConnAddrs = append(uiConnAddrs, e)
d.Set("ui_proxy_conn_addrs", uiConnAddrs)
// ZKConnAddrs
var zkConnAddrs []map[string]interface{}
for _, v := range conns.ZkConnAddrs.ZkConnAddr {
e := map[string]interface{}{
"conn_addr_port": v.ConnAddrPort,
"conn_addr": v.ConnAddr,
"net_type": v.NetType,
}
zkConnAddrs = append(zkConnAddrs, e)
}
d.Set("zk_conn_addrs", zkConnAddrs)
// slbConnAddrs
var slbConnAddrs []map[string]interface{}
for _, v := range conns.SlbConnAddrs.SlbConnAddr {
e := map[string]interface{}{
"conn_addr_port": v.ConnAddrInfo.ConnAddrPort,
"conn_addr": v.ConnAddrInfo.ConnAddr,
"net_type": v.ConnAddrInfo.NetType,
}
slbConnAddrs = append(slbConnAddrs, e)
}
d.Set("slb_conn_addrs", slbConnAddrs)
return nil
}
func resourceAlicloudHBaseInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
hBaseService := HBaseService{client}
d.Partial(true)
if d.HasChange("pay_type") {
object, err := hBaseService.DescribeHBaseInstance(d.Id())
if err != nil {
return WrapError(err)
}
target := strings.ToLower(d.Get("pay_type").(string))
if strings.ToLower(object["PayType"].(string)) != target {
request := hbase.CreateConvertInstanceRequest()
request.ClusterId = d.Id()
request.PayType = string(Postpaid)
if target == "prepaid" {
request.PayType = string(Prepaid)
}
if d.Get("duration").(int) > 9 {
request.PricingCycle = "year"
request.Duration = requests.NewInteger(d.Get("duration").(int) / 12)
} else {
request.PricingCycle = "month"
request.Duration = requests.NewInteger(d.Get("duration").(int))
}
raw, err := client.WithHbaseClient(func(hbaseClient *hbase.Client) (interface{}, error) {
return hbaseClient.ConvertInstance(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{Hb_ACTIVATION}, d.Timeout(schema.TimeoutUpdate),
2*time.Minute, hBaseService.HBaseClusterStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("pay_type")
}
}
if d.HasChange("ip_white") {
request := hbase.CreateModifyIpWhitelistRequest()
request.ClusterId = d.Id()
request.IpList = d.Get("ip_white").(string)
request.GroupName = "default"
request.IpVersion = "4"
raw, err := client.WithHbaseClient(func(hbaseClient *hbase.Client) (interface{}, error) {
return hbaseClient.ModifyIpWhitelist(request)
})
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("ip_white")
}
if d.HasChange("security_groups") {
request := hbase.CreateModifySecurityGroupsRequest()
request.ClusterId = d.Id()
securityGroups := d.Get("security_groups").(*schema.Set).List()
if securityGroups != nil && len(securityGroups) > 0 {
request.SecurityGroupIds = strings.Join(expandStringList(securityGroups), ",")
} else {
request.SecurityGroupIds = " "
}
raw, err := client.WithHbaseClient(func(hbaseClient *hbase.Client) (interface{}, error) {
return hbaseClient.ModifySecurityGroups(request)
})
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{Hb_ACTIVATION}, d.Timeout(schema.TimeoutUpdate),
5*time.Second, hBaseService.HBaseClusterStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("security_groups")
}
if d.HasChange("maintain_start_time") || d.HasChange("maintain_end_time") {
request := hbase.CreateModifyInstanceMaintainTimeRequest()
request.ClusterId = d.Id()
request.MaintainStartTime = d.Get("maintain_start_time").(string)
request.MaintainEndTime = d.Get("maintain_end_time").(string)
raw, err := client.WithHbaseClient(func(client *hbase.Client) (interface{}, error) {
return client.ModifyInstanceMaintainTime(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("maintain_start_time")
d.SetPartial("maintain_end_time")
}
if d.HasChange("deletion_protection") {
if err := hBaseService.ModifyClusterDeletionProtection(d.Id(), d.Get("deletion_protection").(bool)); err != nil {
return WrapError(err)
}
d.SetPartial("deletion_protection")
}
if err := hBaseService.setInstanceTags(d); err != nil {
return WrapError(err)
}
if d.HasChange("account") || d.HasChange("password") {
request := hbase.CreateModifyUIAccountPasswordRequest()
request.ClusterId = d.Id()
request.AccountName = d.Get("account").(string)
request.AccountPassword = d.Get("password").(string)
raw, err := client.WithHbaseClient(func(client *hbase.Client) (interface{}, error) {
return client.ModifyUIAccountPassword(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("account")
d.SetPartial("password")
}
if d.IsNewResource() {
d.Partial(false)
return resourceAlicloudHBaseInstanceRead(d, meta)
}
if d.HasChange("name") {
request := hbase.CreateModifyInstanceNameRequest()
request.ClusterId = d.Id()
request.ClusterName = d.Get("name").(string)
raw, err := client.WithHbaseClient(func(client *hbase.Client) (interface{}, error) {
return client.ModifyInstanceName(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("name")
}
if d.HasChange("core_instance_quantity") {
request := hbase.CreateResizeNodeCountRequest()
request.ClusterId = d.Id()
request.NodeCount = requests.NewInteger(d.Get("core_instance_quantity").(int))
raw, err := client.WithHbaseClient(func(client *hbase.Client) (interface{}, error) {
return client.ResizeNodeCount(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
// Cumbersome operation,async call, wait for state change
// wait instance status is running after modifying
stateConf := BuildStateConf([]string{Hb_NODE_RESIZING}, []string{Hb_ACTIVATION}, d.Timeout(schema.TimeoutUpdate),
5*time.Minute, hBaseService.HBaseClusterStateRefreshFunc(d.Id(), []string{Hb_NODE_RESIZING_FAILED}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("core_instance_quantity")
}
if d.HasChange("master_instance_type") || d.HasChange("core_instance_type") {
request := hbase.CreateModifyInstanceTypeRequest()
request.ClusterId = d.Id()
typeChange := false
if d.HasChange("master_instance_type") &&
d.Get("engine") != "bds" && d.Get("core_instance_quantity").(int) > 1 {
request.MasterInstanceType = d.Get("master_instance_type").(string)
typeChange = true
}
if d.HasChange("core_instance_type") {
request.CoreInstanceType = d.Get("core_instance_type").(string)
typeChange = true
}
if typeChange {
raw, err := client.WithHbaseClient(func(client *hbase.Client) (interface{}, error) {
return client.ModifyInstanceType(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
// Cumbersome operation,async call, wait for state change
// wait instance status is running after modifying
stateConf := BuildStateConf([]string{Hb_LEVEL_MODIFY}, []string{Hb_ACTIVATION}, d.Timeout(schema.TimeoutUpdate),
5*time.Minute, hBaseService.HBaseClusterStateRefreshFunc(d.Id(), []string{Hb_LEVEL_MODIFY_FAILED}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("master_instance_type")
d.SetPartial("core_instance_type")
}
}
if d.HasChange("core_disk_size") && d.Get("engine") != "bds" {
request := hbase.CreateResizeDiskSizeRequest()
request.ClusterId = d.Id()
request.NodeDiskSize = requests.NewInteger(d.Get("core_disk_size").(int))
raw, err := client.WithHbaseClient(func(client *hbase.Client) (interface{}, error) {
return client.ResizeDiskSize(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
// Cumbersome operation,async call, wait for state change
// wait instance status is running after modifying
stateConf := BuildStateConf([]string{Hb_DISK_RESIZING}, []string{Hb_ACTIVATION}, d.Timeout(schema.TimeoutUpdate),
2*time.Minute, hBaseService.HBaseClusterStateRefreshFunc(d.Id(), []string{Hb_DISK_RESIZE_FAILED}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("core_disk_size")
}
if d.HasChange("cold_storage_size") {
request := hbase.CreateResizeColdStorageSizeRequest()
request.ClusterId = d.Id()
request.ColdStorageSize = requests.NewInteger(d.Get("cold_storage_size").(int))
raw, err := client.WithHbaseClient(func(client *hbase.Client) (interface{}, error) {
return client.ResizeColdStorageSize(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
// Cumbersome operation,async call, wait for state change
// wait instance status is running after modifying
stateConf := BuildStateConf([]string{Hb_HBASE_COLD_EXPANDING}, []string{Hb_ACTIVATION}, d.Timeout(schema.TimeoutUpdate),
10*time.Second, hBaseService.HBaseClusterStateRefreshFunc(d.Id(), []string{Hb_DISK_RESIZE_FAILED}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("cold_storage_size")
}
d.Partial(false)
return resourceAlicloudHBaseInstanceRead(d, meta)
}
func resourceAlicloudHBaseInstanceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
hbaseService := HBaseService{client}
request := hbase.CreateDeleteInstanceRequest()
request.ClusterId = d.Id()
if v, ok := d.GetOk("immediate_delete_flag"); ok {
request.ImmediateDeleteFlag = requests.NewBoolean(v.(bool))
}
raw, err := client.WithHbaseClient(func(hbaseClient *hbase.Client) (interface{}, error) {
return hbaseClient.DeleteInstance(request)
})
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
if err != nil {
if IsExpectedErrors(err, []string{"Instance.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{Hb_DELETING}, []string{}, d.Timeout(schema.TimeoutDelete), 1*time.Minute, hbaseService.HBaseClusterStateRefreshFunc(d.Id(), []string{}))
_, err = stateConf.WaitForState()
return WrapError(err)
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudHbrEcsBackupClient() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudHbrEcsBackupClientCreate,
Read: resourceAlicloudHbrEcsBackupClientRead,
Update: resourceAlicloudHbrEcsBackupClientUpdate,
Delete: resourceAlicloudHbrEcsBackupClientDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"data_network_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"CLASSIC", "PUBLIC", "VPC"}, false),
},
"data_proxy_setting": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"CUSTOM", "DISABLE", "USE_CONTROL_PROXY"}, false),
},
"max_cpu_core": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"max_worker": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"proxy_host": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"proxy_password": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"proxy_port": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"proxy_user": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"ACTIVATED", "STOPPED", "INSTALL_FAILED", "REGISTERED", "DEACTIVATED", "INSTALLING", "NOT_INSTALLED", "UPGRADING", "UPGRADE_FAILED", "UNINSTALLING", "UNINSTALL_FAILED", "UNKNOWN"}, false),
},
"use_https": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
},
}
}
func resourceAlicloudHbrEcsBackupClientCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "InstallBackupClients"
request := make(map[string]interface{})
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
request["InstanceIds"] = "[\"" + d.Get("instance_id").(string) + "\"]"
wait := incrementalWait(30*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"CloudAssistNotRunningOnInstance"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_hbr_ecs_backup_client", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
hbrService := HbrService{client}
taskId := fmt.Sprint(response["TaskId"])
taskConf := BuildStateConf([]string{}, []string{"ACTIVATED"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, hbrService.HbrTaskRefreshFunc(taskId, []string{"INSTALL_FAILED", "DEACTIVATED", "UNKNOWN"}))
if _, err := taskConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
taskResult, err := hbrService.DescribeHbrTask(taskId)
if err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetId(fmt.Sprint(taskResult["ClientId"]))
return resourceAlicloudHbrEcsBackupClientUpdate(d, meta)
}
func resourceAlicloudHbrEcsBackupClientRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
hbrService := HbrService{client}
object, err := hbrService.DescribeHbrEcsBackupClient(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_hbr_ecs_backup_client hbrService.DescribeHbrEcsBackupClient Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_id", object["InstanceId"])
d.Set("status", object["Status"])
if object["Settings"] != nil {
d.Set("use_https", object["Settings"].(map[string]interface{})["UseHttps"])
d.Set("data_network_type", object["Settings"].(map[string]interface{})["DataNetworkType"])
d.Set("data_proxy_setting", object["Settings"].(map[string]interface{})["DataProxySetting"])
d.Set("max_cpu_core", object["Settings"].(map[string]interface{})["MaxCpuCore"])
d.Set("max_worker", object["Settings"].(map[string]interface{})["MaxWorker"])
d.Set("proxy_host", object["Settings"].(map[string]interface{})["ProxyHost"])
d.Set("proxy_password", object["Settings"].(map[string]interface{})["ProxyPassword"])
d.Set("proxy_user", object["Settings"].(map[string]interface{})["ProxyUser"])
d.Set("proxy_port", fmt.Sprint(formatInt(object["Settings"].(map[string]interface{})["ProxyPort"])))
}
return nil
}
func resourceAlicloudHbrEcsBackupClientUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"ClientId": d.Id(),
}
if d.HasChange("use_https") || d.IsNewResource() {
update = true
if v, ok := d.GetOkExists("use_https"); ok {
request["UseHttps"] = v
}
}
if d.HasChange("data_network_type") {
update = true
if v, ok := d.GetOk("data_network_type"); ok {
request["DataNetworkType"] = v
}
}
if d.HasChange("data_proxy_setting") {
update = true
if v, ok := d.GetOk("data_proxy_setting"); ok {
request["DataProxySetting"] = v
}
}
if d.HasChange("max_cpu_core") {
update = true
if v, ok := d.GetOk("max_cpu_core"); ok {
request["MaxCpuCore"] = v
}
}
if d.HasChange("max_worker") {
update = true
if v, ok := d.GetOk("max_worker"); ok {
request["MaxWorker"] = v
}
}
if d.HasChange("proxy_host") {
update = true
if v, ok := d.GetOk("proxy_host"); ok {
request["ProxyHost"] = v
}
}
if d.HasChange("proxy_password") {
update = true
if v, ok := d.GetOk("proxy_password"); ok {
request["ProxyPassword"] = v
}
}
if d.HasChange("proxy_port") {
update = true
if v, ok := d.GetOk("proxy_port"); ok {
request["ProxyPort"] = v
}
}
if d.HasChange("proxy_user") {
update = true
if v, ok := d.GetOk("proxy_user"); ok {
request["ProxyUser"] = v
}
}
if update {
action := "UpdateClientSettings"
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
}
if d.HasChange("status") {
client := meta.(*connectivity.AliyunClient)
hbrService := HbrService{client}
object, err := hbrService.DescribeHbrEcsBackupClient(d.Id())
if err != nil {
return WrapError(err)
}
target := d.Get("status").(string)
if object["Status"].(string) != target {
if target == "ACTIVATED" {
err = resourceAlicloudHbrEcsBackupClientCreate(d, meta)
} else if target == "STOPPED" {
err = resourceAlicloudHbrEcsBackupClientUninstall(d, meta)
} else {
return WrapError(Error(FailedToReachTargetStatus, object["Status"].(string)))
}
if err != nil {
return WrapError(err)
}
}
}
d.SetPartial("status")
return resourceAlicloudHbrEcsBackupClientRead(d, meta)
}
func resourceAlicloudHbrEcsBackupClientUninstall(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "UninstallBackupClients"
var response map[string]interface{}
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ClientIds": "[\"" + d.Id() + "\"]",
}
request["InstanceIds"] = "[\"" + d.Get("instance_id").(string) + "\"]"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
hbrService := HbrService{client}
taskConf := BuildStateConf([]string{}, []string{"NOT_INSTALLED"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, hbrService.HbrTaskRefreshFunc(fmt.Sprint(response["TaskId"]), []string{"UNINSTALL_FAILED", "UNKNOWN"}))
if _, err := taskConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
func resourceAlicloudHbrEcsBackupClientDelete(d *schema.ResourceData, meta interface{}) error {
err := resourceAlicloudHbrEcsBackupClientUninstall(d, meta)
if err != nil {
return WrapError(err)
}
client := meta.(*connectivity.AliyunClient)
action := "DeleteBackupClient"
var response map[string]interface{}
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ClientId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
return nil
}
package alicloud
import (
"fmt"
"log"
"strconv"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudHbrEcsBackupPlan() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudHbrEcsBackupPlanCreate,
Read: resourceAlicloudHbrEcsBackupPlanRead,
Update: resourceAlicloudHbrEcsBackupPlanUpdate,
Delete: resourceAlicloudHbrEcsBackupPlanDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"ecs_backup_plan_name": {
Type: schema.TypeString,
Required: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"vault_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"backup_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"COMPLETE"}, false),
},
"retention": {
Type: schema.TypeString,
Required: true,
},
"schedule": {
Type: schema.TypeString,
Required: true,
},
"path": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"disabled": {
Type: schema.TypeBool,
Computed: true,
Optional: true,
},
"detail": {
Type: schema.TypeString,
Optional: true,
},
"exclude": {
Type: schema.TypeString,
Optional: true,
},
"include": {
Type: schema.TypeString,
Optional: true,
},
"options": {
Type: schema.TypeString,
Optional: true,
},
"speed_limit": {
Type: schema.TypeString,
Optional: true,
},
"update_paths": {
Type: schema.TypeBool,
Optional: true,
Deprecated: "Attribute update_paths has been deprecated in v1.139.0+ and you do not need to set it anymore.",
},
},
}
}
func resourceAlicloudHbrEcsBackupPlanCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateBackupPlan"
request := make(map[string]interface{})
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
request["BackupType"] = d.Get("backup_type")
if v, ok := d.GetOk("bucket"); ok {
request["Bucket"] = v
}
if v, ok := d.GetOk("detail"); ok {
request["Detail"] = v
}
request["PlanName"] = d.Get("ecs_backup_plan_name")
if v, ok := d.GetOk("exclude"); ok {
request["Exclude"] = v
}
if v, ok := d.GetOk("include"); ok {
request["Include"] = v
}
if v, ok := d.GetOk("instance_id"); ok {
request["InstanceId"] = v
}
if v, ok := d.GetOk("options"); ok {
request["Options"] = v
}
if v, ok := d.GetOk("retention"); ok {
request["Retention"] = v
}
request["Schedule"] = d.Get("schedule")
request["SourceType"] = "ECS_FILE"
if v, ok := d.GetOk("speed_limit"); ok {
request["SpeedLimit"] = v
}
if v, ok := d.GetOk("vault_id"); ok {
request["VaultId"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_hbr_ecs_backup_plan", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetId(fmt.Sprint(response["PlanId"]))
return resourceAlicloudHbrEcsBackupPlanUpdate(d, meta)
}
func resourceAlicloudHbrEcsBackupPlanRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
hbrService := HbrService{client}
object, err := hbrService.DescribeHbrEcsBackupPlan(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_hbr_ecs_backup_plan hbrService.DescribeHbrEcsBackupPlan Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("backup_type", object["BackupType"])
d.Set("detail", object["Detail"])
d.Set("ecs_backup_plan_name", object["PlanName"])
d.Set("exclude", object["Exclude"])
d.Set("include", object["Include"])
d.Set("instance_id", object["InstanceId"])
d.Set("options", object["Options"])
if object["Paths"] != nil {
d.Set("path", object["Paths"].(map[string]interface{})["Path"])
}
d.Set("retention", fmt.Sprint(formatInt(object["Retention"])))
d.Set("schedule", object["Schedule"])
d.Set("speed_limit", object["SpeedLimit"])
d.Set("vault_id", object["VaultId"])
d.Set("disabled", object["Disabled"])
return nil
}
func resourceAlicloudHbrEcsBackupPlanUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
hbrService := HbrService{client}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"PlanId": d.Id(),
}
if v, ok := d.GetOk("vault_id"); ok {
request["VaultId"] = v
}
if !d.IsNewResource() && d.HasChange("detail") {
update = true
if v, ok := d.GetOk("detail"); ok {
request["Detail"] = v
}
}
if !d.IsNewResource() && d.HasChange("ecs_backup_plan_name") {
update = true
request["PlanName"] = d.Get("ecs_backup_plan_name")
}
if !d.IsNewResource() && d.HasChange("exclude") {
update = true
if v, ok := d.GetOk("exclude"); ok {
request["Exclude"] = v
}
}
if !d.IsNewResource() && d.HasChange("include") {
update = true
if v, ok := d.GetOk("include"); ok {
request["Include"] = v
}
}
if !d.IsNewResource() && d.HasChange("options") {
update = true
if v, ok := d.GetOk("options"); ok {
request["Options"] = v
}
}
if d.HasChange("path") {
update = true
request["UpdatePaths"] = true
if v, ok := d.GetOk("path"); ok {
request["Path"] = v
}
}
if !d.IsNewResource() && d.HasChange("retention") {
update = true
}
if v, ok := d.GetOk("retention"); ok {
request["Retention"] = v
}
if !d.IsNewResource() && d.HasChange("schedule") {
update = true
request["Schedule"] = d.Get("schedule")
}
request["SourceType"] = "ECS_FILE"
if !d.IsNewResource() && d.HasChange("speed_limit") {
update = true
if v, ok := d.GetOk("speed_limit"); ok {
request["SpeedLimit"] = v
}
}
if update {
action := "UpdateBackupPlan"
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetPartial("vault_id")
d.SetPartial("detail")
d.SetPartial("ecs_backup_plan_name")
d.SetPartial("exclude")
d.SetPartial("include")
d.SetPartial("options")
d.SetPartial("path")
d.SetPartial("retention")
d.SetPartial("schedule")
d.SetPartial("speed_limit")
}
if d.HasChange("disabled") {
object, err := hbrService.DescribeHbrEcsBackupPlan(d.Id())
if err != nil {
return WrapError(err)
}
target := strconv.FormatBool(d.Get("disabled").(bool))
if strconv.FormatBool(object["Disabled"].(bool)) != target {
action := "EnableBackupPlan"
if target == "false" {
action = "EnableBackupPlan"
} else {
action = "DisableBackupPlan"
}
request := map[string]interface{}{
"PlanId": d.Id(),
}
request["VaultId"] = d.Get("vault_id")
request["SourceType"] = "ECS_FILE"
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
}
}
d.SetPartial("disabled")
d.Partial(false)
return resourceAlicloudHbrEcsBackupPlanRead(d, meta)
}
func resourceAlicloudHbrEcsBackupPlanDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteBackupPlan"
var response map[string]interface{}
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"PlanId": d.Id(),
}
request["SourceType"] = "ECS_FILE"
if v, ok := d.GetOk("vault_id"); ok {
request["VaultId"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
return nil
}
package alicloud
import (
"fmt"
"log"
"strconv"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudHbrNasBackupPlan() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudHbrNasBackupPlanCreate,
Read: resourceAlicloudHbrNasBackupPlanRead,
Update: resourceAlicloudHbrNasBackupPlanUpdate,
Delete: resourceAlicloudHbrNasBackupPlanDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"backup_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"COMPLETE"}, false),
},
"disabled": {
Type: schema.TypeBool,
Computed: true,
Optional: true,
},
"create_time": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Field 'create_time' has been deprecated from provider version 1.153.0.",
},
"file_system_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"nas_backup_plan_name": {
Type: schema.TypeString,
Required: true,
},
"options": {
Type: schema.TypeString,
Optional: true,
},
"path": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"retention": {
Type: schema.TypeString,
Required: true,
},
"schedule": {
Type: schema.TypeString,
Required: true,
},
"vault_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudHbrNasBackupPlanCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateBackupPlan"
request := make(map[string]interface{})
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
request["BackupType"] = d.Get("backup_type")
if v, ok := d.GetOk("create_time"); ok {
request["CreateTime"] = ConvertNasFileSystemStringToUnix(v.(string))
}
if v, ok := d.GetOk("file_system_id"); ok {
request["FileSystemId"] = v
}
request["PlanName"] = d.Get("nas_backup_plan_name")
if v, ok := d.GetOk("options"); ok {
request["Options"] = v
}
if v, ok := d.GetOk("retention"); ok {
request["Retention"] = v
}
request["Schedule"] = d.Get("schedule")
request["SourceType"] = "NAS"
if v, ok := d.GetOk("vault_id"); ok {
request["VaultId"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_hbr_nas_backup_plan", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetId(fmt.Sprint(response["PlanId"]))
return resourceAlicloudHbrNasBackupPlanUpdate(d, meta)
}
func resourceAlicloudHbrNasBackupPlanRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
hbrService := HbrService{client}
object, err := hbrService.DescribeHbrNasBackupPlan(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_hbr_nas_backup_plan hbrService.DescribeHbrNasBackupPlan Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("backup_type", object["BackupType"])
t := int64(formatInt(object["CreateTime"]))
d.Set("create_time", ConvertNasFileSystemUnixToString(d.Get("create_time").(string), t))
d.Set("file_system_id", object["FileSystemId"])
d.Set("nas_backup_plan_name", object["PlanName"])
d.Set("options", object["Options"])
if object["Paths"] != nil {
d.Set("path", object["Paths"].(map[string]interface{})["Path"])
}
d.Set("retention", fmt.Sprint(formatInt(object["Retention"])))
d.Set("schedule", object["Schedule"])
d.Set("vault_id", object["VaultId"])
d.Set("disabled", object["Disabled"])
return nil
}
func resourceAlicloudHbrNasBackupPlanUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
hbrService := HbrService{client}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"PlanId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("retention") {
update = true
}
if v, ok := d.GetOk("retention"); ok {
request["Retention"] = v
}
if v, ok := d.GetOk("vault_id"); ok {
request["VaultId"] = v
}
if !d.IsNewResource() && d.HasChange("nas_backup_plan_name") {
update = true
request["PlanName"] = d.Get("nas_backup_plan_name")
}
if !d.IsNewResource() && d.HasChange("options") {
update = true
if v, ok := d.GetOk("options"); ok {
request["Options"] = v
}
}
if d.HasChange("path") {
update = true
request["UpdatePaths"] = true
if v, ok := d.GetOk("path"); ok {
request["Path"] = v
}
}
if !d.IsNewResource() && d.HasChange("schedule") {
update = true
request["Schedule"] = d.Get("schedule")
}
request["SourceType"] = "NAS"
if update {
action := "UpdateBackupPlan"
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetPartial("retention")
d.SetPartial("vault_id")
d.SetPartial("nas_backup_plan_name")
d.SetPartial("options")
d.SetPartial("path")
d.SetPartial("schedule")
}
if d.HasChange("disabled") {
object, err := hbrService.DescribeHbrNasBackupPlan(d.Id())
if err != nil {
return WrapError(err)
}
target := strconv.FormatBool(d.Get("disabled").(bool))
if strconv.FormatBool(object["Disabled"].(bool)) != target {
action := "EnableBackupPlan"
if target == "false" {
action = "EnableBackupPlan"
} else {
action = "DisableBackupPlan"
}
request := map[string]interface{}{
"PlanId": d.Id(),
}
request["VaultId"] = d.Get("vault_id")
request["SourceType"] = "NAS"
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
}
}
d.SetPartial("disabled")
d.Partial(false)
return resourceAlicloudHbrNasBackupPlanRead(d, meta)
}
func resourceAlicloudHbrNasBackupPlanDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteBackupPlan"
var response map[string]interface{}
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"PlanId": d.Id(),
}
request["SourceType"] = "NAS"
if v, ok := d.GetOk("vault_id"); ok {
request["VaultId"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
{
action := "DetachNasFileSystem"
request := map[string]interface{}{
"PlanId": d.Id(),
}
request["VaultId"] = d.Get("vault_id")
if v, ok := d.GetOk("file_system_id"); ok {
request["FileSystemId"] = v
}
if v, ok := d.GetOk("create_time"); ok {
request["CreateTime"] = ConvertNasFileSystemStringToUnix(v.(string))
}
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"NasFileSystemNotExist"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
}
return nil
}
func ConvertNasFileSystemUnixToString(v string, t int64) string {
var s string
c := time.Unix(t, 0)
if strings.HasSuffix(v, "CST") {
s = fmt.Sprint(c.Format("2006-01-02T15:04:05CST"))
} else if strings.HasSuffix(v, "Z") {
s = fmt.Sprint(c.Format("2006-01-02T15:04:05Z"))
} else {
s = fmt.Sprint(c.Format("2006-01-02T15:04:05CST"))
}
return s
}
func ConvertNasFileSystemStringToUnix(v string) int64 {
var t time.Time
if strings.HasSuffix(v, "CST") {
t, _ = time.ParseInLocation("2006-01-02T15:04:05CST", v, time.Local)
} else if strings.HasSuffix(v, "Z") {
t, _ = time.ParseInLocation("2006-01-02T15:04:05Z", v, time.FixedZone("CST", 8*3600))
} else {
t, _ = time.ParseInLocation("2006-01-02T15:04:05CST", v, time.Local)
}
return t.Unix()
}
package alicloud
import (
"fmt"
"log"
"strconv"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudHbrOssBackupPlan() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudHbrOssBackupPlanCreate,
Read: resourceAlicloudHbrOssBackupPlanRead,
Update: resourceAlicloudHbrOssBackupPlanUpdate,
Delete: resourceAlicloudHbrOssBackupPlanDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"backup_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"COMPLETE"}, false),
},
"disabled": {
Type: schema.TypeBool,
Computed: true,
Optional: true,
},
"bucket": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"oss_backup_plan_name": {
Type: schema.TypeString,
Required: true,
},
"prefix": {
Type: schema.TypeString,
Optional: true,
},
"retention": {
Type: schema.TypeString,
Required: true,
},
"schedule": {
Type: schema.TypeString,
Required: true,
},
"vault_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudHbrOssBackupPlanCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateBackupPlan"
request := make(map[string]interface{})
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
request["BackupType"] = d.Get("backup_type")
if v, ok := d.GetOk("bucket"); ok {
request["Bucket"] = v
}
request["PlanName"] = d.Get("oss_backup_plan_name")
if v, ok := d.GetOk("path"); ok {
request["Path"] = v
}
if v, ok := d.GetOk("prefix"); ok {
request["Prefix"] = v
}
if v, ok := d.GetOk("retention"); ok {
request["Retention"] = v
}
request["Schedule"] = d.Get("schedule")
request["SourceType"] = "OSS"
if v, ok := d.GetOk("vault_id"); ok {
request["VaultId"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_hbr_oss_backup_plan", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetId(fmt.Sprint(response["PlanId"]))
return resourceAlicloudHbrOssBackupPlanUpdate(d, meta)
}
func resourceAlicloudHbrOssBackupPlanRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
hbrService := HbrService{client}
object, err := hbrService.DescribeHbrOssBackupPlan(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_hbr_oss_backup_plan hbrService.DescribeHbrOssBackupPlan Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("backup_type", object["BackupType"])
d.Set("bucket", object["Bucket"])
d.Set("oss_backup_plan_name", object["PlanName"])
d.Set("prefix", object["Prefix"])
d.Set("retention", fmt.Sprint(formatInt(object["Retention"])))
d.Set("schedule", object["Schedule"])
d.Set("vault_id", object["VaultId"])
d.Set("disabled", object["Disabled"])
return nil
}
func resourceAlicloudHbrOssBackupPlanUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
hbrService := HbrService{client}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"PlanId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("retention") {
update = true
}
if v, ok := d.GetOk("retention"); ok {
request["Retention"] = v
}
if v, ok := d.GetOk("vault_id"); ok {
request["VaultId"] = v
}
if !d.IsNewResource() && d.HasChange("oss_backup_plan_name") {
update = true
request["PlanName"] = d.Get("oss_backup_plan_name")
}
if !d.IsNewResource() && d.HasChange("prefix") {
update = true
if v, ok := d.GetOk("prefix"); ok {
request["Prefix"] = v
}
}
if !d.IsNewResource() && d.HasChange("schedule") {
update = true
request["Schedule"] = d.Get("schedule")
}
request["SourceType"] = "OSS"
if update {
action := "UpdateBackupPlan"
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetPartial("retention")
d.SetPartial("vault_id")
d.SetPartial("oss_backup_plan_name")
d.SetPartial("prefix")
d.SetPartial("schedule")
}
if d.HasChange("disabled") {
object, err := hbrService.DescribeHbrOssBackupPlan(d.Id())
if err != nil {
return WrapError(err)
}
target := strconv.FormatBool(d.Get("disabled").(bool))
if strconv.FormatBool(object["Disabled"].(bool)) != target {
action := "EnableBackupPlan"
if target == "false" {
action = "EnableBackupPlan"
} else {
action = "DisableBackupPlan"
}
request := map[string]interface{}{
"PlanId": d.Id(),
}
request["VaultId"] = d.Get("vault_id")
request["SourceType"] = "OSS"
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
}
}
d.SetPartial("disabled")
d.Partial(false)
return resourceAlicloudHbrOssBackupPlanRead(d, meta)
}
func resourceAlicloudHbrOssBackupPlanDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteBackupPlan"
var response map[string]interface{}
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"PlanId": d.Id(),
}
request["SourceType"] = "OSS"
if v, ok := d.GetOk("vault_id"); ok {
request["VaultId"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudHbrReplicationVault() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudHbrReplicationVaultCreate,
Read: resourceAlicloudHbrReplicationVaultRead,
Update: resourceAlicloudHbrReplicationVaultUpdate,
Delete: resourceAlicloudHbrReplicationVaultDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(0, 255),
},
"replication_source_region_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"replication_source_vault_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vault_name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(1, 64),
},
"vault_storage_class": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"STANDARD"}, false),
},
},
}
}
func resourceAlicloudHbrReplicationVaultCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateReplicationVault"
request := make(map[string]interface{})
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["VaultRegionId"] = client.RegionId
request["ReplicationSourceRegionId"] = d.Get("replication_source_region_id")
request["ReplicationSourceVaultId"] = d.Get("replication_source_vault_id")
request["VaultName"] = d.Get("vault_name")
if v, ok := d.GetOk("vault_storage_class"); ok {
request["VaultStorageClass"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_hbr_replication_vault", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetId(fmt.Sprint(response["VaultId"]))
return resourceAlicloudHbrReplicationVaultRead(d, meta)
}
func resourceAlicloudHbrReplicationVaultRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
hbrService := HbrService{client}
object, err := hbrService.DescribeHbrReplicationVault(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_hbr_replication_vault hbrService.DescribeHbrReplicationVault Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", object["Description"])
d.Set("replication_source_region_id", object["ReplicationSourceRegionId"])
d.Set("replication_source_vault_id", object["ReplicationSourceVaultId"])
d.Set("status", object["Status"])
d.Set("vault_name", object["VaultName"])
d.Set("vault_region_id", object["VaultRegionId"])
d.Set("vault_storage_class", object["VaultStorageClass"])
return nil
}
func resourceAlicloudHbrReplicationVaultUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"VaultId": d.Id(),
}
if d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
}
if d.HasChange("vault_name") {
update = true
request["VaultName"] = d.Get("vault_name")
}
if update {
action := "UpdateVault"
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
}
return resourceAlicloudHbrReplicationVaultRead(d, meta)
}
func resourceAlicloudHbrReplicationVaultDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteVault"
var response map[string]interface{}
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"VaultId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudHbrRestoreJob() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudHbrRestoreJobCreate,
Read: resourceAlicloudHbrRestoreJobRead,
Update: resourceAlicloudHbrRestoreJobUpdate,
Delete: resourceAlicloudHbrRestoreJobDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(3 * time.Minute),
},
Schema: map[string]*schema.Schema{
"exclude": {
Type: schema.TypeString,
Optional: true,
},
"include": {
Type: schema.TypeString,
Optional: true,
},
"options": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"restore_job_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"restore_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ECS_FILE", "NAS", "OSS"}, false),
},
"snapshot_hash": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"snapshot_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"source_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ECS_FILE", "NAS", "OSS"}, false),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"target_bucket": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"target_client_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"target_container": {
Type: schema.TypeString,
Optional: true,
},
"target_container_cluster_id": {
Type: schema.TypeString,
Optional: true,
},
"target_create_time": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"target_data_source_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"target_file_system_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"target_instance_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"target_path": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"target_prefix": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vault_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudHbrRestoreJobCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateRestoreJob"
request := make(map[string]interface{})
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("exclude"); ok {
request["Exclude"] = v
}
if v, ok := d.GetOk("include"); ok {
request["Include"] = v
}
if v, ok := d.GetOk("options"); ok {
request["Options"] = v
}
if v, ok := d.GetOk("restore_job_id"); ok {
request["RestoreId"] = v
}
request["RestoreType"] = d.Get("restore_type")
if v, ok := d.GetOk("snapshot_hash"); ok {
request["SnapshotHash"] = v
}
if v, ok := d.GetOk("snapshot_id"); ok {
request["SnapshotId"] = v
}
request["SourceType"] = d.Get("source_type")
if v, ok := d.GetOk("target_bucket"); ok {
request["TargetBucket"] = v
}
if v, ok := d.GetOk("target_client_id"); ok {
request["TargetClientId"] = v
}
if v, ok := d.GetOk("target_container"); ok {
request["TargetContainer"] = v
}
if v, ok := d.GetOk("target_container_cluster_id"); ok {
request["TargetContainerClusterId"] = v
}
if v, ok := d.GetOk("target_create_time"); ok {
request["TargetCreateTime"] = ConvertNasFileSystemStringToUnix(v.(string))
}
if v, ok := d.GetOk("target_data_source_id"); ok {
request["TargetDataSourceId"] = v
}
if v, ok := d.GetOk("target_file_system_id"); ok {
request["TargetFileSystemId"] = v
}
if v, ok := d.GetOk("target_instance_id"); ok {
request["TargetInstanceId"] = v
}
if v, ok := d.GetOk("target_path"); ok {
request["TargetPath"] = v
}
if v, ok := d.GetOk("target_prefix"); ok {
request["TargetPrefix"] = v
}
if v, ok := d.GetOk("vault_id"); ok {
request["VaultId"] = v
}
request["ClientToken"] = buildClientToken("CreateRestoreJob")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_hbr_restore_job", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetId(fmt.Sprint(response["RestoreId"], ":", request["RestoreType"]))
hbrService := HbrService{client}
stateConf := BuildStateConf([]string{"PARTIAL_COMPLETE", "CREATED"}, []string{"RUNNING", "COMPLETE", "FAILED"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, hbrService.HbrRestoreJobStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudHbrRestoreJobRead(d, meta)
}
func resourceAlicloudHbrRestoreJobRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
hbrService := HbrService{client}
object, err := hbrService.DescribeHbrRestoreJob(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_hbr_restore_job hbrService.DescribeHbrRestoreJob Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("restore_job_id", parts[0])
d.Set("restore_type", parts[1])
d.Set("options", object["Options"])
d.Set("snapshot_hash", object["SnapshotHash"])
d.Set("snapshot_id", object["SnapshotId"])
d.Set("source_type", object["SourceType"])
d.Set("status", object["Status"])
d.Set("target_bucket", object["TargetBucket"])
d.Set("target_client_id", object["TargetClientId"])
if object["TargetCreateTime"] != nil {
t := int64(formatInt(object["TargetCreateTime"]))
d.Set("target_create_time", ConvertNasFileSystemUnixToString(d.Get("target_create_time").(string), t))
}
d.Set("target_data_source_id", object["TargetDataSourceId"])
d.Set("target_file_system_id", object["TargetFileSystemId"])
d.Set("target_instance_id", object["TargetInstanceId"])
d.Set("target_path", object["TargetPath"])
d.Set("target_prefix", object["TargetPrefix"])
d.Set("vault_id", object["VaultId"])
return nil
}
func resourceAlicloudHbrRestoreJobUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return resourceAlicloudHbrRestoreJobRead(d, meta)
}
func resourceAlicloudHbrRestoreJobDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudHbrRestoreJob. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
package alicloud
import (
"fmt"
"log"
"strconv"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudHbrServerBackupPlan() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudHbrServerBackupPlanCreate,
Read: resourceAlicloudHbrServerBackupPlanRead,
Update: resourceAlicloudHbrServerBackupPlanUpdate,
Delete: resourceAlicloudHbrServerBackupPlanDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"disabled": {
Type: schema.TypeBool,
Computed: true,
Optional: true,
},
"detail": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"app_consistent": {
Type: schema.TypeBool,
Required: true,
},
"snapshot_group": {
Type: schema.TypeBool,
Required: true,
},
"enable_fs_freeze": {
Type: schema.TypeBool,
Optional: true,
},
"pre_script_path": {
Type: schema.TypeString,
Optional: true,
},
"post_script_path": {
Type: schema.TypeString,
Optional: true,
},
"timeout_in_seconds": {
Type: schema.TypeInt,
Optional: true,
Default: 30,
},
"disk_id_list": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"do_copy": {
Type: schema.TypeBool,
Optional: true,
},
"destination_region_id": {
Type: schema.TypeString,
Optional: true,
},
"destination_retention": {
Type: schema.TypeInt,
Optional: true,
Default: -1,
},
},
},
},
"ecs_server_backup_plan_name": {
Type: schema.TypeString,
Required: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"retention": {
Type: schema.TypeInt,
Required: true,
},
"schedule": {
Type: schema.TypeString,
Required: true,
},
},
}
}
func resourceAlicloudHbrServerBackupPlanCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
hbrService := HbrService{client}
var response map[string]interface{}
action := "CreateBackupPlan"
request := make(map[string]interface{})
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
request["BackupType"] = "COMPLETE"
if v, err := hbrService.convertDetailToString(d.Get("detail").(*schema.Set).List()); err == nil {
request["Detail"] = v
} else {
return WrapError(err)
}
request["PlanName"] = d.Get("ecs_server_backup_plan_name")
request["InstanceId"] = d.Get("instance_id")
request["UdmRegionId"] = client.RegionId
request["Retention"] = d.Get("retention")
request["Schedule"] = d.Get("schedule")
request["SourceType"] = "UDM_ECS"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_hbr_server_backup_plan", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetId(fmt.Sprint(response["PlanId"]))
return resourceAlicloudHbrServerBackupPlanUpdate(d, meta)
}
func resourceAlicloudHbrServerBackupPlanRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
hbrService := HbrService{client}
object, err := hbrService.DescribeHbrServerBackupPlan(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_hbr_server_backup_plan hbrService.DescribeHbrServerBackupPlan Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
if v, ok := object["Detail"].(map[string]interface{}); ok {
details := make([]map[string]interface{}, 0)
detail := make(map[string]interface{})
detail["app_consistent"] = v["appConsistent"]
detail["snapshot_group"] = v["snapshotGroup"]
detail["enable_fs_freeze"] = v["enableFsFreeze"]
detail["pre_script_path"] = v["preScriptPath"]
detail["post_script_path"] = v["postScriptPath"]
detail["timeout_in_seconds"] = formatInt(v["timeoutInSeconds"])
detail["do_copy"] = v["doCopy"]
detail["destination_region_id"] = v["destinationRegionId"]
detail["destination_retention"] = v["destinationRetention"]
if v["diskIdList"] != nil {
detail["disk_id_list"] = expandStringList(v["diskIdList"].([]interface{}))
}
details = append(details, detail)
if err := d.Set("detail", details); err != nil {
return WrapError(err)
}
}
d.Set("ecs_server_backup_plan_name", object["PlanName"])
d.Set("instance_id", object["InstanceId"])
d.Set("retention", formatInt(object["Retention"]))
d.Set("schedule", object["Schedule"])
d.Set("disabled", object["Disabled"])
return nil
}
func resourceAlicloudHbrServerBackupPlanUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
hbrService := HbrService{client}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"PlanId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("retention") {
update = true
}
if v, ok := d.GetOk("retention"); ok {
request["Retention"] = v
}
if !d.IsNewResource() && d.HasChange("detail") {
update = true
if v, err := hbrService.convertDetailToString(d.Get("detail").(*schema.Set).List()); err == nil {
request["Detail"] = v
} else {
return WrapError(err)
}
}
if !d.IsNewResource() && d.HasChange("ecs_server_backup_plan_name") {
update = true
request["PlanName"] = d.Get("ecs_server_backup_plan_name")
}
if !d.IsNewResource() && d.HasChange("schedule") {
update = true
request["Schedule"] = d.Get("schedule")
}
request["SourceType"] = "UDM_ECS"
if update {
action := "UpdateBackupPlan"
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetPartial("retention")
d.SetPartial("detail")
d.SetPartial("ecs_server_backup_plan_name")
d.SetPartial("schedule")
}
if d.HasChange("disabled") {
object, err := hbrService.DescribeHbrServerBackupPlan(d.Id())
if err != nil {
return WrapError(err)
}
target := strconv.FormatBool(d.Get("disabled").(bool))
if strconv.FormatBool(object["Disabled"].(bool)) != target {
if target == "false" {
request := map[string]interface{}{
"PlanId": d.Id(),
}
request["SourceType"] = "UDM_ECS"
}
action := "EnableBackupPlan"
if target == "false" {
action = "EnableBackupPlan"
} else {
action = "DisableBackupPlan"
}
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
}
d.SetPartial("disabled")
}
d.Partial(false)
return resourceAlicloudHbrServerBackupPlanRead(d, meta)
}
func resourceAlicloudHbrServerBackupPlanDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteBackupPlan"
var response map[string]interface{}
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"PlanId": d.Id(),
}
request["SourceType"] = "UDM_ECS"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudHbrVault() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudHbrVaultCreate,
Read: resourceAlicloudHbrVaultRead,
Update: resourceAlicloudHbrVaultUpdate,
Delete: resourceAlicloudHbrVaultDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vault_name": {
Type: schema.TypeString,
Required: true,
},
"vault_storage_class": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"STANDARD"}, false),
},
"vault_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"STANDARD"}, false),
},
},
}
}
func resourceAlicloudHbrVaultCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateVault"
request := make(map[string]interface{})
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["VaultRegionId"] = client.RegionId
request["VaultName"] = d.Get("vault_name")
if v, ok := d.GetOk("vault_storage_class"); ok {
request["VaultStorageClass"] = v
}
if v, ok := d.GetOk("vault_type"); ok {
request["VaultType"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_hbr_vault", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetId(fmt.Sprint(response["VaultId"]))
hbrService := HbrService{client}
stateConf := BuildStateConf([]string{}, []string{"CREATED"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, hbrService.HbrVaultStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudHbrVaultRead(d, meta)
}
func resourceAlicloudHbrVaultRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
hbrService := HbrService{client}
object, err := hbrService.DescribeHbrVault(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_hbr_vault hbrService.DescribeHbrVault Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", object["Description"])
d.Set("status", object["Status"])
d.Set("vault_name", object["VaultName"])
d.Set("vault_storage_class", object["VaultStorageClass"])
d.Set("vault_type", object["VaultType"])
return nil
}
func resourceAlicloudHbrVaultUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"VaultId": d.Id(),
}
if d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
}
if d.HasChange("vault_name") {
update = true
request["VaultName"] = d.Get("vault_name")
}
if update {
action := "UpdateVault"
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
}
return resourceAlicloudHbrVaultRead(d, meta)
}
func resourceAlicloudHbrVaultDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteVault"
var response map[string]interface{}
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"VaultId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"CannotDeleteReplicationSourceVault"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
return nil
}
package alicloud
import (
"log"
"strconv"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliCloudImage() *schema.Resource {
return &schema.Resource{
Create: resourceAliCloudImageCreate,
Read: resourceAliCloudImageRead,
Update: resourceAliCloudImageUpdate,
Delete: resourceAliCloudImageDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"architecture": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "x86_64",
ValidateFunc: validation.StringInSlice([]string{
"x86_64",
"i386",
}, false),
},
"instance_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ConflictsWith: []string{"disk_device_mapping", "snapshot_id"},
},
"snapshot_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ConflictsWith: []string{"instance_id", "disk_device_mapping"},
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Attribute 'name' has been deprecated from version 1.69.0. Use `image_name` instead.",
},
"image_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"platform": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "Ubuntu",
ValidateFunc: validation.StringInSlice([]string{
"CentOS",
"Ubuntu",
"SUSE",
"OpenSUSE",
"RedHat",
"Debian",
"CoreOS",
"Aliyun Linux",
"Windows Server 2003",
"Windows Server 2008",
"Windows Server 2012",
"Windows 7",
"Customized Linux",
"Others Linux",
}, false),
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
},
"disk_device_mapping": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Computed: true,
ConflictsWith: []string{"instance_id", "snapshot_id"},
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"disk_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"device": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"size": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Computed: true,
},
"snapshot_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
},
},
},
"force": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"tags": tagsSchema(),
// Not the public attribute and it used to automatically delete dependence snapshots while deleting the image.
// Available in 1.136.0
"delete_auto_snapshot": {
Type: schema.TypeBool,
Optional: true,
},
},
}
}
func resourceAliCloudImageCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
// Make sure the instance status is Running or Stopped
if v, ok := d.GetOk("instance_id"); ok {
instance, err := ecsService.DescribeInstance(v.(string))
if err != nil {
return WrapError(err)
}
status := Status(instance.Status)
if status != Running && status != Stopped {
return WrapError(Error("You must make sure that the status of the specified instance is Running or Stopped. "))
}
}
// The snapshot cannot be a snapshot created before July 15, 2013 (inclusive)
if snapshotId, ok := d.GetOk("snapshot_id"); ok {
snapshot, err := ecsService.DescribeSnapshot(snapshotId.(string))
if err != nil {
return WrapError(err)
}
snapshotCreationTime, err := time.Parse("2006-01-02T15:04:05Z", snapshot.CreationTime)
if err != nil {
return WrapErrorf(err, IdMsg, snapshotId)
}
deadlineTime, _ := time.Parse("2006-01-02T15:04:05Z", "2013-07-16T00:00:00Z")
if deadlineTime.After(snapshotCreationTime) {
return WrapError(Error("the specified snapshot cannot be created on or before July 15, 2013."))
}
}
request := ecs.CreateCreateImageRequest()
request.RegionId = client.RegionId
if instanceId, ok := d.GetOk("instance_id"); ok {
request.InstanceId = instanceId.(string)
}
if value, ok := d.GetOk("disk_device_mapping"); ok {
diskDeviceMappings := value.([]interface{})
if diskDeviceMappings != nil && len(diskDeviceMappings) > 0 {
mappings := make([]ecs.CreateImageDiskDeviceMapping, 0, len(diskDeviceMappings))
for _, diskDeviceMapping := range diskDeviceMappings {
mapping := diskDeviceMapping.(map[string]interface{})
deviceMapping := ecs.CreateImageDiskDeviceMapping{
SnapshotId: mapping["snapshot_id"].(string),
Size: strconv.Itoa(mapping["size"].(int)),
DiskType: mapping["disk_type"].(string),
Device: mapping["device"].(string),
}
mappings = append(mappings, deviceMapping)
}
request.DiskDeviceMapping = &mappings
}
}
tags := d.Get("tags").(map[string]interface{})
if tags != nil && len(tags) > 0 {
imageTags := make([]ecs.CreateImageTag, 0, len(tags))
for k, v := range tags {
imageTag := ecs.CreateImageTag{
Key: k,
Value: v.(string),
}
imageTags = append(imageTags, imageTag)
}
request.Tag = &imageTags
}
if snapshotId, ok := d.GetOk("snapshot_id"); ok {
request.SnapshotId = snapshotId.(string)
}
request.ResourceGroupId = d.Get("resource_group_id").(string)
request.Platform = d.Get("platform").(string)
request.ImageName = d.Get("image_name").(string)
request.Description = d.Get("description").(string)
request.Architecture = d.Get("architecture").(string)
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.CreateImage(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectInstanceStatus"}) {
time.Sleep(time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ecs.CreateImageResponse)
d.SetId(response.ImageId)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"Creating"}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 1*time.Minute, ecsService.ImageStateRefreshFunc(d.Id(), []string{"CreateFailed", "UnAvailable"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAliCloudImageRead(d, meta)
}
func resourceAliCloudImageUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
err := ecsService.updateImage(d)
if err != nil {
return WrapError(err)
}
if d.HasChange("resource_group_id") {
action := "JoinResourceGroup"
request := map[string]interface{}{
"ResourceType": "image",
"ResourceId": d.Id(),
"RegionId": client.RegionId,
"ResourceGroupId": d.Get("resource_group_id"),
}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetPartial("resource_group_id")
}
return resourceAliCloudImageRead(d, meta)
}
func resourceAliCloudImageRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
object, err := ecsService.DescribeImageById(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_image ecsService.DescribeImageById Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("resource_group_id", object.ResourceGroupId)
d.Set("platform", object.Platform)
d.Set("image_name", object.ImageName)
d.Set("name", object.ImageName)
d.Set("description", object.Description)
d.Set("architecture", object.Architecture)
d.Set("disk_device_mapping", FlattenImageDiskDeviceMappings(object.DiskDeviceMappings.DiskDeviceMapping))
tags, err := ecsService.ListTagResources(d.Id(), "image")
if err != nil {
return WrapError(err)
} else {
d.Set("tags", tagsToMap(tags))
}
return WrapError(err)
}
func resourceAliCloudImageDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
return ecsService.deleteImage(d)
}
func FlattenImageDiskDeviceMappings(list []ecs.DiskDeviceMapping) []map[string]interface{} {
result := make([]map[string]interface{}, 0, len(list))
for _, i := range list {
size, _ := strconv.Atoi(i.Size)
l := map[string]interface{}{
"device": i.Device,
"size": size,
"snapshot_id": i.SnapshotId,
"disk_type": i.Type,
}
result = append(result, l)
}
return result
}
package alicloud
import (
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliCloudImageCopy() *schema.Resource {
return &schema.Resource{
Create: resourceAliCloudImageCopyCreate,
Read: resourceAliCloudImageCopyRead,
Update: resourceAliCloudImageCopyUpdate,
Delete: resourceAliCloudImageCopyDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"source_image_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"source_region_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Attribute 'name' has been deprecated from version 1.69.0. Use `image_name` instead.",
},
"image_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"encrypted": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"kms_key_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"force": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"tags": tagsSchema(),
// Not the public attribute and it used to automatically delete dependence snapshots while deleting the image.
// Available in 1.136.0
"delete_auto_snapshot": {
Type: schema.TypeBool,
Optional: true,
},
},
}
}
func resourceAliCloudImageCopyCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
request := ecs.CreateCopyImageRequest()
request.RegionId = d.Get("source_region_id").(string)
request.ImageId = d.Get("source_image_id").(string)
request.DestinationRegionId = client.RegionId
request.DestinationImageName = d.Get("image_name").(string)
request.DestinationDescription = d.Get("description").(string)
request.Encrypted = requests.NewBoolean(d.Get("encrypted").(bool))
request.KMSKeyId = d.Get("kms_key_id").(string)
tags := d.Get("tags").(map[string]interface{})
if tags != nil && len(tags) > 0 {
imageTags := make([]ecs.CopyImageTag, 0, len(tags))
for k, v := range tags {
imageTag := ecs.CopyImageTag{
Key: k,
Value: v.(string),
}
imageTags = append(imageTags, imageTag)
}
request.Tag = &imageTags
}
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.CopyImage(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_image_copy", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ecs.CopyImageResponse)
d.SetId(response.ImageId)
stateConf := BuildStateConf([]string{"Creating", "Waiting"}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 1*time.Minute, ecsService.ImageStateRefreshFunc(d.Id(), []string{"CreateFailed", "UnAvailable"}))
if _, err := stateConf.WaitForState(); err != nil {
// If the copying is timeout, the progress should be cancelled
// Currently the product does not support cancel some specify images
//cancelCopyImageRequest := ecs.CreateCancelCopyImageRequest()
//cancelCopyImageRequest.ImageId = d.Id()
//cancelCopyImageRequest.RegionId = client.RegionId
//if _, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
// return ecsClient.CancelCopyImage(cancelCopyImageRequest)
//}); err != nil {
// return WrapErrorf(err, DefaultErrorMsg, "alicloud_image_copy", cancelCopyImageRequest.GetActionName(), AlibabaCloudSdkGoERROR)
//}
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAliCloudImageCopyRead(d, meta)
}
func resourceAliCloudImageCopyUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
err := ecsService.updateImage(d)
if err != nil {
return WrapError(err)
}
return resourceAliCloudImageRead(d, meta)
}
func resourceAliCloudImageCopyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
object, err := ecsService.DescribeImageById(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", object.ImageName)
d.Set("image_name", object.ImageName)
d.Set("description", object.Description)
tags := object.Tags.Tag
if len(tags) > 0 {
err = d.Set("tags", ecsService.tagsToMap(tags))
}
return WrapError(err)
}
func resourceAliCloudImageCopyDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
return ecsService.deleteImage(d)
}
package alicloud
import (
"fmt"
"time"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliCloudImageExport() *schema.Resource {
return &schema.Resource{
Create: resourceAliCloudImageExportCreate,
Read: resourceAliCloudImageExportRead,
Delete: resourceAliCloudImageExportDelete,
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(20 * time.Minute),
},
Schema: map[string]*schema.Schema{
"image_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"oss_bucket": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"oss_prefix": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
}
}
func resourceAliCloudImageExportCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client: client}
request := ecs.CreateExportImageRequest()
request.RegionId = client.RegionId
request.ImageId = d.Get("image_id").(string)
request.OSSBucket = d.Get("oss_bucket").(string)
request.OSSPrefix = d.Get("oss_prefix").(string)
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ExportImage(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_image_export", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response := raw.(*ecs.ExportImageResponse)
taskId := response.TaskId
d.SetId(request.ImageId)
stateConf := BuildStateConf([]string{"Waiting", "Processing"}, []string{"Finished"}, d.Timeout(schema.TimeoutCreate), 2*time.Minute, ecsService.TaskStateRefreshFunc(taskId, []string{"CreateFailed", "UnAvailable"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAliCloudImageExportRead(d, meta)
}
func resourceAliCloudImageExportRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client: client}
object, err := ecsService.DescribeImageById(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("image_id", object.ImageId)
return WrapError(err)
}
func resourceAliCloudImageExportDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ossService := OssService{client: client}
var requestInfo *oss.Client
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return ossClient.Bucket(d.Get("oss_bucket").(string))
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "oss_bucket", AliyunOssGoSdk)
}
addDebug("oss_bucket", raw, requestInfo, map[string]string{"bucketName": d.Get("oss_bucket").(string)})
bucket, _ := raw.(*oss.Bucket)
objectName := fmt.Sprintf(d.Get("oss_prefix").(string) + "_" + d.Id() + "_system.raw.tar.gz")
err = bucket.DeleteObject(objectName)
if err != nil {
if IsExpectedErrors(err, []string{"No Content", "Not Found"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Get("oss_prefix").(string), "DeleteObject", AliyunOssGoSdk)
}
addDebug("oss_prefix", nil, requestInfo, map[string]string{"oss_prefix": d.Get("oss_prefix").(string)})
return WrapError(ossService.WaitForOssBucketObject(bucket, d.Get("oss_prefix").(string), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"strconv"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAliCloudImageImport() *schema.Resource {
return &schema.Resource{
Create: resourceAliCloudImageImportCreate,
Read: resourceAliCloudImageImportRead,
Update: resourceAliCloudImageImportUpdate,
Delete: resourceAliCloudImageImportDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(20 * time.Minute),
Delete: schema.DefaultTimeout(20 * time.Minute),
},
Schema: map[string]*schema.Schema{
"architecture": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "x86_64",
ValidateFunc: validation.StringInSlice([]string{
"x86_64",
"i386",
}, false),
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"image_name": {
Type: schema.TypeString,
Optional: true,
},
"license_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "Auto",
ValidateFunc: validation.StringInSlice([]string{
"Auto",
"Aliyun",
"BYOL",
}, false),
},
"platform": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "Ubuntu",
ValidateFunc: validation.StringInSlice([]string{
"CentOS",
"Ubuntu",
"SUSE",
"OpenSUSE",
"Debian",
"CoreOS",
"Windows Server 2003",
"Windows Server 2008",
"Windows Server 2012",
"Windows 7",
"Customized Linux",
"Others Linux",
}, false),
},
"os_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "linux",
ValidateFunc: validation.StringInSlice([]string{
"windows",
"linux",
}, false),
},
"disk_device_mapping": {
Type: schema.TypeList,
ForceNew: true,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"device": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"disk_image_size": {
Type: schema.TypeInt,
Optional: true,
Default: 5,
ForceNew: true,
},
"format": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{
"RAW",
"VHD",
"qcow2",
}, false),
},
"oss_bucket": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"oss_object": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
},
},
},
}
}
func resourceAliCloudImageImportCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client: client}
request := ecs.CreateImportImageRequest()
request.RegionId = client.RegionId
request.Architecture = d.Get("architecture").(string)
request.Description = d.Get("description").(string)
request.ImageName = d.Get("image_name").(string)
request.LicenseType = d.Get("license_type").(string)
request.OSType = d.Get("os_type").(string)
request.Platform = d.Get("platform").(string)
diskDeviceMappings := d.Get("disk_device_mapping").([]interface{})
if diskDeviceMappings != nil && len(diskDeviceMappings) > 0 {
mappings := make([]ecs.ImportImageDiskDeviceMapping, 0, len(diskDeviceMappings))
for _, diskDeviceMapping := range diskDeviceMappings {
mapping := diskDeviceMapping.(map[string]interface{})
size := strconv.Itoa(mapping["disk_image_size"].(int))
diskmapping := ecs.ImportImageDiskDeviceMapping{
Device: mapping["device"].(string),
DiskImageSize: size,
Format: mapping["format"].(string),
OSSBucket: mapping["oss_bucket"].(string),
OSSObject: mapping["oss_object"].(string),
}
mappings = append(mappings, diskmapping)
}
request.DiskDeviceMapping = &mappings
}
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ImportImage(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_import_image", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
resp, _ := raw.(*ecs.ImportImageResponse)
d.SetId(resp.ImageId)
stateConf := BuildStateConf([]string{"Waiting"}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 1*time.Minute, ecsService.ImageStateRefreshFunc(d.Id(), []string{"CreateFailed", "UnAvailable"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAliCloudImageImportRead(d, meta)
}
func resourceAliCloudImageImportRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client: client}
object, err := ecsService.DescribeImageById(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("image_name", object.ImageName)
d.Set("description", object.Description)
d.Set("architecture", object.Architecture)
d.Set("os_type", object.OSType)
d.Set("platform", object.Platform)
d.Set("disk_device_mapping", FlattenImageImportDiskDeviceMappings(object.DiskDeviceMappings.DiskDeviceMapping))
return nil
}
func resourceAliCloudImageImportUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
err := ecsService.updateImage(d)
if err != nil {
return WrapError(err)
}
return resourceAliCloudImageRead(d, meta)
}
func resourceAliCloudImageImportDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
return ecsService.deleteImage(d)
}
func FlattenImageImportDiskDeviceMappings(list []ecs.DiskDeviceMapping) []map[string]interface{} {
result := make([]map[string]interface{}, 0, len(list))
for _, i := range list {
size, _ := strconv.Atoi(i.Size)
l := map[string]interface{}{
"device": i.Device,
"disk_image_size": size,
"format": i.Format,
"oss_bucket": i.ImportOSSBucket,
"oss_object": i.ImportOSSObject,
}
result = append(result, l)
}
return result
}
package alicloud
import (
"log"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliCloudImageSharePermission() *schema.Resource {
return &schema.Resource{
Create: resourceAliCloudImageSharePermissionCreate,
Read: resourceAliCloudImageSharePermissionRead,
Delete: resourceAliCloudImageSharePermissionDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"image_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"account_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAliCloudImageSharePermissionCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
imageId := d.Get("image_id").(string)
accountId := d.Get("account_id").(string)
request := ecs.CreateModifyImageSharePermissionRequest()
request.RegionId = client.RegionId
request.ImageId = imageId
accountSli := []string{accountId}
request.AddAccount = &accountSli
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ModifyImageSharePermission(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_image_share_permission", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetId(imageId + ":" + accountId)
return resourceAliCloudImageSharePermissionRead(d, meta)
}
func resourceAliCloudImageSharePermissionRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client: client}
object, err := ecsService.DescribeImageShareByImageId(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_image_share_permission ecsService.DescribeImageShareByImageId Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
d.Set("image_id", object.ImageId)
d.Set("account_id", parts[1])
return WrapError(err)
}
func resourceAliCloudImageSharePermissionDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ecs.CreateModifyImageSharePermissionRequest()
request.RegionId = client.RegionId
parts, err := ParseResourceId(d.Id(), 2)
request.ImageId = parts[0]
accountSli := []string{parts[1]}
request.RemoveAccount = &accountSli
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ModifyImageSharePermission(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_image_share_permission", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudImmProject() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudImmProjectCreate,
Read: resourceAlicloudImmProjectRead,
Update: resourceAlicloudImmProjectUpdate,
Delete: resourceAlicloudImmProjectDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"project": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-zA-z][a-zA-Z0-9\\-]{1,49}$`), "The length of the project name is limited to 1-50 characters, can only contain English letters, numbers and dashes (-), must start with an English letter, and cannot be ALL (reserved words)"),
},
"service_role": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
},
}
}
func resourceAlicloudImmProjectCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "PutProject"
request := make(map[string]interface{})
conn, err := client.NewImmClient()
if err != nil {
return WrapError(err)
}
request["Project"] = d.Get("project")
if v, ok := d.GetOk("service_role"); ok {
request["ServiceRole"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-06"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_imm_project", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["Project"]))
return resourceAlicloudImmProjectUpdate(d, meta)
}
func resourceAlicloudImmProjectRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
immService := ImmService{client}
object, err := immService.DescribeImmProject(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_imm_project immService.DescribeImmProject Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("project", d.Id())
if v, ok := object["CU"]; ok && fmt.Sprint(v) != "0" {
d.Set("compute_unit", formatInt(v))
}
d.Set("service_role", object["ServiceRole"])
return nil
}
func resourceAlicloudImmProjectUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"Project": d.Id(),
}
if !d.IsNewResource() && d.HasChange("service_role") {
update = true
if v, ok := d.GetOk("service_role"); ok {
request["NewServiceRole"] = v
}
}
if update {
action := "UpdateProject"
conn, err := client.NewImmClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-06"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudImmProjectRead(d, meta)
}
func resourceAlicloudImmProjectDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteProject"
var response map[string]interface{}
conn, err := client.NewImmClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"Project": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-06"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudImpAppTemplate() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudImpAppTemplateCreate,
Read: resourceAlicloudImpAppTemplateRead,
Update: resourceAlicloudImpAppTemplateUpdate,
Delete: resourceAlicloudImpAppTemplateDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"app_template_name": {
Type: schema.TypeString,
Required: true,
},
"component_list": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"component.live", "component.liveRecord", "component.liveBeauty", "component.rtc", "component.rtcRecord", "component.im", "component.whiteboard", "component.liveSecurity", "component.chatSecurity"}, false),
},
ForceNew: true,
},
"config_list": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"value": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
},
},
},
"integration_mode": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"paasSDK", "standardRoom"}, false),
},
"scene": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"business", "classroom"}, false),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudImpAppTemplateCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateAppTemplate"
request := make(map[string]interface{})
conn, err := client.NewImpClient()
if err != nil {
return WrapError(err)
}
request["AppTemplateName"] = d.Get("app_template_name")
request["ComponentList"] = convertListToJsonString(d.Get("component_list").([]interface{}))
if v, ok := d.GetOk("integration_mode"); ok {
request["IntegrationMode"] = v
}
if v, ok := d.GetOk("scene"); ok {
request["Scene"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-06-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_imp_app_template", action, AlibabaCloudSdkGoERROR)
}
responseResult := response["Result"].(map[string]interface{})
d.SetId(fmt.Sprint(responseResult["AppTemplateId"]))
return resourceAlicloudImpAppTemplateRead(d, meta)
}
func resourceAlicloudImpAppTemplateRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
impService := ImpService{client}
object, err := impService.DescribeImpAppTemplate(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_imp_app_template impService.DescribeImpAppTemplate Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("app_template_name", object["AppTemplateName"])
if componentList, ok := object["ComponentList"]; ok && componentList != nil {
d.Set("component_list", componentList)
}
if configList, ok := object["ConfigList"]; ok && configList != nil {
configListMaps := make([]map[string]interface{}, 0)
for _, configListItem := range configList.([]interface{}) {
if configListItemMap, ok := configListItem.(map[string]interface{}); ok {
configListMap := make(map[string]interface{}, 0)
configListMap["key"] = configListItemMap["Key"]
configListMap["value"] = configListItemMap["Value"]
configListMaps = append(configListMaps, configListMap)
}
}
d.Set("config_list", configListMaps)
}
d.Set("integration_mode", object["IntegrationMode"])
d.Set("scene", object["Scene"])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudImpAppTemplateUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"AppTemplateId": d.Id(),
}
if d.HasChange("app_template_name") {
update = true
request["AppTemplateName"] = d.Get("app_template_name")
}
if update {
action := "UpdateAppTemplate"
conn, err := client.NewImpClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-06-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("app_template_name")
}
update = false
updateAppTemplateConfigReq := map[string]interface{}{
"AppTemplateId": d.Id(),
}
if d.HasChanges("config_list") {
update = true
if v, ok := d.GetOk("config_list"); ok {
configListMaps := make([]map[string]interface{}, 0)
for _, configList := range v.(*schema.Set).List() {
configListArg := configList.(map[string]interface{})
configListMap := map[string]interface{}{
"Key": configListArg["key"],
"Value": configListArg["value"],
}
configListMaps = append(configListMaps, configListMap)
}
if v, err := convertListMapToJsonString(configListMaps); err != nil {
return WrapError(err)
} else {
updateAppTemplateConfigReq["ConfigList"] = v
}
}
}
if update {
action := "UpdateAppTemplateConfig"
conn, err := client.NewImpClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-06-30"), StringPointer("AK"), nil, updateAppTemplateConfigReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, updateAppTemplateConfigReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("key")
d.SetPartial("value")
}
d.Partial(false)
return resourceAlicloudImpAppTemplateRead(d, meta)
}
func resourceAlicloudImpAppTemplateDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteAppTemplate"
var response map[string]interface{}
conn, err := client.NewImpClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AppTemplateId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-06-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidAppTemplateId.App.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"strconv"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/denverdino/aliyungo/common"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"encoding/base64"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliyunInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunInstanceCreate,
Read: resourceAliyunInstanceRead,
Update: resourceAliyunInstanceUpdate,
Delete: resourceAliyunInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(20 * time.Minute),
},
Schema: map[string]*schema.Schema{
"availability_zone": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"image_id": {
Type: schema.TypeString,
Required: true,
},
"instance_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^ecs\..*`), "prefix must be 'ecs.'"),
},
"credit_specification": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{
string(CreditSpecificationStandard),
string(CreditSpecificationUnlimited),
}, false),
},
"security_groups": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Required: true,
},
"allocate_public_ip": {
Type: schema.TypeBool,
Optional: true,
Deprecated: "Field 'allocate_public_ip' has been deprecated from provider version 1.6.1. Setting 'internet_max_bandwidth_out' larger than 0 will allocate public ip for instance.",
},
"instance_name": {
Type: schema.TypeString,
Optional: true,
Default: "ECS-Instance",
ValidateFunc: validation.StringLenBetween(2, 128),
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"internet_charge_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"PayByBandwidth", "PayByTraffic"}, false),
Default: PayByTraffic,
DiffSuppressFunc: ecsInternetDiffSuppressFunc,
},
"internet_max_bandwidth_in": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
DiffSuppressFunc: ecsInternetDiffSuppressFunc,
Deprecated: "The attribute is invalid and no any affect for the instance. So it has been deprecated from version v1.121.2.",
},
"internet_max_bandwidth_out": {
Type: schema.TypeInt,
Optional: true,
Default: 0,
},
"host_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"kms_encrypted_password": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: kmsDiffSuppressFunc,
},
"kms_encryption_context": {
Type: schema.TypeMap,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("kms_encrypted_password") == ""
},
Elem: schema.TypeString,
},
"io_optimized": {
Type: schema.TypeString,
Optional: true,
Deprecated: "Attribute io_optimized has been deprecated on instance resource. All the launched alicloud instances will be IO optimized. Suggest to remove it from your template.",
},
"is_outdated": {
Type: schema.TypeBool,
Optional: true,
},
"system_disk_category": {
Type: schema.TypeString,
Default: DiskCloudEfficiency,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"all", "cloud", "ephemeral_ssd", "cloud_essd", "cloud_efficiency", "cloud_ssd", "local_disk"}, false),
},
"system_disk_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 128),
},
"system_disk_description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"system_disk_size": {
Type: schema.TypeInt,
Optional: true,
Default: 40,
},
"system_disk_performance_level": {
Type: schema.TypeString,
Optional: true,
Computed: true,
DiffSuppressFunc: ecsSystemDiskPerformanceLevelSuppressFunc,
ValidateFunc: validation.StringInSlice([]string{"PL0", "PL1", "PL2", "PL3"}, false),
},
"system_disk_auto_snapshot_policy_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"data_disks": {
Type: schema.TypeList,
Optional: true,
MinItems: 1,
MaxItems: 16,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(2, 128),
},
"size": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
},
"category": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"all", "cloud", "ephemeral_ssd", "cloud_essd", "cloud_efficiency", "cloud_ssd", "local_disk"}, false),
Default: DiskCloudEfficiency,
ForceNew: true,
},
"encrypted": {
Type: schema.TypeBool,
Optional: true,
Default: false,
ForceNew: true,
},
"kms_key_id": {
Type: schema.TypeString,
Optional: true,
},
"snapshot_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"auto_snapshot_policy_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"delete_with_instance": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"performance_level": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"PL0", "PL1", "PL2", "PL3"}, false),
},
},
},
},
//subnet_id and vswitch_id both exists, cause compatible old version, and aws habit.
"subnet_id": {
Type: schema.TypeString,
Optional: true,
Computed: true, //add this schema cause subnet_id not used enter parameter, will different, so will be ForceNew
ConflictsWith: []string{"vswitch_id"},
},
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
},
"private_ip": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"instance_charge_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{string(common.PrePaid), string(common.PostPaid)}, false),
Default: PostPaid,
},
"period": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.Any(
validation.IntBetween(1, 9),
validation.IntInSlice([]int{12, 24, 36, 48, 60})),
DiffSuppressFunc: PostPaidDiffSuppressFunc,
},
"period_unit": {
Type: schema.TypeString,
Optional: true,
Default: Month,
ValidateFunc: validation.StringInSlice([]string{"Week", "Month"}, false),
DiffSuppressFunc: PostPaidDiffSuppressFunc,
},
"renewal_status": {
Type: schema.TypeString,
Optional: true,
Default: RenewNormal,
ValidateFunc: validation.StringInSlice([]string{
string(RenewAutoRenewal),
string(RenewNormal),
string(RenewNotRenewal)}, false),
DiffSuppressFunc: PostPaidDiffSuppressFunc,
},
"auto_renew_period": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 6, 12}),
DiffSuppressFunc: ecsNotAutoRenewDiffSuppressFunc,
},
"include_data_disks": {
Type: schema.TypeBool,
Optional: true,
Default: true,
DiffSuppressFunc: PostPaidDiffSuppressFunc,
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"public_ip": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Running", "Stopped"}, false),
Default: "Running",
},
"user_data": {
Type: schema.TypeString,
Optional: true,
},
"role_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
DiffSuppressFunc: vpcTypeResourceDiffSuppressFunc,
},
"key_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"spot_strategy": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: NoSpot,
ValidateFunc: validation.StringInSlice([]string{"NoSpot", "SpotAsPriceGo", "SpotWithPriceLimit"}, false),
DiffSuppressFunc: ecsSpotStrategyDiffSuppressFunc,
},
"spot_price_limit": {
Type: schema.TypeFloat,
Optional: true,
ForceNew: true,
DiffSuppressFunc: ecsSpotPriceLimitDiffSuppressFunc,
},
"deletion_protection": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"force_delete": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: descriptions["A behavior mark used to delete 'PrePaid' ECS instance forcibly."],
DiffSuppressFunc: PostPaidDiffSuppressFunc,
},
"security_enhancement_strategy": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
string(ActiveSecurityEnhancementStrategy),
string(DeactiveSecurityEnhancementStrategy),
}, false),
},
"tags": tagsSchemaWithIgnore(),
"volume_tags": tagsSchemaComputed(),
"auto_release_time": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
diff := d.Get("instance_charge_type").(string) == "PrePaid"
if diff {
return diff
}
if old != "" && new != "" && strings.HasPrefix(new, strings.Trim(old, "Z")) {
diff = true
}
return diff
},
},
"hpc_cluster_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"secondary_private_ips": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Computed: true,
ConflictsWith: []string{"secondary_private_ip_address_count"},
},
"secondary_private_ip_address_count": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ConflictsWith: []string{"secondary_private_ips"},
},
"deployment_set_id": {
Type: schema.TypeString,
Optional: true,
},
"deployment_set_group_no": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAliyunInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
// Ensure instance_type is valid
//zoneId, validZones, requestId, err := ecsService.DescribeAvailableResources(d, meta, InstanceTypeResource)
//if err != nil {
// return WrapError(err)
//}
//if err := ecsService.InstanceTypeValidation(d.Get("instance_type").(string), zoneId, validZones); err != nil {
// return WrapError(Error("%s. RequestId: %s", err, requestId))
//}
request, err := buildAliyunInstanceArgs(d, meta)
if err != nil {
return WrapError(err)
}
request.IoOptimized = "optimized"
if d.Get("is_outdated").(bool) == true {
request.IoOptimized = "none"
}
wait := incrementalWait(1*time.Second, 1*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.RunInstances(request)
})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ecs.RunInstancesResponse)
d.SetId(response.InstanceIdSets.InstanceIdSet[0])
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_instance", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"Pending", "Starting", "Stopped"}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 10*time.Second, ecsService.InstanceStateRefreshFunc(d.Id(), []string{"Stopping"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAliyunInstanceUpdate(d, meta)
}
func resourceAliyunInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
instance, err := ecsService.DescribeInstance(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_instance ecsService.DescribeInstance Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
var disk ecs.Disk
err = resource.Retry(2*time.Minute, func() *resource.RetryError {
disk, err = ecsService.DescribeInstanceSystemDisk(d.Id(), instance.ResourceGroupId)
if err != nil {
if NotFoundError(err) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapError(err)
}
d.Set("system_disk_category", disk.Category)
d.Set("system_disk_size", disk.Size)
d.Set("system_disk_auto_snapshot_policy_id", disk.AutoSnapshotPolicyId)
d.Set("volume_tags", ecsService.tagsToMap(disk.Tags.Tag))
d.Set("system_disk_performance_level", disk.PerformanceLevel)
d.Set("instance_name", instance.InstanceName)
d.Set("resource_group_id", instance.ResourceGroupId)
d.Set("description", instance.Description)
d.Set("status", instance.Status)
d.Set("availability_zone", instance.ZoneId)
d.Set("host_name", instance.HostName)
d.Set("image_id", instance.ImageId)
d.Set("instance_type", instance.InstanceType)
d.Set("password", d.Get("password").(string))
d.Set("internet_max_bandwidth_out", instance.InternetMaxBandwidthOut)
d.Set("internet_max_bandwidth_in", instance.InternetMaxBandwidthIn)
d.Set("instance_charge_type", instance.InstanceChargeType)
d.Set("key_name", instance.KeyPairName)
d.Set("spot_strategy", instance.SpotStrategy)
d.Set("spot_price_limit", instance.SpotPriceLimit)
d.Set("internet_charge_type", instance.InternetChargeType)
d.Set("deletion_protection", instance.DeletionProtection)
d.Set("credit_specification", instance.CreditSpecification)
d.Set("auto_release_time", instance.AutoReleaseTime)
d.Set("tags", ecsService.tagsToMap(instance.Tags.Tag))
d.Set("hpc_cluster_id", instance.HpcClusterId)
d.Set("deployment_set_id", instance.DeploymentSetId)
d.Set("deployment_set_group_no", instance.DeploymentSetGroupNo)
if len(instance.PublicIpAddress.IpAddress) > 0 {
d.Set("public_ip", instance.PublicIpAddress.IpAddress[0])
} else {
d.Set("public_ip", "")
}
d.Set("subnet_id", instance.VpcAttributes.VSwitchId)
d.Set("vswitch_id", instance.VpcAttributes.VSwitchId)
if len(instance.VpcAttributes.PrivateIpAddress.IpAddress) > 0 {
d.Set("private_ip", instance.VpcAttributes.PrivateIpAddress.IpAddress[0])
} else {
d.Set("private_ip", strings.Join(instance.InnerIpAddress.IpAddress, ","))
}
sgs := make([]string, 0, len(instance.SecurityGroupIds.SecurityGroupId))
for _, sg := range instance.SecurityGroupIds.SecurityGroupId {
sgs = append(sgs, sg)
}
if err := d.Set("security_groups", sgs); err != nil {
return WrapError(err)
}
if !d.IsNewResource() || d.HasChange("user_data") {
dataRequest := ecs.CreateDescribeUserDataRequest()
dataRequest.RegionId = client.RegionId
dataRequest.InstanceId = d.Id()
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeUserData(dataRequest)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), dataRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(dataRequest.GetActionName(), raw, dataRequest.RpcRequest, dataRequest)
response, _ := raw.(*ecs.DescribeUserDataResponse)
d.Set("user_data", userDataHashSum(response.UserData))
}
if len(instance.VpcAttributes.VSwitchId) > 0 && (!d.IsNewResource() || d.HasChange("role_name")) {
request := ecs.CreateDescribeInstanceRamRoleRequest()
request.RegionId = client.RegionId
request.InstanceIds = convertListToJsonString([]interface{}{d.Id()})
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeInstanceRamRole(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ecs.DescribeInstanceRamRoleResponse)
if len(response.InstanceRamRoleSets.InstanceRamRoleSet) >= 1 {
d.Set("role_name", response.InstanceRamRoleSets.InstanceRamRoleSet[0].RamRoleName)
}
}
if instance.InstanceChargeType == string(PrePaid) {
request := ecs.CreateDescribeInstanceAutoRenewAttributeRequest()
request.RegionId = client.RegionId
request.InstanceId = d.Id()
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeInstanceAutoRenewAttribute(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ecs.DescribeInstanceAutoRenewAttributeResponse)
periodUnit := d.Get("period_unit").(string)
if periodUnit == "" {
periodUnit = "Month"
}
if len(response.InstanceRenewAttributes.InstanceRenewAttribute) > 0 {
renew := response.InstanceRenewAttributes.InstanceRenewAttribute[0]
d.Set("renewal_status", renew.RenewalStatus)
d.Set("auto_renew_period", renew.Duration)
if renew.RenewalStatus == "AutoRenewal" {
periodUnit = renew.PeriodUnit
}
if periodUnit == "Year" {
periodUnit = "Month"
d.Set("auto_renew_period", renew.Duration*12)
}
}
//period, err := computePeriodByUnit(instance.CreationTime, instance.ExpiredTime, d.Get("period").(int), periodUnit)
//if err != nil {
// return WrapError(err)
//}
//thisPeriod := d.Get("period").(int)
//if thisPeriod != 0 && thisPeriod != period {
// d.Set("period", thisPeriod)
//} else {
// d.Set("period", period)
//}
d.Set("period_unit", periodUnit)
}
networkInterfaceId := ""
for _, obj := range instance.NetworkInterfaces.NetworkInterface {
if obj.Type == "Primary" {
networkInterfaceId = obj.NetworkInterfaceId
break
}
}
if len(networkInterfaceId) != 0 {
object, err := ecsService.DescribeEcsNetworkInterface(networkInterfaceId)
if err != nil {
return WrapError(err)
}
secondaryPrivateIpsSli := make([]interface{}, 0, len(object["PrivateIpSets"].(map[string]interface{})["PrivateIpSet"].([]interface{})))
for _, v := range object["PrivateIpSets"].(map[string]interface{})["PrivateIpSet"].([]interface{}) {
if !v.(map[string]interface{})["Primary"].(bool) {
secondaryPrivateIpsSli = append(secondaryPrivateIpsSli, v.(map[string]interface{})["PrivateIpAddress"])
}
}
d.Set("secondary_private_ips", secondaryPrivateIpsSli)
d.Set("secondary_private_ip_address_count", len(secondaryPrivateIpsSli))
}
return nil
}
func resourceAliyunInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
d.Partial(true)
if !d.IsNewResource() {
if err := setTags(client, TagResourceInstance, d); err != nil {
return WrapError(err)
} else {
d.SetPartial("tags")
}
}
if !d.IsNewResource() && d.HasChange("resource_group_id") {
action := "JoinResourceGroup"
request := map[string]interface{}{
"ResourceType": "instance",
"ResourceId": d.Id(),
"RegionId": client.RegionId,
"ResourceGroupId": d.Get("resource_group_id"),
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetPartial("resource_group_id")
}
if err := setVolumeTags(client, TagResourceDisk, d); err != nil {
return WrapError(err)
} else {
d.SetPartial("volume_tags")
}
if d.HasChange("security_groups") {
if !d.IsNewResource() || d.Get("vswitch_id").(string) == "" {
o, n := d.GetChange("security_groups")
os := o.(*schema.Set)
ns := n.(*schema.Set)
rl := expandStringList(os.Difference(ns).List())
al := expandStringList(ns.Difference(os).List())
if len(al) > 0 {
err := ecsService.JoinSecurityGroups(d.Id(), al)
if err != nil {
return WrapError(err)
}
}
if len(rl) > 0 {
err := ecsService.LeaveSecurityGroups(d.Id(), rl)
if err != nil {
return WrapError(err)
}
}
d.SetPartial("security_groups")
}
}
if !d.IsNewResource() && d.HasChange("system_disk_size") {
diskReq := ecs.CreateDescribeDisksRequest()
diskReq.InstanceId = d.Id()
diskReq.DiskType = "system"
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeDisks(diskReq)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), diskReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(diskReq.GetActionName(), raw, diskReq.RpcRequest, diskReq)
resp := raw.(*ecs.DescribeDisksResponse)
instance, errDesc := ecsService.DescribeInstance(d.Id())
if errDesc != nil {
return WrapError(errDesc)
}
request := ecs.CreateResizeDiskRequest()
request.NewSize = requests.NewInteger(d.Get("system_disk_size").(int))
if instance.Status == string(Stopped) {
request.Type = "offline"
} else {
request.Type = "online"
}
request.DiskId = resp.Disks.Disk[0].DiskId
_, err = client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ResizeDisk(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("system_disk_size")
}
run := false
imageUpdate, err := modifyInstanceImage(d, meta, run)
if err != nil {
return WrapError(err)
}
vpcUpdate, err := modifyVpcAttribute(d, meta, run)
if err != nil {
return WrapError(err)
}
passwordUpdate, err := modifyInstanceAttribute(d, meta)
if err != nil {
return WrapError(err)
}
if !d.IsNewResource() && d.HasChange("auto_release_time") {
request := ecs.CreateModifyInstanceAutoReleaseTimeRequest()
request.InstanceId = d.Id()
request.RegionId = client.RegionId
request.AutoReleaseTime = d.Get("auto_release_time").(string)
_, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ModifyInstanceAutoReleaseTime(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("auto_release_time")
}
typeUpdate, err := modifyInstanceType(d, meta, run)
if err != nil {
return WrapError(err)
}
target := d.Get("status").(string)
statusUpdate := d.HasChange("status")
if d.IsNewResource() && target == string(Running) {
statusUpdate = false
}
if imageUpdate || vpcUpdate || passwordUpdate || typeUpdate || statusUpdate {
run = true
instance, errDesc := ecsService.DescribeInstance(d.Id())
if errDesc != nil {
return WrapError(errDesc)
}
if (statusUpdate && target == string(Stopped)) || instance.Status == string(Running) {
stopRequest := ecs.CreateStopInstanceRequest()
stopRequest.RegionId = client.RegionId
stopRequest.InstanceId = d.Id()
stopRequest.ForceStop = requests.NewBoolean(false)
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.StopInstance(stopRequest)
})
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectInstanceStatus"}) {
time.Sleep(time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(stopRequest.GetActionName(), raw)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), stopRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"Pending", "Running", "Stopping"}, []string{"Stopped"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, ecsService.InstanceStateRefreshFunc(d.Id(), []string{}))
if _, err = stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if _, err := modifyInstanceImage(d, meta, run); err != nil {
return WrapError(err)
}
if _, err := modifyVpcAttribute(d, meta, run); err != nil {
return WrapError(err)
}
if _, err := modifyInstanceType(d, meta, run); err != nil {
return WrapError(err)
}
if target == string(Running) {
startRequest := ecs.CreateStartInstanceRequest()
startRequest.InstanceId = d.Id()
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.StartInstance(startRequest)
})
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectInstanceStatus"}) {
time.Sleep(time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(startRequest.GetActionName(), raw)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), startRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
// Start instance sometimes costs more than 8 minutes when os type is centos.
stateConf := &resource.StateChangeConf{
Pending: []string{"Pending", "Starting", "Stopped"},
Target: []string{"Running"},
Refresh: ecsService.InstanceStateRefreshFunc(d.Id(), []string{}),
Timeout: d.Timeout(schema.TimeoutUpdate),
Delay: 5 * time.Second,
MinTimeout: 3 * time.Second,
}
if _, err = stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if d.HasChange("status") {
d.SetPartial("status")
}
}
if err := modifyInstanceNetworkSpec(d, meta); err != nil {
return WrapError(err)
}
if d.HasChange("force_delete") {
d.SetPartial("force_delete")
}
if err := modifyInstanceChargeType(d, meta, false); err != nil {
return WrapError(err)
}
// Only PrePaid instance can support modifying renewal attribute
if d.Get("instance_charge_type").(string) == string(PrePaid) &&
(d.HasChange("renewal_status") || d.HasChange("auto_renew_period")) {
status := d.Get("renewal_status").(string)
request := ecs.CreateModifyInstanceAutoRenewAttributeRequest()
request.InstanceId = d.Id()
request.RenewalStatus = status
if status == string(RenewAutoRenewal) {
request.PeriodUnit = d.Get("period_unit").(string)
request.Duration = requests.NewInteger(d.Get("auto_renew_period").(int))
}
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ModifyInstanceAutoRenewAttribute(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("renewal_status")
d.SetPartial("auto_renew_period")
}
if d.HasChange("secondary_private_ips") {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
var response map[string]interface{}
instance, err := ecsService.DescribeInstance(d.Id())
if err != nil {
return WrapError(err)
}
networkInterfaceId := ""
for _, obj := range instance.NetworkInterfaces.NetworkInterface {
if obj.Type == "Primary" {
networkInterfaceId = obj.NetworkInterfaceId
break
}
}
oraw, nraw := d.GetChange("secondary_private_ips")
remove := oraw.(*schema.Set).Difference(nraw.(*schema.Set)).List()
create := nraw.(*schema.Set).Difference(oraw.(*schema.Set)).List()
if len(remove) > 0 {
action := "UnassignPrivateIpAddresses"
request := map[string]interface{}{
"RegionId": client.RegionId,
"NetworkInterfaceId": networkInterfaceId,
"ClientToken": buildClientToken(action),
}
for index, val := range remove {
request[fmt.Sprintf("PrivateIpAddress.%d", index+1)] = val
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) || IsExpectedErrors(err, []string{"OperationConflict"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetPartial("secondary_private_ips")
}
if len(create) > 0 {
action := "AssignPrivateIpAddresses"
request := map[string]interface{}{
"RegionId": client.RegionId,
"NetworkInterfaceId": networkInterfaceId,
"ClientToken": buildClientToken(action),
}
for index, val := range create {
request[fmt.Sprintf("PrivateIpAddress.%d", index+1)] = val
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) || IsExpectedErrors(err, []string{"OperationConflict"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("secondary_private_ips")
}
}
if d.HasChange("secondary_private_ip_address_count") {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
var response map[string]interface{}
instance, err := ecsService.DescribeInstance(d.Id())
if err != nil {
return WrapError(err)
}
// query for the Primary NetworkInterfaceId
networkInterfaceId := ""
for _, obj := range instance.NetworkInterfaces.NetworkInterface {
if obj.Type == "Primary" {
networkInterfaceId = obj.NetworkInterfaceId
break
}
}
privateIpList := expandStringList(d.Get("secondary_private_ips").(*schema.Set).List())
oldIpsCount, newIpsCount := d.GetChange("secondary_private_ip_address_count")
if oldIpsCount != nil && newIpsCount != nil && newIpsCount != len(privateIpList) {
diff := newIpsCount.(int) - oldIpsCount.(int)
if diff > 0 {
action := "AssignPrivateIpAddresses"
request := map[string]interface{}{
"RegionId": client.RegionId,
"NetworkInterfaceId": networkInterfaceId,
"ClientToken": buildClientToken(action),
"SecondaryPrivateIpAddressCount": diff,
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) || IsExpectedErrors(err, []string{"OperationConflict"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("secondary_private_ip_address_count")
}
if diff < 0 {
diff *= -1
action := "UnassignPrivateIpAddresses"
request := map[string]interface{}{
"RegionId": client.RegionId,
"NetworkInterfaceId": networkInterfaceId,
"ClientToken": buildClientToken(action),
}
for index, val := range privateIpList[:diff] {
request[fmt.Sprintf("PrivateIpAddress.%d", index+1)] = val
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) || IsExpectedErrors(err, []string{"OperationConflict"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetPartial("secondary_private_ip_address_count")
}
}
}
if !d.IsNewResource() && d.HasChange("deployment_set_id") {
action := "ModifyInstanceDeployment"
var response map[string]interface{}
request := map[string]interface{}{
"RegionId": client.RegionId,
"InstanceId": d.Id(),
"ClientToken": buildClientToken(action),
}
if v, ok := d.GetOk("deployment_set_id"); ok {
request["DeploymentSetId"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("deployment_set_id")
}
d.Partial(false)
return resourceAliyunInstanceRead(d, meta)
}
func resourceAliyunInstanceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
if d.Get("instance_charge_type").(string) == string(PrePaid) {
force := d.Get("force_delete").(bool)
if !force {
return WrapError(Error("Please convert 'PrePaid' instance to 'PostPaid' or set 'force_delete' as true before deleting 'PrePaid' instance."))
} else if err := modifyInstanceChargeType(d, meta, force); err != nil {
return WrapError(err)
}
}
stopRequest := ecs.CreateStopInstanceRequest()
stopRequest.InstanceId = d.Id()
stopRequest.ForceStop = requests.NewBoolean(true)
deleteRequest := ecs.CreateDeleteInstanceRequest()
deleteRequest.InstanceId = d.Id()
deleteRequest.Force = requests.NewBoolean(true)
wait := incrementalWait(1*time.Second, 1*time.Second)
err := resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DeleteInstance(deleteRequest)
})
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectInstanceStatus", "DependencyViolation.RouteEntry", "IncorrectInstanceStatus.Initializing"}) {
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{Throttling, "LastTokenProcessing"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(deleteRequest.GetActionName(), raw)
return nil
})
if err != nil {
if IsExpectedErrors(err, EcsNotFound) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), deleteRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"Pending", "Running", "Stopped", "Stopping"}, []string{}, d.Timeout(schema.TimeoutDelete), 10*time.Second, ecsService.InstanceStateRefreshFunc(d.Id(), []string{}))
if _, err = stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
func buildAliyunInstanceArgs(d *schema.ResourceData, meta interface{}) (*ecs.RunInstancesRequest, error) {
client := meta.(*connectivity.AliyunClient)
request := ecs.CreateRunInstancesRequest()
request.RegionId = client.RegionId
request.InstanceType = d.Get("instance_type").(string)
imageID := d.Get("image_id").(string)
request.ImageId = imageID
systemDiskCategory := DiskCategory(d.Get("system_disk_category").(string))
if v, ok := d.GetOk("availability_zone"); ok && v.(string) != "" {
request.ZoneId = v.(string)
}
DiskName := d.Get("system_disk_name").(string)
Description := d.Get("system_disk_description").(string)
request.SystemDiskDiskName = DiskName
request.SystemDiskDescription = Description
request.SystemDiskPerformanceLevel = d.Get("system_disk_performance_level").(string)
request.SystemDiskCategory = string(systemDiskCategory)
request.SystemDiskSize = strconv.Itoa(d.Get("system_disk_size").(int))
if v, ok := d.GetOk("system_disk_auto_snapshot_policy_id"); ok && v.(string) != "" {
request.SystemDiskAutoSnapshotPolicyId = v.(string)
}
if v, ok := d.GetOk("security_groups"); ok {
// At present, the classic network instance does not support multi sg in runInstances
sgs := expandStringList(v.(*schema.Set).List())
if d.Get("vswitch_id").(string) == "" && len(sgs) > 0 {
request.SecurityGroupId = sgs[0]
} else {
request.SecurityGroupIds = &sgs
}
}
if v := d.Get("instance_name").(string); v != "" {
request.InstanceName = v
}
if v := d.Get("credit_specification").(string); v != "" {
request.CreditSpecification = v
}
if v := d.Get("resource_group_id").(string); v != "" {
request.ResourceGroupId = v
}
if v := d.Get("description").(string); v != "" {
request.Description = v
}
if v := d.Get("internet_charge_type").(string); v != "" {
request.InternetChargeType = v
}
request.InternetMaxBandwidthOut = requests.NewInteger(d.Get("internet_max_bandwidth_out").(int))
if v, ok := d.GetOk("internet_max_bandwidth_in"); ok {
request.InternetMaxBandwidthIn = requests.NewInteger(v.(int))
}
if v := d.Get("host_name").(string); v != "" {
request.HostName = v
}
if v := d.Get("password").(string); v != "" {
request.Password = v
}
if v := d.Get("kms_encrypted_password").(string); v != "" {
kmsService := KmsService{client}
decryptResp, err := kmsService.Decrypt(v, d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return request, WrapError(err)
}
request.Password = decryptResp
}
vswitchValue := d.Get("subnet_id").(string)
if vswitchValue == "" {
vswitchValue = d.Get("vswitch_id").(string)
}
if vswitchValue != "" {
request.VSwitchId = vswitchValue
if v, ok := d.GetOk("private_ip"); ok && v.(string) != "" {
request.PrivateIpAddress = v.(string)
}
}
if v := d.Get("instance_charge_type").(string); v != "" {
request.InstanceChargeType = v
}
if request.InstanceChargeType == string(PrePaid) {
request.Period = requests.NewInteger(d.Get("period").(int))
request.PeriodUnit = d.Get("period_unit").(string)
} else {
if v := d.Get("spot_strategy").(string); v != "" {
request.SpotStrategy = v
}
if v := d.Get("spot_price_limit").(float64); v > 0 {
request.SpotPriceLimit = requests.NewFloat(v)
}
}
if v := d.Get("user_data").(string); v != "" {
_, base64DecodeError := base64.StdEncoding.DecodeString(v)
if base64DecodeError == nil {
request.UserData = v
} else {
request.UserData = base64.StdEncoding.EncodeToString([]byte(v))
}
}
if v := d.Get("role_name").(string); v != "" {
request.RamRoleName = v
}
if v := d.Get("key_name").(string); v != "" {
request.KeyPairName = v
}
if v, ok := d.GetOk("security_enhancement_strategy"); ok {
request.SecurityEnhancementStrategy = v.(string)
}
if v, ok := d.GetOk("auto_release_time"); ok && v.(string) != "" {
request.AutoReleaseTime = v.(string)
}
request.DryRun = requests.NewBoolean(d.Get("dry_run").(bool))
request.DeletionProtection = requests.NewBoolean(d.Get("deletion_protection").(bool))
if v, ok := d.GetOk("tags"); ok && len(v.(map[string]interface{})) > 0 {
tags := make([]ecs.RunInstancesTag, 0)
for key, value := range v.(map[string]interface{}) {
tags = append(tags, ecs.RunInstancesTag{
Key: key,
Value: value.(string),
})
}
request.Tag = &tags
}
request.ClientToken = buildClientToken(request.GetActionName())
if v, ok := d.GetOk("data_disks"); ok {
disks := v.([]interface{})
var dataDiskRequests []ecs.RunInstancesDataDisk
for i := range disks {
disk := disks[i].(map[string]interface{})
dataDiskRequest := ecs.RunInstancesDataDisk{
Category: disk["category"].(string),
DeleteWithInstance: strconv.FormatBool(disk["delete_with_instance"].(bool)),
Encrypted: strconv.FormatBool(disk["encrypted"].(bool)),
}
if kmsKeyId, ok := disk["kms_key_id"]; ok {
dataDiskRequest.KMSKeyId = kmsKeyId.(string)
}
if name, ok := disk["name"]; ok {
dataDiskRequest.DiskName = name.(string)
}
if snapshotId, ok := disk["snapshot_id"]; ok {
dataDiskRequest.SnapshotId = snapshotId.(string)
}
if description, ok := disk["description"]; ok {
dataDiskRequest.Description = description.(string)
}
if autoSnapshotPolicyId, ok := disk["auto_snapshot_policy_id"]; ok {
dataDiskRequest.AutoSnapshotPolicyId = autoSnapshotPolicyId.(string)
}
dataDiskRequest.Size = fmt.Sprintf("%d", disk["size"].(int))
dataDiskRequest.Category = disk["category"].(string)
if dataDiskRequest.Category == string(DiskEphemeralSSD) {
dataDiskRequest.DeleteWithInstance = ""
}
if performanceLevel, ok := disk["performance_level"]; ok && dataDiskRequest.Category == string(DiskCloudESSD) {
dataDiskRequest.PerformanceLevel = performanceLevel.(string)
}
dataDiskRequests = append(dataDiskRequests, dataDiskRequest)
}
request.DataDisk = &dataDiskRequests
}
if v, ok := d.GetOk("hpc_cluster_id"); ok {
request.HpcClusterId = v.(string)
}
if v, ok := d.GetOk("deployment_set_id"); ok {
request.DeploymentSetId = v.(string)
}
return request, nil
}
func modifyInstanceChargeType(d *schema.ResourceData, meta interface{}, forceDelete bool) error {
if d.IsNewResource() {
d.Partial(false)
return nil
}
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
chargeType := d.Get("instance_charge_type").(string)
if d.HasChange("instance_charge_type") || forceDelete {
if forceDelete {
chargeType = string(PostPaid)
}
request := ecs.CreateModifyInstanceChargeTypeRequest()
request.InstanceIds = convertListToJsonString(append(make([]interface{}, 0, 1), d.Id()))
request.IncludeDataDisks = requests.NewBoolean(d.Get("include_data_disks").(bool))
request.AutoPay = requests.NewBoolean(true)
request.DryRun = requests.NewBoolean(d.Get("dry_run").(bool))
request.ClientToken = fmt.Sprintf("terraform-modify-instance-charge-type-%s", d.Id())
if chargeType == string(PrePaid) {
request.Period = requests.NewInteger(d.Get("period").(int))
request.PeriodUnit = d.Get("period_unit").(string)
}
request.InstanceChargeType = chargeType
if err := resource.Retry(6*time.Minute, func() *resource.RetryError {
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ModifyInstanceChargeType(request)
})
if err != nil {
if IsExpectedErrors(err, []string{Throttling}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
// Wait for instance charge type has been changed
if err := resource.Retry(5*time.Minute, func() *resource.RetryError {
if instance, err := ecsService.DescribeInstance(d.Id()); err != nil {
return resource.NonRetryableError(err)
} else if instance.InstanceChargeType == chargeType {
return nil
}
return resource.RetryableError(Error("Waitting for instance %s to be %s timeout.", d.Id(), chargeType))
}); err != nil {
return WrapError(err)
}
d.SetPartial("instance_charge_type")
return nil
}
return nil
}
func modifyInstanceImage(d *schema.ResourceData, meta interface{}, run bool) (bool, error) {
if d.IsNewResource() {
d.Partial(false)
return false, nil
}
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
update := false
if d.HasChange("image_id") {
update = true
if !run {
return update, nil
}
instance, err := ecsService.DescribeInstance(d.Id())
if err != nil {
return update, WrapError(err)
}
keyPairName := instance.KeyPairName
request := ecs.CreateReplaceSystemDiskRequest()
request.InstanceId = d.Id()
request.ImageId = d.Get("image_id").(string)
request.SystemDiskSize = requests.NewInteger(d.Get("system_disk_size").(int))
request.ClientToken = buildClientToken(request.GetActionName())
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ReplaceSystemDisk(request)
})
if err != nil {
return update, WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
// Ensure instance's image has been replaced successfully.
timeout := DefaultTimeoutMedium
for {
instance, errDesc := ecsService.DescribeInstance(d.Id())
if errDesc != nil {
return update, WrapError(errDesc)
}
var disk ecs.Disk
err := resource.Retry(2*time.Minute, func() *resource.RetryError {
disk, err = ecsService.DescribeInstanceSystemDisk(d.Id(), instance.ResourceGroupId)
if err != nil {
if NotFoundError(err) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return update, WrapError(err)
}
if instance.ImageId == d.Get("image_id") && disk.Size == d.Get("system_disk_size").(int) {
break
}
time.Sleep(DefaultIntervalShort * time.Second)
timeout = timeout - DefaultIntervalShort
if timeout <= 0 {
return update, WrapError(GetTimeErrorFromString(fmt.Sprintf("Replacing instance %s system disk timeout.", d.Id())))
}
}
d.SetPartial("system_disk_size")
d.SetPartial("image_id")
// After updating image, it need to re-attach key pair
if keyPairName != "" {
if err := ecsService.AttachKeyPair(keyPairName, []interface{}{d.Id()}); err != nil {
return update, WrapError(err)
}
}
}
return update, nil
}
func modifyInstanceAttribute(d *schema.ResourceData, meta interface{}) (bool, error) {
if d.IsNewResource() {
d.Partial(false)
return false, nil
}
update := false
reboot := false
request := ecs.CreateModifyInstanceAttributeRequest()
request.InstanceId = d.Id()
if d.HasChange("instance_name") {
d.SetPartial("instance_name")
request.InstanceName = d.Get("instance_name").(string)
update = true
}
if d.HasChange("description") {
d.SetPartial("description")
request.Description = d.Get("description").(string)
update = true
}
if d.HasChange("user_data") {
d.SetPartial("user_data")
if v, ok := d.GetOk("user_data"); ok && v.(string) != "" {
_, base64DecodeError := base64.StdEncoding.DecodeString(v.(string))
if base64DecodeError == nil {
request.UserData = v.(string)
} else {
request.UserData = base64.StdEncoding.EncodeToString([]byte(v.(string)))
}
}
update = true
reboot = true
}
if d.HasChange("host_name") {
d.SetPartial("host_name")
request.HostName = d.Get("host_name").(string)
update = true
reboot = true
}
if d.HasChange("password") || d.HasChange("kms_encrypted_password") {
if v := d.Get("password").(string); v != "" {
d.SetPartial("password")
request.Password = v
update = true
reboot = true
}
if v := d.Get("kms_encrypted_password").(string); v != "" {
kmsService := KmsService{meta.(*connectivity.AliyunClient)}
decryptResp, err := kmsService.Decrypt(v, d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return reboot, WrapError(err)
}
request.Password = decryptResp
d.SetPartial("kms_encrypted_password")
d.SetPartial("kms_encryption_context")
update = true
reboot = true
}
}
if d.HasChange("deletion_protection") {
d.SetPartial("deletion_protection")
request.DeletionProtection = requests.NewBoolean(d.Get("deletion_protection").(bool))
update = true
}
if d.HasChange("credit_specification") {
d.SetPartial("credit_specification")
request.CreditSpecification = d.Get("credit_specification").(string)
update = true
}
client := meta.(*connectivity.AliyunClient)
if update {
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ModifyInstanceAttribute(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidChargeType.ValueNotSupported"}) {
time.Sleep(time.Minute)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return reboot, WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
return reboot, nil
}
func modifyVpcAttribute(d *schema.ResourceData, meta interface{}, run bool) (bool, error) {
if d.IsNewResource() {
d.Partial(false)
return false, nil
}
update := false
request := ecs.CreateModifyInstanceVpcAttributeRequest()
request.InstanceId = d.Id()
request.VSwitchId = d.Get("vswitch_id").(string)
if d.HasChange("vswitch_id") {
update = true
if d.Get("vswitch_id").(string) == "" {
return update, WrapError(Error("Field 'vswitch_id' is required when modifying the instance VPC attribute."))
}
d.SetPartial("vswitch_id")
}
if d.HasChange("subnet_id") {
update = true
if d.Get("subnet_id").(string) == "" {
return update, WrapError(Error("Field 'subnet_id' is required when modifying the instance VPC attribute."))
}
request.VSwitchId = d.Get("subnet_id").(string)
d.SetPartial("subnet_id")
}
if request.VSwitchId != "" && d.HasChange("private_ip") {
request.PrivateIpAddress = d.Get("private_ip").(string)
update = true
d.SetPartial("private_ip")
}
if !run {
return update, nil
}
if update {
client := meta.(*connectivity.AliyunClient)
err := resource.Retry(1*time.Minute, func() *resource.RetryError {
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ModifyInstanceVpcAttribute(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"OperationConflict"}) {
time.Sleep(1 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return update, WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
ecsService := EcsService{client}
if err := ecsService.WaitForVpcAttributesChanged(d.Id(), request.VSwitchId, request.PrivateIpAddress); err != nil {
return update, WrapError(err)
}
}
return update, nil
}
func modifyInstanceType(d *schema.ResourceData, meta interface{}, run bool) (bool, error) {
if d.IsNewResource() {
d.Partial(false)
return false, nil
}
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
update := false
if d.HasChange("instance_type") {
update = true
if !run {
return update, nil
}
// Ensure instance_type is valid
//zoneId, validZones, err := ecsService.DescribeAvailableResources(d, meta, InstanceTypeResource)
//if err != nil {
// return update, WrapError(err)
//}
//if err = ecsService.InstanceTypeValidation(d.Get("instance_type").(string), zoneId, validZones); err != nil {
// return update, WrapError(err)
//}
// There should use the old instance charge type to decide API method because of instance_charge_type will be updated at last step
oldCharge, _ := d.GetChange("instance_charge_type")
if oldCharge.(string) == string(PrePaid) {
request := ecs.CreateModifyPrepayInstanceSpecRequest()
request.InstanceId = d.Id()
request.InstanceType = d.Get("instance_type").(string)
err := resource.Retry(6*time.Minute, func() *resource.RetryError {
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ModifyPrepayInstanceSpec(request)
})
if err != nil {
if IsExpectedErrors(err, []string{Throttling}) {
time.Sleep(5 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return update, WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
} else {
//An instance that was successfully modified once cannot be modified again within 5 minutes.
request := ecs.CreateModifyInstanceSpecRequest()
request.InstanceId = d.Id()
request.InstanceType = d.Get("instance_type").(string)
request.ClientToken = buildClientToken(request.GetActionName())
err := resource.Retry(6*time.Minute, func() *resource.RetryError {
args := *request
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ModifyInstanceSpec(&args)
})
if err != nil {
if IsExpectedErrors(err, []string{Throttling}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return update, WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
// Ensure instance's type has been replaced successfully.
timeout := DefaultTimeoutMedium
for {
instance, err := ecsService.DescribeInstance(d.Id())
if err != nil {
return update, WrapError(err)
}
if instance.InstanceType == d.Get("instance_type").(string) {
break
}
timeout = timeout - DefaultIntervalShort
if timeout <= 0 {
return update, WrapErrorf(err, WaitTimeoutMsg, d.Id(), GetFunc(1), timeout, instance.InstanceType, d.Get("instance_type"), ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
d.SetPartial("instance_type")
}
return update, nil
}
func modifyInstanceNetworkSpec(d *schema.ResourceData, meta interface{}) error {
if d.IsNewResource() {
d.Partial(false)
return nil
}
allocate := false
update := false
request := ecs.CreateModifyInstanceNetworkSpecRequest()
request.InstanceId = d.Id()
request.ClientToken = buildClientToken(request.GetActionName())
if d.HasChange("internet_charge_type") {
request.NetworkChargeType = d.Get("internet_charge_type").(string)
update = true
d.SetPartial("internet_charge_type")
}
if d.HasChange("internet_max_bandwidth_out") {
o, n := d.GetChange("internet_max_bandwidth_out")
if o.(int) <= 0 && n.(int) > 0 {
allocate = true
}
request.InternetMaxBandwidthOut = requests.NewInteger(n.(int))
update = true
d.SetPartial("internet_max_bandwidth_out")
}
if d.HasChange("internet_max_bandwidth_in") {
request.InternetMaxBandwidthIn = requests.NewInteger(d.Get("internet_max_bandwidth_in").(int))
update = true
d.SetPartial("internet_max_bandwidth_in")
}
//An instance that was successfully modified once cannot be modified again within 5 minutes.
wait := incrementalWait(2*time.Second, 2*time.Second)
client := meta.(*connectivity.AliyunClient)
if update {
if err := resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ModifyInstanceNetworkSpec(request)
})
if err != nil {
if IsExpectedErrors(err, []string{Throttling, "LastOrderProcessing", "LastRequestProcessing", "LastTokenProcessing"}) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"InternalError"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
ecsService := EcsService{client: client}
deadline := time.Now().Add(DefaultTimeout * time.Second)
for {
instance, err := ecsService.DescribeInstance(d.Id())
if err != nil {
return WrapError(err)
}
if instance.InternetMaxBandwidthOut == d.Get("internet_max_bandwidth_out").(int) &&
instance.InternetChargeType == d.Get("internet_charge_type").(string) {
break
}
if time.Now().After(deadline) {
return WrapError(Error(`wait for internet update timeout! expect internet_charge_type value %s, get %s
expect internet_max_bandwidth_out value %d, get %d,`,
d.Get("internet_charge_type").(string), instance.InternetChargeType, d.Get("internet_max_bandwidth_out").(int),
instance.InternetMaxBandwidthOut))
}
time.Sleep(1 * time.Second)
}
if allocate {
request := ecs.CreateAllocatePublicIpAddressRequest()
request.InstanceId = d.Id()
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.AllocatePublicIpAddress(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudIotDeviceGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudIotDeviceGroupCreate,
Read: resourceAlicloudIotDeviceGroupRead,
Update: resourceAlicloudIotDeviceGroupUpdate,
Delete: resourceAlicloudIotDeviceGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"group_desc": {
Type: schema.TypeString,
Optional: true,
},
"group_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(0, 30),
},
"iot_instance_id": {
Type: schema.TypeString,
Optional: true,
},
"super_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudIotDeviceGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateDeviceGroup"
request := make(map[string]interface{})
conn, err := client.NewIotClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("group_desc"); ok {
request["GroupDesc"] = v
}
request["GroupName"] = d.Get("group_name")
if v, ok := d.GetOk("iot_instance_id"); ok {
request["IotInstanceId"] = v
}
if v, ok := d.GetOk("super_group_id"); ok {
request["SuperGroupId"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_iot_device_group", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
responseData := response["Data"].(map[string]interface{})
d.SetId(fmt.Sprint(responseData["GroupId"]))
return resourceAlicloudIotDeviceGroupRead(d, meta)
}
func resourceAlicloudIotDeviceGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
iotService := IotService{client}
object, err := iotService.DescribeIotDeviceGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_iot_device_group iotService.DescribeIotDeviceGroup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
descmap := object["Data"].(map[string]interface{})
if val, exist := descmap["GroupDesc"]; exist {
d.Set("group_desc", val)
}
d.Set("group_name", object["Data"].(map[string]interface{})["GroupName"])
return nil
}
func resourceAlicloudIotDeviceGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"GroupId": d.Id(),
}
if d.HasChange("group_desc") {
update = true
if v, ok := d.GetOk("group_desc"); ok {
request["GroupDesc"] = v
}
}
if d.HasChange("iot_instance_id") {
update = true
if v, ok := d.GetOk("iot_instance_id"); ok {
request["IotInstanceId"] = v
}
}
if update {
action := "UpdateDeviceGroup"
conn, err := client.NewIotClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
}
return resourceAlicloudIotDeviceGroupRead(d, meta)
}
func resourceAlicloudIotDeviceGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteDeviceGroup"
var response map[string]interface{}
conn, err := client.NewIotClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"GroupId": d.Id(),
}
if v, ok := d.GetOk("iot_instance_id"); ok {
request["IotInstanceId"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudKmsAlias() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudKmsAliasCreate,
Read: resourceAlicloudKmsAliasRead,
Update: resourceAlicloudKmsAliasUpdate,
Delete: resourceAlicloudKmsAliasDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"alias_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"key_id": {
Type: schema.TypeString,
Required: true,
},
},
}
}
func resourceAlicloudKmsAliasCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateAlias"
request := make(map[string]interface{})
conn, err := client.NewKmsClient()
if err != nil {
return WrapError(err)
}
request["AliasName"] = d.Get("alias_name")
request["KeyId"] = d.Get("key_id")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_kms_alias", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["AliasName"]))
return resourceAlicloudKmsAliasRead(d, meta)
}
func resourceAlicloudKmsAliasRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
kmsService := KmsService{client}
object, err := kmsService.DescribeKmsAlias(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_kms_alias kmsService.DescribeKmsAlias Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("alias_name", d.Id())
d.Set("key_id", object["KeyId"])
return nil
}
func resourceAlicloudKmsAliasUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
if d.HasChange("key_id") {
request := map[string]interface{}{
"AliasName": d.Id(),
}
request["KeyId"] = d.Get("key_id")
action := "UpdateAlias"
conn, err := client.NewKmsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudKmsAliasRead(d, meta)
}
func resourceAlicloudKmsAliasDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteAlias"
var response map[string]interface{}
conn, err := client.NewKmsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AliasName": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"strconv"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudKmsCiphertext() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudKmsCiphertextCreate,
Read: schema.Noop,
Delete: resourceAlicloudKmsCiphertextDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"plaintext": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Sensitive: true,
},
"key_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"encryption_context": {
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"ciphertext_blob": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudKmsCiphertextCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
// Since a ciphertext has no ID, we create an ID based on
// current unix time.
d.SetId(strconv.FormatInt(time.Now().Unix(), 16))
action := "Encrypt"
request := make(map[string]interface{})
request["Plaintext"] = d.Get("plaintext")
request["KeyId"] = d.Get("key_id")
request["RegionId"] = client.RegionId
if context := d.Get("encryption_context"); context != nil {
cm := context.(map[string]interface{})
contextJson, err := convertMaptoJsonString(cm)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_kms_ciphertext", action, AlibabaCloudSdkGoERROR)
}
request["EncryptionContext"] = contextJson
}
var response map[string]interface{}
conn, err := client.NewKmsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_kms_ciphertext", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.CiphertextBlob", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, action, "$.CiphertextBlob", response)
}
d.Set("ciphertext_blob", resp)
return nil
}
func resourceAlicloudKmsCiphertextDelete(d *schema.ResourceData, meta interface{}) error {
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudKmsKey() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudKmsKeyCreate,
Read: resourceAlicloudKmsKeyRead,
Update: resourceAlicloudKmsKeyUpdate,
Delete: resourceAlicloudKmsKeyDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"arn": {
Type: schema.TypeString,
Computed: true,
},
"automatic_rotation": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Disabled", "Enabled"}, false),
Default: "Disabled",
},
"creation_date": {
Type: schema.TypeString,
Computed: true,
},
"creator": {
Type: schema.TypeString,
Computed: true,
},
"delete_date": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"key_spec": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Aliyun_AES_256", "Aliyun_SM4", "RSA_2048", "EC_P256", "EC_P256K", "EC_SM2"}, false),
},
"is_enabled": {
Type: schema.TypeBool,
Optional: true,
Deprecated: "Field 'is_enabled' has been deprecated from provider version 1.85.0. New field 'key_state' instead.",
},
"key_usage": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ENCRYPT/DECRYPT", "SIGN/VERIFY"}, false),
Default: "ENCRYPT/DECRYPT",
},
"last_rotation_date": {
Type: schema.TypeString,
Computed: true,
},
"material_expire_time": {
Type: schema.TypeString,
Computed: true,
},
"next_rotation_date": {
Type: schema.TypeString,
Computed: true,
},
"origin": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Aliyun_KMS", "EXTERNAL"}, false),
Default: "Aliyun_KMS",
},
"pending_window_in_days": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ConflictsWith: []string{"deletion_window_in_days"},
ValidateFunc: validation.IntBetween(7, 30),
},
"deletion_window_in_days": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Deprecated: "Field 'deletion_window_in_days' has been deprecated from provider version 1.85.0. New field 'pending_window_in_days' instead.",
ConflictsWith: []string{"pending_window_in_days"},
ValidateFunc: validation.IntBetween(7, 30),
},
"primary_key_version": {
Type: schema.TypeString,
Computed: true,
},
"protection_level": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"SOFTWARE", "HSM"}, false),
Default: "SOFTWARE",
},
"rotation_interval": {
Type: schema.TypeString,
Optional: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Disabled", "Enabled", "PendingDeletion"}, false),
ConflictsWith: []string{"key_state"},
},
"key_state": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Disabled", "Enabled", "PendingDeletion"}, false),
ConflictsWith: []string{"status"},
Deprecated: "Field 'key_state' has been deprecated from provider version 1.123.1. New field 'status' instead.",
},
},
}
}
func resourceAlicloudKmsKeyCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateKey"
request := make(map[string]interface{})
conn, err := client.NewKmsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("automatic_rotation"); ok {
request["EnableAutomaticRotation"] = convertKmsKeyAutomaticRotationRequest(v.(string))
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("key_spec"); ok {
request["KeySpec"] = v
}
if v, ok := d.GetOk("key_usage"); ok {
request["KeyUsage"] = v
}
if v, ok := d.GetOk("origin"); ok {
request["Origin"] = v
}
if v, ok := d.GetOk("protection_level"); ok {
request["ProtectionLevel"] = v
}
if v, ok := d.GetOk("rotation_interval"); ok {
request["RotationInterval"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_kms_key", action, AlibabaCloudSdkGoERROR)
}
responseKeyMetadata := response["KeyMetadata"].(map[string]interface{})
d.SetId(fmt.Sprint(responseKeyMetadata["KeyId"]))
return resourceAlicloudKmsKeyUpdate(d, meta)
}
func resourceAlicloudKmsKeyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
kmsService := KmsService{client}
object, err := kmsService.DescribeKmsKey(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_kms_key kmsService.DescribeKmsKey Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("arn", object["Arn"])
d.Set("automatic_rotation", object["AutomaticRotation"])
d.Set("creator", object["Creator"])
d.Set("creation_date", object["CreationDate"])
d.Set("delete_date", object["DeleteDate"])
d.Set("description", object["Description"])
d.Set("key_spec", object["KeySpec"])
d.Set("key_usage", object["KeyUsage"])
d.Set("last_rotation_date", object["LastRotationDate"])
d.Set("material_expire_time", object["MaterialExpireTime"])
d.Set("next_rotation_date", object["NextRotationDate"])
d.Set("origin", object["Origin"])
d.Set("primary_key_version", object["PrimaryKeyVersion"])
d.Set("protection_level", object["ProtectionLevel"])
d.Set("rotation_interval", object["RotationInterval"])
d.Set("status", object["KeyState"])
d.Set("key_state", object["KeyState"])
return nil
}
func resourceAlicloudKmsKeyUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
kmsService := KmsService{client}
var response map[string]interface{}
d.Partial(true)
if !d.IsNewResource() && d.HasChange("description") {
request := map[string]interface{}{
"KeyId": d.Id(),
}
request["Description"] = d.Get("description")
action := "UpdateKeyDescription"
conn, err := client.NewKmsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("description")
}
update := false
request := map[string]interface{}{
"KeyId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("automatic_rotation") {
update = true
}
request["EnableAutomaticRotation"] = convertKmsKeyAutomaticRotationRequest(d.Get("automatic_rotation").(string))
if !d.IsNewResource() && d.HasChange("rotation_interval") {
update = true
request["RotationInterval"] = d.Get("rotation_interval")
}
if update {
action := "UpdateRotationPolicy"
conn, err := client.NewKmsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("automatic_rotation")
d.SetPartial("rotation_interval")
}
if d.HasChange("status") || d.HasChange("key_state") || d.HasChange("is_enabled") {
object, err := kmsService.DescribeKmsKey(d.Id())
if err != nil {
return WrapError(err)
}
var target = ""
if k, ok := d.GetOk("status"); ok {
target = k.(string)
} else if k, ok := d.GetOk("key_state"); ok {
target = k.(string)
} else {
if k, ok := d.GetOk("is_enabled"); ok {
if k.(bool) {
target = "Enable"
} else {
target = "Disabled"
}
}
}
if object["KeyState"].(string) != target {
if target == "Disabled" {
request := map[string]interface{}{
"KeyId": d.Id(),
}
action := "DisableKey"
conn, err := client.NewKmsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if target == "Enabled" {
request := map[string]interface{}{
"KeyId": d.Id(),
}
action := "EnableKey"
conn, err := client.NewKmsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("status")
d.SetPartial("key_state")
d.SetPartial("is_enabled")
}
}
d.Partial(false)
return resourceAlicloudKmsKeyRead(d, meta)
}
func resourceAlicloudKmsKeyDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ScheduleKeyDeletion"
var response map[string]interface{}
conn, err := client.NewKmsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"KeyId": d.Id(),
}
if v, ok := d.GetOk("pending_window_in_days"); ok {
request["PendingWindowInDays"] = v
} else if v, ok := d.GetOk("deletion_window_in_days"); ok {
request["PendingWindowInDays"] = v
} else {
return WrapError(Error(`[ERROR] Argument "pending_window_in_days" or "deletion_window_in_days" must be set one!`))
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func convertKmsKeyAutomaticRotationRequest(source interface{}) interface{} {
switch source {
case "Disabled":
return false
case "Enabled":
return true
}
return false
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudKmsKeyVersion() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudKmsKeyVersionCreate,
Read: resourceAlicloudKmsKeyVersionRead,
Delete: resourceAlicloudKmsKeyVersionDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"key_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"key_version_id": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudKmsKeyVersionCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateKeyVersion"
request := make(map[string]interface{})
conn, err := client.NewKmsClient()
if err != nil {
return WrapError(err)
}
request["KeyId"] = d.Get("key_id")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_kms_key_version", action, AlibabaCloudSdkGoERROR)
}
responseKeyVersion := response["KeyVersion"].(map[string]interface{})
d.SetId(fmt.Sprint(responseKeyVersion["KeyId"], ":", responseKeyVersion["KeyVersionId"]))
return resourceAlicloudKmsKeyVersionRead(d, meta)
}
func resourceAlicloudKmsKeyVersionRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
kmsService := KmsService{client}
_, err := kmsService.DescribeKmsKeyVersion(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_kms_key_version kmsService.DescribeKmsKeyVersion Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("key_id", parts[0])
d.Set("key_version_id", parts[1])
return nil
}
func resourceAlicloudKmsKeyVersionDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudKmsKeyVersion. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
package alicloud
import (
"encoding/json"
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudKmsSecret() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudKmsSecretCreate,
Read: resourceAlicloudKmsSecretRead,
Update: resourceAlicloudKmsSecretUpdate,
Delete: resourceAlicloudKmsSecretDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
Delete: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"arn": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"enable_automatic_rotation": {
Type: schema.TypeBool,
Optional: true,
},
"encryption_key_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"force_delete_without_recovery": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"planned_delete_time": {
Type: schema.TypeString,
Computed: true,
},
"recovery_window_in_days": {
Type: schema.TypeInt,
Optional: true,
Default: 30,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("force_delete_without_recovery").(bool)
},
},
"rotation_interval": {
Type: schema.TypeString,
Optional: true,
},
"secret_data": {
Type: schema.TypeString,
Required: true,
Sensitive: true,
},
"secret_data_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"binary", "text"}, false),
Default: "text",
},
"secret_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"tags": tagsSchema(),
"version_id": {
Type: schema.TypeString,
Required: true,
},
"version_stages": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
}
}
func resourceAlicloudKmsSecretCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateSecret"
request := make(map[string]interface{})
conn, err := client.NewKmsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOkExists("enable_automatic_rotation"); ok {
request["EnableAutomaticRotation"] = v
}
if v, ok := d.GetOk("encryption_key_id"); ok {
request["EncryptionKeyId"] = v
}
if v, ok := d.GetOk("rotation_interval"); ok {
request["RotationInterval"] = v
}
request["SecretData"] = d.Get("secret_data")
if v, ok := d.GetOk("secret_data_type"); ok {
request["SecretDataType"] = v
}
request["SecretName"] = d.Get("secret_name")
if v, ok := d.GetOk("tags"); ok {
addTags := make([]JsonTag, 0)
for key, value := range v.(map[string]interface{}) {
addTags = append(addTags, JsonTag{
TagKey: key,
TagValue: value.(string),
})
}
tags, err := json.Marshal(addTags)
if err != nil {
return WrapError(err)
}
request["Tags"] = string(tags)
}
request["VersionId"] = d.Get("version_id")
wait := incrementalWait(3*time.Second, 1*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_kms_secret", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["SecretName"]))
return resourceAlicloudKmsSecretUpdate(d, meta)
}
func resourceAlicloudKmsSecretRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
kmsService := KmsService{client}
object, err := kmsService.DescribeKmsSecret(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_kms_secret kmsService.DescribeKmsSecret Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("secret_name", d.Id())
d.Set("arn", object["Arn"])
d.Set("description", object["Description"])
d.Set("encryption_key_id", object["EncryptionKeyId"])
d.Set("planned_delete_time", object["PlannedDeleteTime"])
if v, ok := object["Tags"].(map[string]interface{}); ok {
d.Set("tags", tagsToMap(v["Tag"]))
}
getSecretValueObject, err := kmsService.GetSecretValue(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("secret_data", getSecretValueObject["SecretData"])
d.Set("secret_data_type", getSecretValueObject["SecretDataType"])
d.Set("version_id", getSecretValueObject["VersionId"])
d.Set("version_stages", getSecretValueObject["VersionStages"].(map[string]interface{})["VersionStage"])
return nil
}
func resourceAlicloudKmsSecretUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
kmsService := KmsService{client}
var response map[string]interface{}
d.Partial(true)
if !d.IsNewResource() && d.HasChange("tags") {
if err := kmsService.SetResourceTags(d, "secret"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
if !d.IsNewResource() && d.HasChange("description") {
request := map[string]interface{}{
"SecretName": d.Id(),
}
request["Description"] = d.Get("description")
action := "UpdateSecret"
conn, err := client.NewKmsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 1*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("description")
}
update := false
request := map[string]interface{}{
"SecretName": d.Id(),
}
if !d.IsNewResource() && d.HasChange("secret_data") {
update = true
}
request["SecretData"] = d.Get("secret_data")
if !d.IsNewResource() && d.HasChange("version_id") {
update = true
}
request["VersionId"] = d.Get("version_id")
if !d.IsNewResource() && d.HasChange("secret_data_type") {
update = true
request["SecretDataType"] = d.Get("secret_data_type")
}
if d.HasChange("version_stages") {
update = true
request["VersionStages"] = convertListToJsonString(d.Get("version_stages").(*schema.Set).List())
}
if update {
action := "PutSecretValue"
conn, err := client.NewKmsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 1*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("secret_data")
d.SetPartial("version_id")
d.SetPartial("secret_data_type")
d.SetPartial("version_stages")
}
d.Partial(false)
return resourceAlicloudKmsSecretRead(d, meta)
}
func resourceAlicloudKmsSecretDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteSecret"
var response map[string]interface{}
conn, err := client.NewKmsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"SecretName": d.Id(),
}
if v, ok := d.GetOkExists("force_delete_without_recovery"); ok {
request["ForceDeleteWithoutRecovery"] = fmt.Sprintf("%v", v.(bool))
}
if v, ok := d.GetOk("recovery_window_in_days"); ok {
request["RecoveryWindowInDays"] = v
}
wait := incrementalWait(3*time.Second, 1*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Forbidden.ResourceNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
r_kvstore "github.com/aliyun/alibaba-cloud-sdk-go/services/r-kvstore"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudKvstoreAccount() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudKvstoreAccountCreate,
Read: resourceAlicloudKvstoreAccountRead,
Update: resourceAlicloudKvstoreAccountUpdate,
Delete: resourceAlicloudKvstoreAccountDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(6 * time.Minute),
Update: schema.DefaultTimeout(6 * time.Minute),
},
Schema: map[string]*schema.Schema{
"account_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"account_password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"account_privilege": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"RoleReadOnly", "RoleReadWrite", "RoleRepl"}, false),
Default: "RoleReadWrite",
},
"account_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Normal"}, false),
Default: "Normal",
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"kms_encrypted_password": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: kmsDiffSuppressFunc,
},
"kms_encryption_context": {
Type: schema.TypeMap,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("kms_encrypted_password").(string) == ""
},
Elem: schema.TypeString,
},
},
}
}
func resourceAlicloudKvstoreAccountCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
r_kvstoreService := R_kvstoreService{client}
request := r_kvstore.CreateCreateAccountRequest()
request.AccountName = d.Get("account_name").(string)
request.AccountPassword = d.Get("account_password").(string)
if request.AccountPassword == "" {
if v := d.Get("kms_encrypted_password").(string); v != "" {
kmsService := KmsService{client}
decryptResp, err := kmsService.Decrypt(v, d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request.AccountPassword = decryptResp
}
}
if request.AccountPassword == "" {
return WrapError(Error("One of the 'account_password' and 'kms_encrypted_password' should be set."))
}
if v, ok := d.GetOk("account_privilege"); ok {
request.AccountPrivilege = v.(string)
}
if v, ok := d.GetOk("account_type"); ok {
request.AccountType = v.(string)
}
if v, ok := d.GetOk("description"); ok {
request.AccountDescription = v.(string)
}
request.InstanceId = d.Get("instance_id").(string)
wait := incrementalWait(3*time.Second, 30*time.Second)
err := resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.CreateAccount(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"OperationDeniedDBStatus"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw)
response, _ := raw.(*r_kvstore.CreateAccountResponse)
d.SetId(fmt.Sprintf("%v:%v", response.InstanceId, response.AcountName))
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_kvstore_account", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 60*time.Second, r_kvstoreService.KvstoreAccountStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudKvstoreAccountRead(d, meta)
}
func resourceAlicloudKvstoreAccountRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
r_kvstoreService := R_kvstoreService{client}
object, err := r_kvstoreService.DescribeKvstoreAccount(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_kvstore_account r_kvstoreService.DescribeKvstoreAccount Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("account_name", parts[1])
d.Set("instance_id", parts[0])
d.Set("account_type", object.AccountType)
d.Set("description", object.AccountDescription)
d.Set("status", object.AccountStatus)
if len(object.DatabasePrivileges.DatabasePrivilege) > 0 {
d.Set("account_privilege", object.DatabasePrivileges.DatabasePrivilege[0].AccountPrivilege)
}
return nil
}
func resourceAlicloudKvstoreAccountUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
r_kvstoreService := R_kvstoreService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Partial(true)
if d.HasChange("account_privilege") {
request := r_kvstore.CreateGrantAccountPrivilegeRequest()
request.AccountName = parts[1]
request.InstanceId = parts[0]
request.AccountPrivilege = d.Get("account_privilege").(string)
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.GrantAccountPrivilege(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 120*time.Second, r_kvstoreService.KvstoreAccountStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("account_privilege")
}
if d.HasChange("description") {
request := r_kvstore.CreateModifyAccountDescriptionRequest()
request.AccountName = parts[1]
request.InstanceId = parts[0]
request.AccountDescription = d.Get("description").(string)
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.ModifyAccountDescription(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("description")
}
if d.HasChange("account_password") || d.HasChange("kms_encrypted_password") {
request := r_kvstore.CreateResetAccountPasswordRequest()
request.AccountName = parts[1]
request.InstanceId = parts[0]
password := d.Get("account_password").(string)
kmsPassword := d.Get("kms_encrypted_password").(string)
if password == "" && kmsPassword == "" {
return WrapError(Error("One of the 'account_password' and 'kms_encrypted_password' should be set."))
}
if password != "" {
request.AccountPassword = password
} else {
kmsService := KmsService{meta.(*connectivity.AliyunClient)}
decryptResp, err := kmsService.Decrypt(kmsPassword, d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request.AccountPassword = decryptResp
}
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.ResetAccountPassword(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 120*time.Second, r_kvstoreService.KvstoreAccountStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("kms_encrypted_password")
d.SetPartial("kms_encryption_context")
d.SetPartial("account_password")
}
d.Partial(false)
return resourceAlicloudKvstoreAccountRead(d, meta)
}
func resourceAlicloudKvstoreAccountDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request := r_kvstore.CreateDeleteAccountRequest()
request.AccountName = parts[1]
request.InstanceId = parts[0]
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.DeleteAccount(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidAccountName.NotFound", "InvalidInstanceId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudKvstoreAuditLogConfig() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudKvstoreAuditLogConfigCreate,
Read: resourceAlicloudKvstoreAuditLogConfigRead,
Update: resourceAlicloudKvstoreAuditLogConfigUpdate,
Delete: resourceAlicloudKvstoreAuditLogConfigDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"db_audit": {
Type: schema.TypeBool,
Optional: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"retention": {
Type: schema.TypeInt,
Optional: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudKvstoreAuditLogConfigCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "ModifyAuditLogConfig"
request := make(map[string]interface{})
conn, err := client.NewRedisaClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("db_audit"); ok {
request["DbAudit"] = v
}
request["InstanceId"] = d.Get("instance_id")
if v, ok := d.GetOk("retention"); ok {
request["Retention"] = v
} else if v, ok := d.GetOkExists("db_audit"); ok && v.(bool) {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is %v ", "retention", "db_audit", d.Get("db_audit")))
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_kvstore_audit_log_config", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["InstanceId"]))
rKvstoreService := RKvstoreService{client}
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, rKvstoreService.KvstoreAuditLogConfigStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudKvstoreAuditLogConfigRead(d, meta)
}
func resourceAlicloudKvstoreAuditLogConfigRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rKvstoreService := RKvstoreService{client}
object, err := rKvstoreService.DescribeKvstoreAuditLogConfig(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_kvstore_audit_log_config rKvstoreService.DescribeKvstoreAuditLogConfig Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_id", d.Id())
d.Set("db_audit", object["DbAudit"])
if v, ok := object["Retention"]; ok && v.(string) != "" {
d.Set("retention", formatInt(v))
}
describeInstanceAttributeObject, err := rKvstoreService.DescribeInstanceAttribute(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("create_time", describeInstanceAttributeObject["CreateTime"])
d.Set("status", describeInstanceAttributeObject["InstanceStatus"])
return nil
}
func resourceAlicloudKvstoreAuditLogConfigUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rKvstoreService := RKvstoreService{client}
var response map[string]interface{}
update := false
request := map[string]interface{}{
"InstanceId": d.Id(),
}
if d.HasChange("db_audit") || d.IsNewResource() {
update = true
if v, ok := d.GetOkExists("db_audit"); ok {
request["DbAudit"] = v
}
}
if d.HasChange("retention") {
update = true
if v, ok := d.GetOk("retention"); ok {
request["Retention"] = v
} else if v, ok := d.GetOkExists("db_audit"); ok && v.(bool) {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is %v ", "retention", "db_audit", d.Get("db_audit")))
}
}
if update {
action := "ModifyAuditLogConfig"
conn, err := client.NewRedisaClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, rKvstoreService.KvstoreAuditLogConfigStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudKvstoreAuditLogConfigRead(d, meta)
}
func resourceAlicloudKvstoreAuditLogConfigDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudKvstoreAuditLogConfig. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
package alicloud
import (
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
r_kvstore "github.com/aliyun/alibaba-cloud-sdk-go/services/r-kvstore"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudKVStoreBackupPolicy() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudKVStoreBackupPolicyCreate,
Read: resourceAlicloudKVStoreBackupPolicyRead,
Update: resourceAlicloudKVStoreBackupPolicyUpdate,
Delete: resourceAlicloudKVStoreBackupPolicyDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Update: schema.DefaultTimeout(40 * time.Minute),
},
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"backup_time": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice(BACKUP_TIME, false),
Optional: true,
Default: "02:00Z-03:00Z",
},
"backup_period": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
// terraform does not support ValidateFunc of TypeList attr
// ValidateFunc: validateAllowedStringValue([]string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}),
Optional: true,
Computed: true,
},
},
}
}
func resourceAlicloudKVStoreBackupPolicyCreate(d *schema.ResourceData, meta interface{}) error {
d.SetId(d.Get("instance_id").(string))
return resourceAlicloudKVStoreBackupPolicyUpdate(d, meta)
}
func resourceAlicloudKVStoreBackupPolicyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
kvstoreService := KvstoreService{client}
object, err := kvstoreService.DescribeKVstoreBackupPolicy(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_id", d.Id())
d.Set("backup_time", object.PreferredBackupTime)
d.Set("backup_period", strings.Split(object.PreferredBackupPeriod, ","))
return nil
}
func resourceAlicloudKVStoreBackupPolicyUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
r_kvstoreService := R_kvstoreService{client}
if d.HasChange("backup_time") || d.HasChange("backup_period") {
client := meta.(*connectivity.AliyunClient)
kvstoreService := KvstoreService{client}
request := r_kvstore.CreateModifyBackupPolicyRequest()
request.RegionId = client.RegionId
request.InstanceId = d.Id()
request.PreferredBackupTime = d.Get("backup_time").(string)
periodList := expandStringList(d.Get("backup_period").(*schema.Set).List())
request.PreferredBackupPeriod = strings.Join(periodList, COMMA_SEPARATED)
raw, err := client.WithRkvClient(func(rkvClient *r_kvstore.Client) (interface{}, error) {
return rkvClient.ModifyBackupPolicy(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutUpdate), 60*time.Second, r_kvstoreService.KvstoreInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
// There is a random error and need waiting some seconds to ensure the update is success
_, err = kvstoreService.DescribeKVstoreBackupPolicy(d.Id())
if err != nil {
return WrapError(err)
}
}
return resourceAlicloudKVStoreBackupPolicyRead(d, meta)
}
func resourceAlicloudKVStoreBackupPolicyDelete(d *schema.ResourceData, meta interface{}) error {
// In case of a delete we are resetting to default values which is Monday - Sunday each 3am-4am
client := meta.(*connectivity.AliyunClient)
r_kvstoreService := R_kvstoreService{client}
request := r_kvstore.CreateModifyBackupPolicyRequest()
request.RegionId = client.RegionId
request.InstanceId = d.Id()
request.PreferredBackupTime = "01:00Z-02:00Z"
request.PreferredBackupPeriod = "Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday"
raw, err := client.WithRkvClient(func(rkvClient *r_kvstore.Client) (interface{}, error) {
return rkvClient.ModifyBackupPolicy(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutUpdate), 60*time.Second, r_kvstoreService.KvstoreInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
r_kvstore "github.com/aliyun/alibaba-cloud-sdk-go/services/r-kvstore"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudKvstoreConnection() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudKvstoreConnectionCreate,
Read: resourceAlicloudKvstoreConnectionRead,
Update: resourceAlicloudKvstoreConnectionUpdate,
Delete: resourceAlicloudKvstoreConnectionDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(2 * time.Minute),
Delete: schema.DefaultTimeout(2 * time.Minute),
Update: schema.DefaultTimeout(2 * time.Minute),
},
Schema: map[string]*schema.Schema{
"connection_string": {
Type: schema.TypeString,
Computed: true,
},
"connection_string_prefix": {
Type: schema.TypeString,
Required: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"port": {
Type: schema.TypeString,
Required: true,
},
},
}
}
func resourceAlicloudKvstoreConnectionCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
r_kvstoreService := R_kvstoreService{client}
request := r_kvstore.CreateAllocateInstancePublicConnectionRequest()
request.ConnectionStringPrefix = d.Get("connection_string_prefix").(string)
request.InstanceId = d.Get("instance_id").(string)
request.Port = d.Get("port").(string)
request.RegionId = client.RegionId
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.AllocateInstancePublicConnection(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_kvstore_connection", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
d.SetId(fmt.Sprintf("%v", request.InstanceId))
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutCreate), 30*time.Second, r_kvstoreService.KvstoreInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudKvstoreConnectionUpdate(d, meta)
}
func resourceAlicloudKvstoreConnectionRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
r_kvstoreService := R_kvstoreService{client}
object, err := r_kvstoreService.DescribeKvstoreConnection(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_kvstore_connection r_kvstoreService.DescribeKvstoreConnection Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_id", d.Id())
for _, instanceNetInfo := range object {
if instanceNetInfo.DBInstanceNetType == "0" {
d.Set("connection_string", instanceNetInfo.ConnectionString)
d.Set("port", instanceNetInfo.Port)
}
}
return nil
}
func resourceAlicloudKvstoreConnectionUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
r_kvstoreService := R_kvstoreService{client}
update := false
request := r_kvstore.CreateModifyDBInstanceConnectionStringRequest()
request.DBInstanceId = d.Id()
request.CurrentConnectionString = d.Get("connection_string").(string)
if !d.IsNewResource() && d.HasChange("connection_string_prefix") {
update = true
}
request.NewConnectionString = d.Get("connection_string_prefix").(string)
request.IPType = "Public"
if !d.IsNewResource() && d.HasChange("port") {
update = true
request.Port = d.Get("port").(string)
}
if update {
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.ModifyDBInstanceConnectionString(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutUpdate), 30*time.Second, r_kvstoreService.KvstoreInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudKvstoreConnectionRead(d, meta)
}
func resourceAlicloudKvstoreConnectionDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
r_kvstoreService := R_kvstoreService{client}
request := r_kvstore.CreateReleaseInstancePublicConnectionRequest()
request.InstanceId = d.Id()
request.CurrentConnectionString = d.Get("connection_string").(string)
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.ReleaseInstancePublicConnection(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidInstanceId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutDelete), 30*time.Second, r_kvstoreService.KvstoreInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"encoding/json"
"fmt"
"log"
"strconv"
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
r_kvstore "github.com/aliyun/alibaba-cloud-sdk-go/services/r-kvstore"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/hashcode"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudKvstoreInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudKvstoreInstanceCreate,
Read: resourceAlicloudKvstoreInstanceRead,
Update: resourceAlicloudKvstoreInstanceUpdate,
Delete: resourceAlicloudKvstoreInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(11 * time.Minute),
Update: schema.DefaultTimeout(40 * time.Minute),
},
Schema: map[string]*schema.Schema{
"auto_renew": {
Type: schema.TypeBool,
Optional: true,
Default: false,
DiffSuppressFunc: redisPostPaidDiffSuppressFunc,
},
"auto_renew_period": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
ValidateFunc: validation.IntBetween(1, 12),
DiffSuppressFunc: redisPostPaidAndRenewDiffSuppressFunc,
},
"auto_use_coupon": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: false,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return !d.IsNewResource()
},
},
"backup_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"backup_period": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"backup_time": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"bandwidth": {
Type: schema.TypeInt,
Computed: true,
},
"business_info": {
Type: schema.TypeString,
Optional: true,
},
"capacity": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ForceNew: true,
},
"config": {
Type: schema.TypeMap,
Optional: true,
ConflictsWith: []string{"parameters"},
},
"connection_domain": {
Type: schema.TypeString,
Computed: true,
},
"coupon_no": {
Type: schema.TypeString,
Optional: true,
Default: "youhuiquan_promotion_option_id_for_blank",
},
"db_instance_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"instance_name"},
},
"instance_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Field 'instance_name' has been deprecated from version 1.101.0. Use 'db_instance_name' instead.",
ConflictsWith: []string{"db_instance_name"},
},
"dedicated_host_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"enable_backup_log": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{0, 1}),
Default: 0,
},
"end_time": {
Type: schema.TypeString,
Computed: true,
},
"engine_version": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"2.8", "4.0", "5.0", "6.0"}, false),
Default: "5.0",
},
"force_upgrade": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"global_instance": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: false,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return !d.IsNewResource()
},
},
"global_instance_id": {
Type: schema.TypeString,
Optional: true,
},
"instance_class": {
Type: schema.TypeString,
Optional: true,
},
"instance_release_protection": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"instance_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Memcache", "Redis"}, false),
Default: "Redis",
},
"maintain_end_time": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"maintain_start_time": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"modify_mode": {
Type: schema.TypeInt,
Optional: true,
Default: 0,
},
"node_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"MASTER_SLAVE", "STAND_ALONE", "double", "single"}, false),
Deprecated: "Field 'node_type' has been deprecated from version 1.120.1",
},
"order_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"UPGRADE", "DOWNGRADE"}, false),
Default: "UPGRADE",
},
"password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"payment_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"PostPaid", "PrePaid"}, false),
ConflictsWith: []string{"instance_charge_type"},
},
"instance_charge_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"PostPaid", "PrePaid"}, false),
Deprecated: "Field 'instance_charge_type' has been deprecated from version 1.101.0. Use 'payment_type' instead.",
ConflictsWith: []string{"payment_type"},
},
"period": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"1", "12", "2", "24", "3", "36", "4", "5", "6", "7", "8", "9"}, false),
},
"port": {
Type: schema.TypeInt,
Optional: true,
},
"private_connection_prefix": {
Type: schema.TypeString,
Optional: true,
},
"private_connection_port": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"private_ip": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"qps": {
Type: schema.TypeInt,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"restore_time": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ssl_enable": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Disable", "Enable", "Update"}, false),
},
"secondary_zone_id": {
Type: schema.TypeString,
Optional: true,
},
"security_group_id": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: redisSecurityGroupIdDiffSuppressFunc,
},
"security_ip_group_attribute": {
Type: schema.TypeString,
Optional: true,
},
"security_ip_group_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"security_ips": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"srcdb_instance_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
},
"vpc_auth_mode": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Close", "Open"}, false),
Default: "Open",
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"availability_zone"},
},
"availability_zone": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Field 'availability_zone' has been deprecated from version 1.101.0. Use 'zone_id' instead.",
ConflictsWith: []string{"zone_id"},
},
"kms_encrypted_password": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: kmsDiffSuppressFunc,
},
"kms_encryption_context": {
Type: schema.TypeMap,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("kms_encrypted_password").(string) == ""
},
Elem: schema.TypeString,
},
"enable_public": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
Deprecated: "Field 'enable_public' has been deprecated from version 1.101.0. Please use resource 'alicloud_kvstore_connection' instead.",
},
"connection_string_prefix": {
Type: schema.TypeString,
Optional: true,
Deprecated: "Field 'connection_string_prefix' has been deprecated from version 1.101.0. Please use resource 'alicloud_kvstore_connection' instead.",
},
"connection_string": {
Type: schema.TypeString,
Computed: true,
Deprecated: "Field 'connection_string' has been deprecated from version 1.101.0. Please use resource 'alicloud_kvstore_connection' instead.",
},
"parameters": {
Type: schema.TypeSet,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"value": {
Type: schema.TypeString,
Required: true,
},
},
},
Set: func(v interface{}) int {
return hashcode.String(
v.(map[string]interface{})["name"].(string) + "|" + v.(map[string]interface{})["value"].(string))
},
Optional: true,
Computed: true,
Deprecated: "Field 'parameters' has been deprecated from version 1.101.0. Use 'config' instead.",
ConflictsWith: []string{"config"},
},
},
}
}
func resourceAlicloudKvstoreInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
r_kvstoreService := R_kvstoreService{client}
request := r_kvstore.CreateCreateInstanceRequest()
request.RegionId = client.RegionId
if v, ok := d.GetOkExists("auto_renew"); ok {
request.AutoRenew = convertBoolToString(v.(bool))
}
if v, ok := d.GetOk("auto_renew_period"); ok {
request.AutoRenewPeriod = convertIntergerToString(v.(int))
}
if v, ok := d.GetOkExists("auto_use_coupon"); ok {
request.AutoUseCoupon = convertBoolToString(v.(bool))
}
if v, ok := d.GetOk("backup_id"); ok {
request.BackupId = v.(string)
}
if v, ok := d.GetOk("business_info"); ok {
request.BusinessInfo = v.(string)
}
if v, ok := d.GetOk("capacity"); ok {
request.Capacity = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("coupon_no"); ok {
request.CouponNo = v.(string)
}
if v, ok := d.GetOk("db_instance_name"); ok {
request.InstanceName = v.(string)
} else if v, ok := d.GetOk("instance_name"); ok {
request.InstanceName = v.(string)
}
if v, ok := d.GetOk("dedicated_host_group_id"); ok {
request.DedicatedHostGroupId = v.(string)
}
if v, ok := d.GetOkExists("dry_run"); ok {
request.DryRun = requests.NewBoolean(v.(bool))
}
if v, ok := d.GetOk("engine_version"); ok {
request.EngineVersion = v.(string)
}
if v, ok := d.GetOkExists("global_instance"); ok {
request.GlobalInstance = requests.NewBoolean(v.(bool))
}
if v, ok := d.GetOk("global_instance_id"); ok {
request.GlobalInstanceId = v.(string)
}
if v, ok := d.GetOk("instance_class"); ok {
request.InstanceClass = v.(string)
}
if v, ok := d.GetOk("instance_type"); ok {
request.InstanceType = v.(string)
}
request.NetworkType = "CLASSIC"
if v, ok := d.GetOk("node_type"); ok {
request.NodeType = v.(string)
}
request.Password = d.Get("password").(string)
if request.Password == "" {
if v := d.Get("kms_encrypted_password").(string); v != "" {
kmsService := KmsService{client}
decryptResp, err := kmsService.Decrypt(v, d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request.Password = decryptResp
}
}
if v, ok := d.GetOk("payment_type"); ok {
request.ChargeType = v.(string)
} else if v, ok := d.GetOk("instance_charge_type"); ok {
request.ChargeType = v.(string)
}
if v, ok := d.GetOk("period"); ok {
request.Period = v.(string)
}
if v, ok := d.GetOk("private_ip"); ok {
request.PrivateIpAddress = v.(string)
}
if v, ok := d.GetOk("resource_group_id"); ok {
request.ResourceGroupId = v.(string)
}
if v, ok := d.GetOk("restore_time"); ok {
request.RestoreTime = v.(string)
}
if v, ok := d.GetOk("srcdb_instance_id"); ok {
request.SrcDBInstanceId = v.(string)
}
if v, ok := d.GetOk("zone_id"); ok {
request.ZoneId = v.(string)
} else if v, ok := d.GetOk("availability_zone"); ok {
request.ZoneId = v.(string)
}
if v, ok := d.GetOk("secondary_zone_id"); ok {
request.SecondaryZoneId = v.(string)
}
vswitchId := Trim(d.Get("vswitch_id").(string))
if vswitchId != "" {
vpcService := VpcService{client}
vsw, err := vpcService.DescribeVSwitch(vswitchId)
if err != nil {
return WrapError(err)
}
request.NetworkType = "VPC"
request.VpcId = vsw.VpcId
request.VSwitchId = vswitchId
if request.ZoneId == "" {
request.ZoneId = vsw.ZoneId
}
}
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.CreateInstance(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_kvstore_instance", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ := raw.(*r_kvstore.CreateInstanceResponse)
d.SetId(fmt.Sprintf("%v", response.InstanceId))
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutCreate), 300*time.Second, r_kvstoreService.KvstoreInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudKvstoreInstanceUpdate(d, meta)
}
func resourceAlicloudKvstoreInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
r_kvstoreService := R_kvstoreService{client}
object, err := r_kvstoreService.DescribeKvstoreInstance(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_kvstore_instance r_kvstoreService.DescribeKvstoreInstance Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("enable_public", false)
d.Set("connection_string", "")
net, _ := r_kvstoreService.DescribeKvstoreConnection(d.Id())
for _, instanceNetInfo := range net {
if instanceNetInfo.DBInstanceNetType == "0" {
d.Set("enable_public", true)
d.Set("connection_string", instanceNetInfo.ConnectionString)
}
if instanceNetInfo.DBInstanceNetType == "2" {
d.Set("private_connection_port", instanceNetInfo.Port)
}
}
d.Set("bandwidth", object.Bandwidth)
d.Set("capacity", object.Capacity)
d.Set("config", object.Config)
d.Set("connection_domain", object.ConnectionDomain)
d.Set("db_instance_name", object.InstanceName)
d.Set("instance_name", object.InstanceName)
d.Set("end_time", object.EndTime)
d.Set("engine_version", object.EngineVersion)
d.Set("instance_class", object.InstanceClass)
d.Set("instance_release_protection", object.InstanceReleaseProtection)
d.Set("instance_type", object.InstanceType)
d.Set("maintain_end_time", object.MaintainEndTime)
d.Set("maintain_start_time", object.MaintainStartTime)
d.Set("node_type", object.NodeType)
d.Set("payment_type", object.ChargeType)
d.Set("instance_charge_type", object.ChargeType)
d.Set("private_ip", object.PrivateIp)
d.Set("qps", object.QPS)
d.Set("resource_group_id", object.ResourceGroupId)
d.Set("status", object.InstanceStatus)
tags := make(map[string]string)
for _, t := range object.Tags.Tag {
if !ignoredTags(t.Key, t.Value) {
tags[t.Key] = t.Value
}
}
d.Set("tags", tags)
d.Set("vswitch_id", object.VSwitchId)
d.Set("vpc_auth_mode", object.VpcAuthMode)
d.Set("zone_id", object.ZoneId)
d.Set("availability_zone", object.ZoneId)
d.Set("secondary_zone_id", object.SecondaryZoneId)
describeBackupPolicyObject, err := r_kvstoreService.DescribeBackupPolicy(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("backup_period", strings.Split(describeBackupPolicyObject.PreferredBackupPeriod, ","))
d.Set("backup_time", describeBackupPolicyObject.PreferredBackupTime)
if _, ok := d.GetOk("security_group_id"); ok {
describeSecurityGroupConfigurationObject, err := r_kvstoreService.DescribeSecurityGroupConfiguration(d.Id())
if err != nil {
return WrapError(err)
}
sgs := make([]string, 0)
for _, sg := range describeSecurityGroupConfigurationObject.EcsSecurityGroupRelation {
sgs = append(sgs, sg.SecurityGroupId)
}
d.Set("security_group_id", strings.Join(sgs, ","))
}
if _, ok := d.GetOk("ssl_enable"); ok {
describeInstanceSSLObject, err := r_kvstoreService.DescribeInstanceSSL(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("ssl_enable", describeInstanceSSLObject.SSLEnabled)
}
if _, ok := d.GetOk("security_ips"); ok {
describeSecurityIpsObject, err := r_kvstoreService.DescribeSecurityIps(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("security_ip_group_attribute", describeSecurityIpsObject.SecurityIpGroupAttribute)
d.Set("security_ip_group_name", describeSecurityIpsObject.SecurityIpGroupName)
d.Set("security_ips", strings.Split(describeSecurityIpsObject.SecurityIpList, ","))
}
if object.ChargeType == string(PrePaid) {
describeInstanceAutoRenewalAttributeObject, err := r_kvstoreService.DescribeInstanceAutoRenewalAttribute(d.Id())
if err != nil {
return WrapError(err)
}
autoRenew, err := strconv.ParseBool(describeInstanceAutoRenewalAttributeObject.AutoRenew)
if err != nil {
// invalid request response
return WrapError(err)
}
d.Set("auto_renew", autoRenew)
d.Set("auto_renew_period", describeInstanceAutoRenewalAttributeObject.Duration)
}
//refresh parameters
if err = refreshParameters(d, meta); err != nil {
return WrapError(err)
}
return nil
}
func resourceAlicloudKvstoreInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
r_kvstoreService := R_kvstoreService{client}
d.Partial(true)
if d.HasChange("payment_type") {
object, err := r_kvstoreService.DescribeKvstoreInstance(d.Id())
if err != nil {
return WrapError(err)
}
target := d.Get("payment_type").(string)
if object.ChargeType != target {
if target == "PrePaid" {
request := r_kvstore.CreateTransformToPrePaidRequest()
request.InstanceId = d.Id()
if v, ok := d.GetOk("period"); ok {
if v, err := strconv.Atoi(v.(string)); err == nil {
request.Period = requests.NewInteger(v)
} else {
return WrapError(err)
}
}
if v, ok := d.GetOk("auto_renew"); ok {
request.AutoPay = requests.NewBoolean(v.(bool))
}
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.TransformToPrePaid(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutUpdate), 60*time.Second, r_kvstoreService.KvstoreInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.SetPartial("payment_type")
}
}
if d.HasChange("tags") {
if err := r_kvstoreService.SetResourceTags(d, "INSTANCE"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
if d.HasChange("config") {
request := r_kvstore.CreateModifyInstanceConfigRequest()
request.InstanceId = d.Id()
respJson, err := convertMaptoJsonString(d.Get("config").(map[string]interface{}))
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_kvstore_instance", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
request.Config = respJson
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.ModifyInstanceConfig(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutUpdate), 120*time.Second, r_kvstoreService.KvstoreInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("config")
}
if d.HasChange("vpc_auth_mode") && d.Get("vswitch_id") != "" {
request := r_kvstore.CreateModifyInstanceVpcAuthModeRequest()
request.InstanceId = d.Id()
request.VpcAuthMode = d.Get("vpc_auth_mode").(string)
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.ModifyInstanceVpcAuthMode(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutUpdate), 120*time.Second, r_kvstoreService.KvstoreInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("vpc_auth_mode")
}
if d.HasChange("security_group_id") {
request := r_kvstore.CreateModifySecurityGroupConfigurationRequest()
request.DBInstanceId = d.Id()
request.SecurityGroupId = d.Get("security_group_id").(string)
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.ModifySecurityGroupConfiguration(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutUpdate), 120*time.Second, r_kvstoreService.KvstoreInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("security_group_id")
}
update := false
request := r_kvstore.CreateModifyInstanceAutoRenewalAttributeRequest()
request.DBInstanceId = d.Id()
if !d.IsNewResource() && d.HasChange("auto_renew") {
update = true
request.AutoRenew = convertBoolToString(d.Get("auto_renew").(bool))
}
if !d.IsNewResource() && d.HasChange("auto_renew_period") {
update = true
request.Duration = convertIntergerToString(d.Get("auto_renew_period").(int))
}
if update {
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.ModifyInstanceAutoRenewalAttribute(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("auto_renew")
d.SetPartial("auto_renew_period")
}
update = false
modifyInstanceMaintainTimeReq := r_kvstore.CreateModifyInstanceMaintainTimeRequest()
modifyInstanceMaintainTimeReq.InstanceId = d.Id()
if d.HasChange("maintain_end_time") {
update = true
}
modifyInstanceMaintainTimeReq.MaintainEndTime = d.Get("maintain_end_time").(string)
if d.HasChange("maintain_start_time") {
update = true
}
modifyInstanceMaintainTimeReq.MaintainStartTime = d.Get("maintain_start_time").(string)
if update {
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.ModifyInstanceMaintainTime(modifyInstanceMaintainTimeReq)
})
addDebug(modifyInstanceMaintainTimeReq.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), modifyInstanceMaintainTimeReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("maintain_end_time")
d.SetPartial("maintain_start_time")
}
update = false
modifyInstanceMajorVersionReq := r_kvstore.CreateModifyInstanceMajorVersionRequest()
modifyInstanceMajorVersionReq.InstanceId = d.Id()
if !d.IsNewResource() && d.HasChange("engine_version") {
update = true
}
modifyInstanceMajorVersionReq.MajorVersion = d.Get("engine_version").(string)
modifyInstanceMajorVersionReq.EffectiveTime = "0"
if update {
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.ModifyInstanceMajorVersion(modifyInstanceMajorVersionReq)
})
addDebug(modifyInstanceMajorVersionReq.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), modifyInstanceMajorVersionReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutUpdate), 300*time.Second, r_kvstoreService.KvstoreInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("engine_version")
}
if d.HasChange("ssl_enable") {
request := r_kvstore.CreateModifyInstanceSSLRequest()
request.InstanceId = d.Id()
request.SSLEnabled = d.Get("ssl_enable").(string)
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.ModifyInstanceSSL(request)
})
addDebug(request.GetActionName(), raw)
if err != nil && !IsExpectedErrors(err, []string{"SSLDisableStateExistsFault"}) {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutUpdate), 60*time.Second, r_kvstoreService.KvstoreInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("ssl_enable")
}
if !d.IsNewResource() && d.HasChange("resource_group_id") {
request := r_kvstore.CreateModifyResourceGroupRequest()
request.InstanceId = d.Id()
request.RegionId = client.RegionId
request.ResourceGroupId = d.Get("resource_group_id").(string)
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.ModifyResourceGroup(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutUpdate), 60*time.Second, r_kvstoreService.KvstoreInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("resource_group_id")
}
update = false
migrateToOtherZoneReq := r_kvstore.CreateMigrateToOtherZoneRequest()
migrateToOtherZoneReq.DBInstanceId = d.Id()
if !d.IsNewResource() && (d.HasChange("zone_id") || d.HasChange("availability_zone")) {
update = true
}
if v, ok := d.GetOk("zone_id"); ok {
migrateToOtherZoneReq.ZoneId = v.(string)
} else {
migrateToOtherZoneReq.ZoneId = d.Get("availability_zone").(string)
}
migrateToOtherZoneReq.EffectiveTime = "0"
if !d.IsNewResource() && d.HasChange("vswitch_id") {
update = true
migrateToOtherZoneReq.VSwitchId = d.Get("vswitch_id").(string)
}
if !d.IsNewResource() && d.HasChange("secondary_zone_id") {
update = true
migrateToOtherZoneReq.SecondaryZoneId = d.Get("secondary_zone_id").(string)
}
if update {
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.MigrateToOtherZone(migrateToOtherZoneReq)
})
addDebug(migrateToOtherZoneReq.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), migrateToOtherZoneReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutUpdate), 300*time.Second, r_kvstoreService.KvstoreInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("availability_zone")
d.SetPartial("zone_id")
d.SetPartial("vswitch_id")
}
update = false
modifyBackupPolicyReq := r_kvstore.CreateModifyBackupPolicyRequest()
modifyBackupPolicyReq.InstanceId = d.Id()
if d.HasChange("backup_period") {
update = true
}
modifyBackupPolicyReq.PreferredBackupPeriod = convertListToCommaSeparate(d.Get("backup_period").(*schema.Set).List())
if d.HasChange("backup_time") {
update = true
}
modifyBackupPolicyReq.PreferredBackupTime = d.Get("backup_time").(string)
if update {
if _, ok := d.GetOk("enable_backup_log"); ok {
modifyBackupPolicyReq.EnableBackupLog = requests.NewInteger(d.Get("enable_backup_log").(int))
}
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.ModifyBackupPolicy(modifyBackupPolicyReq)
})
addDebug(modifyBackupPolicyReq.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), modifyBackupPolicyReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutUpdate), 60*time.Second, r_kvstoreService.KvstoreInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("backup_period")
d.SetPartial("backup_time")
}
update = false
modifyInstanceAttributeReq := r_kvstore.CreateModifyInstanceAttributeRequest()
modifyInstanceAttributeReq.InstanceId = d.Id()
if !d.IsNewResource() && d.HasChange("db_instance_name") {
update = true
modifyInstanceAttributeReq.InstanceName = d.Get("db_instance_name").(string)
}
if !d.IsNewResource() && d.HasChange("instance_name") {
update = true
modifyInstanceAttributeReq.InstanceName = d.Get("instance_name").(string)
}
if d.HasChange("instance_release_protection") {
update = true
modifyInstanceAttributeReq.InstanceReleaseProtection = requests.NewBoolean(d.Get("instance_release_protection").(bool))
}
if !d.IsNewResource() && (d.HasChange("password") || d.HasChange("kms_encrypted_password")) {
update = true
password := d.Get("password").(string)
kmsPassword := d.Get("kms_encrypted_password").(string)
if password == "" && kmsPassword == "" {
return WrapError(Error("One of the 'password' and 'kms_encrypted_password' should be set."))
}
if password != "" {
modifyInstanceAttributeReq.NewPassword = password
} else {
kmsService := KmsService{meta.(*connectivity.AliyunClient)}
decryptResp, err := kmsService.Decrypt(kmsPassword, d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return WrapError(err)
}
modifyInstanceAttributeReq.NewPassword = decryptResp
}
}
if update {
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.ModifyInstanceAttribute(modifyInstanceAttributeReq)
})
addDebug(modifyInstanceAttributeReq.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), modifyInstanceAttributeReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutUpdate), 120*time.Second, r_kvstoreService.KvstoreInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("instance_name")
d.SetPartial("db_instance_name")
d.SetPartial("instance_release_protection")
d.SetPartial("kms_encrypted_password")
d.SetPartial("kms_encryption_context")
d.SetPartial("password")
}
update = false
modifyDBInstanceConnectionStringReq := r_kvstore.CreateModifyDBInstanceConnectionStringRequest()
modifyDBInstanceConnectionStringReq.DBInstanceId = d.Id()
if d.HasChange("private_connection_prefix") {
update = true
modifyDBInstanceConnectionStringReq.NewConnectionString = d.Get("private_connection_prefix").(string)
}
if d.HasChange("private_connection_port") {
update = true
modifyDBInstanceConnectionStringReq.Port = d.Get("private_connection_port").(string)
}
modifyDBInstanceConnectionStringReq.IPType = "Private"
if update {
object, err := r_kvstoreService.DescribeKvstoreInstance(d.Id())
modifyDBInstanceConnectionStringReq.CurrentConnectionString = object.ConnectionDomain
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.ModifyDBInstanceConnectionString(modifyDBInstanceConnectionStringReq)
})
addDebug(modifyDBInstanceConnectionStringReq.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), modifyDBInstanceConnectionStringReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutUpdate), 60*time.Second, r_kvstoreService.KvstoreInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("private_connection_prefix")
d.SetPartial("private_connection_port")
}
update = false
modifySecurityIpsReq := r_kvstore.CreateModifySecurityIpsRequest()
modifySecurityIpsReq.InstanceId = d.Id()
if d.HasChange("security_ips") {
update = true
}
modifySecurityIpsReq.SecurityIps = convertListToCommaSeparate(d.Get("security_ips").(*schema.Set).List())
if d.HasChange("security_ip_group_attribute") {
update = true
modifySecurityIpsReq.SecurityIpGroupAttribute = d.Get("security_ip_group_attribute").(string)
}
if d.HasChange("security_ip_group_name") {
update = true
modifySecurityIpsReq.SecurityIpGroupName = d.Get("security_ip_group_name").(string)
}
if update {
if _, ok := d.GetOk("modify_mode"); ok {
modifySecurityIpsReq.ModifyMode = convertModifyModeRequest(d.Get("modify_mode").(int))
}
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.ModifySecurityIps(modifySecurityIpsReq)
})
addDebug(modifySecurityIpsReq.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), modifySecurityIpsReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutUpdate), 1*time.Second, r_kvstoreService.KvstoreInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("security_ips")
d.SetPartial("security_ip_group_attribute")
d.SetPartial("security_ip_group_name")
}
update = false
modifyInstanceSpecReq := r_kvstore.CreateModifyInstanceSpecRequest()
modifyInstanceSpecReq.InstanceId = d.Id()
modifyInstanceSpecReq.AutoPay = requests.NewBoolean(true)
modifyInstanceSpecReq.EffectiveTime = "0"
if !d.IsNewResource() && d.HasChange("engine_version") {
modifyInstanceSpecReq.MajorVersion = d.Get("engine_version").(string)
}
if !d.IsNewResource() && d.HasChange("instance_class") {
update = true
modifyInstanceSpecReq.InstanceClass = d.Get("instance_class").(string)
}
if update {
if _, ok := d.GetOk("business_info"); ok {
modifyInstanceSpecReq.BusinessInfo = d.Get("business_info").(string)
}
if _, ok := d.GetOk("coupon_no"); ok {
modifyInstanceSpecReq.CouponNo = d.Get("coupon_no").(string)
}
if _, ok := d.GetOkExists("force_upgrade"); ok {
modifyInstanceSpecReq.ForceUpgrade = requests.NewBoolean(d.Get("force_upgrade").(bool))
}
if _, ok := d.GetOk("order_type"); ok {
modifyInstanceSpecReq.OrderType = d.Get("order_type").(string)
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err := resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
modifyInstanceSpecReq.ClientToken = buildClientToken(modifyInstanceSpecReq.GetActionName())
args := *modifyInstanceSpecReq
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.ModifyInstanceSpec(&args)
})
if err != nil {
if IsExpectedErrors(err, []string{"MissingRedisUsedmemoryUnsupportPerfItem"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), modifyInstanceSpecReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutUpdate), 360*time.Second, r_kvstoreService.KvstoreInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("engine_version")
d.SetPartial("instance_class")
}
if d.HasChange("parameters") {
request := r_kvstore.CreateModifyInstanceConfigRequest()
request.InstanceId = d.Id()
config := make(map[string]interface{})
documented := d.Get("parameters").(*schema.Set).List()
if len(documented) > 0 {
for _, i := range documented {
key := i.(map[string]interface{})["name"].(string)
value := i.(map[string]interface{})["value"]
config[key] = value
}
cfg, _ := convertMaptoJsonString(config)
request.Config = cfg
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.ModifyInstanceConfig(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutUpdate), 120*time.Second, r_kvstoreService.KvstoreInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.SetPartial("parameters")
}
if d.HasChange("enable_public") {
prefix := d.Get("connection_string_prefix").(string)
port := fmt.Sprintf("%s", d.Get("port"))
target := d.Get("enable_public").(bool)
if target {
request := r_kvstore.CreateAllocateInstancePublicConnectionRequest()
request.InstanceId = d.Id()
request.ConnectionStringPrefix = prefix
request.Port = port
raw, err := client.WithRkvClient(func(client *r_kvstore.Client) (interface{}, error) {
return client.AllocateInstancePublicConnection(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutUpdate), 120*time.Second, r_kvstoreService.KvstoreInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if !target && d.Get("connection_string") != "" {
request := r_kvstore.CreateReleaseInstancePublicConnectionRequest()
request.InstanceId = d.Id()
request.CurrentConnectionString = d.Get("connection_string").(string)
raw, err := client.WithRkvClient(func(client *r_kvstore.Client) (interface{}, error) {
return client.ReleaseInstancePublicConnection(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutUpdate), 120*time.Second, r_kvstoreService.KvstoreInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.SetPartial("enable_public")
}
d.Partial(false)
return resourceAlicloudKvstoreInstanceRead(d, meta)
}
func resourceAlicloudKvstoreInstanceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := r_kvstore.CreateDeleteInstanceRequest()
request.InstanceId = d.Id()
request.RegionId = client.RegionId
if v, ok := d.GetOk("global_instance_id"); ok {
request.GlobalInstanceId = v.(string)
}
raw, err := client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.DeleteInstance(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidInstanceId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return nil
}
func convertModifyModeRequest(input int) string {
switch input {
case 0:
return "Cover"
case 1:
return "Append"
case 2:
return "Delete"
}
return ""
}
func refreshParameters(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
r_kvstoreService := R_kvstoreService{client}
var param []map[string]interface{}
_, ok := d.GetOk("parameters")
if !ok {
d.Set("parameters", param)
return nil
}
object, err := r_kvstoreService.DescribeKvstoreInstance(d.Id())
if err != nil {
return WrapError(err)
}
m := make(map[string]interface{})
err = json.Unmarshal([]byte(object.Config), &m)
if err != nil {
return WrapError(err)
}
for k, v := range m {
parameter := map[string]interface{}{
"name": k,
"value": v,
}
param = append(param, parameter)
}
d.Set("parameters", param)
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudLindormInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudLindormInstanceCreate,
Read: resourceAlicloudLindormInstanceRead,
Update: resourceAlicloudLindormInstanceUpdate,
Delete: resourceAlicloudLindormInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
Update: schema.DefaultTimeout(30 * time.Minute),
},
Schema: map[string]*schema.Schema{
"cold_storage": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.Any(validation.IntInSlice([]int{0}), validation.IntBetween(800, 100000)),
},
"core_num": {
Type: schema.TypeInt,
Optional: true,
},
"core_spec": {
Type: schema.TypeString,
Optional: true,
},
"deletion_proection": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"disk_category": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"capacity_cloud_storage", "cloud_efficiency", "cloud_essd", "cloud_ssd"}, false),
},
"duration": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.IntBetween(1, 9),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("payment_type").(string) != "Subscription"
},
},
"file_engine_node_count": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntAtLeast(2),
},
"file_engine_specification": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"lindorm.c.xlarge"}, false),
},
"group_name": {
Type: schema.TypeString,
Optional: true,
},
"instance_name": {
Type: schema.TypeString,
Optional: true,
},
"instance_storage": {
Type: schema.TypeString,
Optional: true,
},
"ip_white_list": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"lts_node_count": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"lts_node_specification": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"lindorm.g.2xlarge", "lindorm.g.xlarge"}, false),
},
"payment_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo", "Subscription"}, false),
},
"phoenix_node_count": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"phoenix_node_specification": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"lindorm.c.2xlarge", "lindorm.c.4xlarge", "lindorm.c.8xlarge", "lindorm.c.xlarge", "lindorm.g.2xlarge", "lindorm.g.4xlarge", "lindorm.g.8xlarge", "lindorm.g.xlarge"}, false),
},
"pricing_cycle": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Month", "Year"}, false),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("payment_type").(string) != "Subscription"
},
},
"search_engine_node_count": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntAtLeast(2),
},
"search_engine_specification": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"lindorm.g.2xlarge", "lindorm.g.4xlarge", "lindorm.g.8xlarge", "lindorm.g.xlarge"}, false),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"table_engine_node_count": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntAtLeast(2),
},
"table_engine_specification": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"lindorm.c.2xlarge", "lindorm.c.4xlarge", "lindorm.c.8xlarge", "lindorm.c.xlarge", "lindorm.g.2xlarge", "lindorm.g.4xlarge", "lindorm.g.8xlarge", "lindorm.g.xlarge"}, false),
},
"time_series_engine_node_count": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntAtLeast(2),
},
"time_serires_engine_specification": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"lindorm.g.2xlarge", "lindorm.g.4xlarge", "lindorm.g.8xlarge", "lindorm.g.xlarge"}, false),
},
"upgrade_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"open-bds-transfer", "open-bds-transfer-only", "open-lindorm-engine", "open-phoenix-engine", "open-search-engine", "open-tsdb-engine", "upgrade-bds-core-num", "upgrade-bds-transfer", "upgrade-cold-storage", "upgrade-disk-size", "upgrade-file-core-num", "upgrade-file-engine", "upgrade-lindorm-core-num", "upgrade-lindorm-engine", "upgrade-phoenix-core-num", "upgrade-phoenix-engine", "upgrade-search-core-num", "upgrade-search-engine", "upgrade-tsdb-core-num", "upgrade-tsdb-engine"}, false),
},
"vswitch_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudLindormInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateLindormInstance"
request := make(map[string]interface{})
conn, err := client.NewHitsdbClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("cold_storage"); ok {
request["ColdStorage"] = v
}
if v, ok := d.GetOk("core_spec"); ok {
request["CoreSpec"] = v
}
request["DiskCategory"] = d.Get("disk_category")
if v, ok := d.GetOk("duration"); ok {
request["Duration"] = v
}
if v, ok := d.GetOk("file_engine_node_count"); ok {
request["FilestoreNum"] = v
}
if v, ok := d.GetOk("file_engine_specification"); ok {
request["FilestoreSpec"] = v
}
if v, ok := d.GetOk("instance_name"); ok {
request["InstanceAlias"] = v
}
if v, ok := d.GetOk("instance_storage"); ok {
request["InstanceStorage"] = v
}
request["PayType"] = convertLindormInstancePaymentTypeRequest(d.Get("payment_type").(string))
if v, ok := d.GetOk("pricing_cycle"); ok {
request["PricingCycle"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("search_engine_node_count"); ok {
request["SolrNum"] = v
}
if v, ok := d.GetOk("search_engine_specification"); ok {
request["SolrSpec"] = v
}
if v, ok := d.GetOk("table_engine_node_count"); ok {
request["LindormNum"] = v
}
if v, ok := d.GetOk("table_engine_specification"); ok {
request["LindormSpec"] = v
}
if v, ok := d.GetOk("time_series_engine_node_count"); ok {
request["TsdbNum"] = v
}
if v, ok := d.GetOk("time_serires_engine_specification"); ok {
request["TsdbSpec"] = v
}
if v, ok := d.GetOk("zone_id"); ok {
request["ZoneId"] = v
}
vswitchId := Trim(d.Get("vswitch_id").(string))
if vswitchId != "" {
vpcService := VpcService{client}
vsw, err := vpcService.DescribeVSwitchWithTeadsl(vswitchId)
if err != nil {
return WrapError(err)
}
request["VPCId"] = vsw["VpcId"]
request["VSwitchId"] = vswitchId
if v, ok := request["ZoneId"].(string); !ok || v == "" {
request["ZoneId"] = vsw["ZoneId"]
}
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_lindorm_instance", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["InstanceId"]))
hitsdbService := HitsdbService{client}
stateConf := BuildStateConf([]string{}, []string{"ACTIVATION"}, d.Timeout(schema.TimeoutCreate), 2*time.Minute, hitsdbService.LindormInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudLindormInstanceRead(d, meta)
}
func resourceAlicloudLindormInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
hitsdbService := HitsdbService{client}
object, err := hitsdbService.DescribeLindormInstance(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_lindorm_instance hitsdbService.DescribeLindormInstance Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
if v, ok := object["ColdStorage"]; ok {
d.Set("cold_storage", formatInt(v))
}
d.Set("deletion_proection", object["DeletionProtection"])
d.Set("disk_category", object["DiskCategory"])
d.Set("instance_name", object["InstanceAlias"])
d.Set("instance_storage", object["InstanceStorage"])
d.Set("payment_type", convertLindormInstancePaymentTypeResponse(object["PayType"]))
d.Set("status", object["InstanceStatus"])
d.Set("vswitch_id", object["VswitchId"])
d.Set("zone_id", object["ZoneId"])
ipWhite, err := hitsdbService.GetInstanceIpWhiteList(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("ip_white_list", ipWhite)
getLindormInstanceEngineInfoObject, err := hitsdbService.GetLindormInstanceEngineInfo(d.Id())
if err != nil {
return WrapError(err)
}
if v, ok := getLindormInstanceEngineInfoObject["FileEngineNodeCount"]; ok {
d.Set("file_engine_node_count", formatInt(v))
}
d.Set("file_engine_specification", getLindormInstanceEngineInfoObject["FileEngineSpecification"])
if v, ok := getLindormInstanceEngineInfoObject["LtsNodeCount"]; ok {
d.Set("lts_node_count", formatInt(v))
}
d.Set("lts_node_specification", getLindormInstanceEngineInfoObject["LtsNodeSpecification"])
if v, ok := getLindormInstanceEngineInfoObject["PhoenixNodeCount"]; ok {
d.Set("phoenix_node_count", formatInt(v))
}
d.Set("phoenix_node_specification", getLindormInstanceEngineInfoObject["PhoenixNodeSpecification"])
if v, ok := getLindormInstanceEngineInfoObject["SearchEngineNodeCount"]; ok {
d.Set("search_engine_node_count", formatInt(v))
}
d.Set("search_engine_specification", getLindormInstanceEngineInfoObject["SearchEngineSpecification"])
if v, ok := getLindormInstanceEngineInfoObject["TableEngineNodeCount"]; ok {
d.Set("table_engine_node_count", formatInt(v))
}
d.Set("table_engine_specification", getLindormInstanceEngineInfoObject["TableEngineSpecification"])
if v, ok := getLindormInstanceEngineInfoObject["TimeSeriesNodeCount"]; ok {
d.Set("time_series_engine_node_count", formatInt(v))
}
d.Set("time_serires_engine_specification", getLindormInstanceEngineInfoObject["TimeSeriesSpecification"])
return nil
}
func resourceAlicloudLindormInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
hitsdbService := HitsdbService{client}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"InstanceId": d.Id(),
}
if d.HasChange("ip_white_list") {
update = true
if v, ok := d.GetOk("ip_white_list"); ok && v != nil {
request["SecurityIpList"] = convertListToCommaSeparate(v.(*schema.Set).List())
}
}
if update {
if v, ok := d.GetOk("group_name"); ok {
request["GroupName"] = v
}
action := "UpdateInstanceIpWhiteList"
conn, err := client.NewHitsdbClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Instance.NotActive", "Lindorm.Errorcode.ParameterInvaild"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("ip_white_list")
}
update = false
updateLindormInstanceAttributeReq := map[string]interface{}{
"InstanceId": d.Id(),
}
if d.HasChange("instance_name") {
update = true
}
if v, ok := d.GetOk("instance_name"); ok {
updateLindormInstanceAttributeReq["InstanceAlias"] = v
}
if d.HasChange("deletion_proection") || d.IsNewResource() {
update = true
if v, ok := d.GetOkExists("deletion_proection"); ok {
updateLindormInstanceAttributeReq["DeletionProtection"] = v
}
}
if update {
action := "UpdateLindormInstanceAttribute"
conn, err := client.NewHitsdbClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-15"), StringPointer("AK"), nil, updateLindormInstanceAttributeReq, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Instance.NotActive", "Lindorm.Errorcode.ParameterInvaild"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, updateLindormInstanceAttributeReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("instance_name")
d.SetPartial("deletion_proection")
}
update = false
upgradeLindormInstanceReq := map[string]interface{}{
"InstanceId": d.Id(),
}
if d.HasChange("cold_storage") {
update = true
}
if v, ok := d.GetOk("cold_storage"); ok {
upgradeLindormInstanceReq["ColdStorage"] = v
}
if d.HasChange("instance_storage") {
update = true
}
if v, ok := d.GetOk("instance_storage"); ok {
upgradeLindormInstanceReq["ClusterStorage"] = v
}
upgradeLindormInstanceReq["RegionId"] = client.RegionId
if d.HasChange("table_engine_node_count") {
update = true
}
if v, ok := d.GetOk("table_engine_node_count"); ok {
upgradeLindormInstanceReq["LindormNum"] = v
}
upgradeLindormInstanceReq["ZoneId"] = d.Get("zone_id")
if d.HasChange("file_engine_node_count") {
update = true
if v, ok := d.GetOk("file_engine_node_count"); ok {
upgradeLindormInstanceReq["FilestoreSpec"] = v
}
}
if d.HasChange("file_engine_specification") {
update = true
if v, ok := d.GetOk("file_engine_specification"); ok {
upgradeLindormInstanceReq["FilestoreNum"] = v
}
}
if d.HasChange("lts_node_count") {
update = true
if v, ok := d.GetOk("lts_node_count"); ok {
upgradeLindormInstanceReq["LtsCoreNum"] = v
}
}
if d.HasChange("lts_node_specification") {
update = true
if v, ok := d.GetOk("lts_node_specification"); ok {
upgradeLindormInstanceReq["LtsCoreSpec"] = v
}
}
if d.HasChange("phoenix_node_count") {
update = true
if v, ok := d.GetOk("phoenix_node_count"); ok {
upgradeLindormInstanceReq["PhoenixCoreNum"] = v
}
}
if d.HasChange("phoenix_node_specification") {
update = true
if v, ok := d.GetOk("phoenix_node_specification"); ok {
upgradeLindormInstanceReq["PhoenixCoreSpec"] = v
}
}
if d.HasChange("search_engine_node_count") {
update = true
if v, ok := d.GetOk("search_engine_node_count"); ok {
upgradeLindormInstanceReq["SolrNum"] = v
}
}
if d.HasChange("search_engine_specification") {
update = true
if v, ok := d.GetOk("search_engine_specification"); ok {
upgradeLindormInstanceReq["SolrSpec"] = v
}
}
if d.HasChange("table_engine_specification") {
update = true
if v, ok := d.GetOk("table_engine_specification"); ok {
upgradeLindormInstanceReq["LindormSpec"] = v
}
}
if d.HasChange("time_series_engine_node_count") {
update = true
if v, ok := d.GetOk("time_series_engine_node_count"); ok {
upgradeLindormInstanceReq["TsdbNum"] = v
}
}
if d.HasChange("time_serires_engine_specification") {
update = true
if v, ok := d.GetOk("time_serires_engine_specification"); ok {
upgradeLindormInstanceReq["TsdbSpec"] = v
}
}
if update {
if v, ok := d.GetOk("upgrade_type"); ok {
upgradeLindormInstanceReq["UpgradeType"] = v
}
if v, ok := d.GetOk("core_num"); ok {
upgradeLindormInstanceReq["CoreNum"] = v
}
if v, ok := d.GetOk("core_spec"); ok {
upgradeLindormInstanceReq["CoreSpec"] = v
}
action := "UpgradeLindormInstance"
conn, err := client.NewHitsdbClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 30*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-15"), StringPointer("AK"), nil, upgradeLindormInstanceReq, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Instance.NotActive", "Lindorm.Errorcode.ParameterInvaild"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, upgradeLindormInstanceReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"ACTIVATION"}, d.Timeout(schema.TimeoutUpdate), 2*time.Minute, hitsdbService.LindormInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("cold_storage")
d.SetPartial("instance_storage")
d.SetPartial("table_engine_node_count")
d.SetPartial("zone_id")
d.SetPartial("file_engine_node_count")
d.SetPartial("file_engine_specification")
d.SetPartial("lts_node_count")
d.SetPartial("lts_node_specification")
d.SetPartial("phoenix_node_count")
d.SetPartial("phoenix_node_specification")
d.SetPartial("search_engine_node_count")
d.SetPartial("search_engine_specification")
d.SetPartial("table_engine_specification")
d.SetPartial("time_series_engine_node_count")
d.SetPartial("time_serires_engine_specification")
}
d.Partial(false)
return resourceAlicloudLindormInstanceRead(d, meta)
}
func resourceAlicloudLindormInstanceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "ReleaseLindormInstance"
var response map[string]interface{}
conn, err := client.NewHitsdbClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"InstanceId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Lindorm.Errorcode.InstanceNotFound", "Instance.IsDeleted"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func convertLindormInstancePaymentTypeRequest(source interface{}) interface{} {
switch source {
case "PayAsYouGo":
return "POSTPAY"
case "Subscription":
return "PREPAY"
}
return source
}
func convertLindormInstancePaymentTypeResponse(source interface{}) interface{} {
switch source {
case "POSTPAY":
return "PayAsYouGo"
case "PREPAY":
return "Subscription"
}
return source
}
package alicloud
import (
"fmt"
"time"
sls "github.com/aliyun/aliyun-log-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudLogAlert() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudLogAlertCreate,
Read: resourceAlicloudLogAlertRead,
Update: resourceAlicloudLogAlertUpdate,
Delete: resourceAlicloudLogAlertDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"project_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"alert_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"alert_displayname": {
Type: schema.TypeString,
Required: true,
},
"alert_description": {
Type: schema.TypeString,
Optional: true,
},
"condition": {
Type: schema.TypeString,
Required: true,
},
"dashboard": {
Type: schema.TypeString,
Required: true,
},
"mute_until": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntAtLeast(0),
Default: time.Now().Unix(),
},
"throttling": {
Type: schema.TypeString,
Optional: true,
},
"notify_threshold": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
},
"query_list": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"chart_title": {
Type: schema.TypeString,
Required: true,
},
"logstore": {
Type: schema.TypeString,
Required: true,
},
"query": {
Type: schema.TypeString,
Required: true,
},
"start": {
Type: schema.TypeString,
Required: true,
},
"end": {
Type: schema.TypeString,
Required: true,
},
"time_span_type": {
Type: schema.TypeString,
Optional: true,
Default: "Custom",
},
},
},
},
"notification_list": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
sls.NotificationTypeSMS,
sls.NotificationTypeDingTalk,
sls.NotificationTypeEmail,
sls.NotificationTypeMessageCenter},
false),
},
"content": {
Type: schema.TypeString,
Required: true,
},
"service_uri": {
Type: schema.TypeString,
Optional: true,
},
"mobile_list": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"email_list": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"schedule_interval": {
Type: schema.TypeString,
Optional: true,
Default: "60s",
},
"schedule_type": {
Type: schema.TypeString,
Optional: true,
Default: "FixedRate",
},
},
}
}
func resourceAlicloudLogAlertCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
project_name := d.Get("project_name").(string)
alert_name := d.Get("alert_name").(string)
alert_displayname := d.Get("alert_displayname").(string)
alert := &sls.Alert{
Name: alert_name,
DisplayName: alert_displayname,
Description: d.Get("alert_description").(string),
State: "Enabled",
Schedule: &sls.Schedule{
Type: d.Get("schedule_type").(string),
Interval: d.Get("schedule_interval").(string),
},
}
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
_, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
dashboard := d.Get("dashboard").(string)
err := CreateDashboard(project_name, dashboard, slsClient)
if err != nil {
return nil, err
}
alert.Configuration = createAlertConfig(d, project_name, dashboard, slsClient)
return nil, slsClient.CreateAlert(project_name, alert)
})
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout}) {
time.Sleep(5 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_log_alert", "CreateLogstoreAlert", AliyunLogGoSdkERROR)
}
d.SetId(fmt.Sprintf("%s%s%s", project_name, COLON_SEPARATED, alert_name))
return resourceAlicloudLogAlertRead(d, meta)
}
func resourceAlicloudLogAlertRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logService := LogService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
object, err := logService.DescribeLogAlert(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("project_name", parts[0])
d.Set("alert_name", parts[1])
d.Set("alert_displayname", object.DisplayName)
d.Set("alert_description", object.Description)
d.Set("condition", object.Configuration.Condition)
d.Set("dashboard", object.Configuration.Dashboard)
d.Set("mute_until", object.Configuration.MuteUntil)
d.Set("throttling", object.Configuration.Throttling)
d.Set("notify_threshold", object.Configuration.NotifyThreshold)
d.Set("schedule_interval", object.Schedule.Interval)
d.Set("schedule_type", object.Schedule.Type)
var notiList []map[string]interface{}
for _, v := range object.Configuration.NotificationList {
mapping := getNotiMap(v)
notiList = append(notiList, mapping)
}
var queryList []map[string]interface{}
for _, v := range object.Configuration.QueryList {
mapping := map[string]interface{}{
"chart_title": v.ChartTitle,
"logstore": v.LogStore,
"query": v.Query,
"start": v.Start,
"end": v.End,
"time_span_type": v.TimeSpanType,
}
queryList = append(queryList, mapping)
}
d.Set("notification_list", notiList)
d.Set("query_list", queryList)
return nil
}
func resourceAlicloudLogAlertUpdate(d *schema.ResourceData, meta interface{}) error {
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
client := meta.(*connectivity.AliyunClient)
params := &sls.Alert{
Name: parts[1],
DisplayName: d.Get("alert_displayname").(string),
Description: d.Get("alert_description").(string),
State: "Enabled",
Schedule: &sls.Schedule{
Type: d.Get("schedule_type").(string),
Interval: d.Get("schedule_interval").(string),
},
}
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
_, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
project_name := d.Get("project_name").(string)
dashboard := d.Get("dashboard").(string)
err := CreateDashboard(project_name, dashboard, slsClient)
if err != nil {
return nil, err
}
params.Configuration = createAlertConfig(d, project_name, dashboard, slsClient)
return nil, slsClient.UpdateAlert(parts[0], params)
})
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout}) {
time.Sleep(5 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "UpdateAlert", AliyunLogGoSdkERROR)
}
return resourceAlicloudLogAlertRead(d, meta)
}
func resourceAlicloudLogAlertDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logService := LogService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
var requestInfo *sls.Client
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return nil, slsClient.DeleteAlert(parts[0], parts[1])
})
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout}) {
time.Sleep(5 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if debugOn() {
addDebug("DeleteAlert", raw, requestInfo, map[string]interface{}{
"project_name": parts[0],
"alert": parts[1],
})
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_log_alert", "DeleteAlert", AliyunLogGoSdkERROR)
}
return WrapError(logService.WaitForLogstoreAlert(d.Id(), Deleted, DefaultTimeout))
}
func createAlertConfig(d *schema.ResourceData, project, dashboard string, client *sls.Client) *sls.AlertConfiguration {
noti := []*sls.Notification{}
if v, ok := d.GetOk("notification_list"); ok {
for _, e := range v.([]interface{}) {
noti_map := e.(map[string]interface{})
content := noti_map["content"].(string)
email_list := []string{}
email_list_temp := noti_map["email_list"].(*schema.Set).List()
for _, v := range email_list_temp {
new_v := v.(string)
email_list = append(email_list, new_v)
}
mobile_list_temp := noti_map["mobile_list"].(*schema.Set).List()
mobile_list := []string{}
if len(mobile_list_temp) > 0 {
for _, v := range mobile_list_temp {
new_v := v.(string)
mobile_list = append(mobile_list, new_v)
}
}
if noti_map["type"].(string) == sls.NotificationTypeEmail {
email := &sls.Notification{
Type: sls.NotificationTypeEmail,
EmailList: email_list,
Content: content,
}
noti = append(noti, email)
}
if noti_map["type"].(string) == sls.NotificationTypeSMS {
sms := &sls.Notification{
Type: sls.NotificationTypeSMS,
MobileList: mobile_list,
Content: content,
}
noti = append(noti, sms)
}
if noti_map["type"].(string) == sls.NotificationTypeDingTalk {
ding := &sls.Notification{
Type: sls.NotificationTypeDingTalk,
ServiceUri: noti_map["service_uri"].(string),
Content: content,
}
noti = append(noti, ding)
}
if noti_map["type"].(string) == sls.NotificationTypeMessageCenter {
messageCenter := &sls.Notification{
Type: sls.NotificationTypeMessageCenter,
Content: content,
}
noti = append(noti, messageCenter)
}
}
}
queryList := []*sls.AlertQuery{}
if v, ok := d.GetOk("query_list"); ok {
for _, e := range v.([]interface{}) {
query_map := e.(map[string]interface{})
query := &sls.AlertQuery{
ChartTitle: GetCharTitile(project, dashboard, query_map["chart_title"].(string), client),
LogStore: query_map["logstore"].(string),
Query: query_map["query"].(string),
Start: query_map["start"].(string),
End: query_map["end"].(string),
TimeSpanType: query_map["time_span_type"].(string),
}
queryList = append(queryList, query)
}
}
config := &sls.AlertConfiguration{
Condition: d.Get("condition").(string),
Dashboard: d.Get("dashboard").(string),
QueryList: queryList,
MuteUntil: int64(d.Get("mute_until").(int)),
NotificationList: noti,
Throttling: d.Get("throttling").(string),
NotifyThreshold: int32(d.Get("notify_threshold").(int)),
}
return config
}
func getNotiMap(v *sls.Notification) map[string]interface{} {
mapping := make(map[string]interface{})
mapping["content"] = v.Content
if v.Type == sls.NotificationTypeSMS {
mapping["type"] = sls.NotificationTypeSMS
mapping["mobile_list"] = v.MobileList
}
if v.Type == sls.NotificationTypeEmail {
mapping["type"] = sls.NotificationTypeEmail
mapping["email_list"] = v.EmailList
}
if v.Type == sls.NotificationTypeDingTalk {
mapping["type"] = sls.NotificationTypeDingTalk
mapping["service_uri"] = v.ServiceUri
}
if v.Type == sls.NotificationTypeMessageCenter {
mapping["type"] = sls.NotificationTypeMessageCenter
}
return mapping
}
package alicloud
import (
"encoding/json"
"fmt"
"log"
"strings"
"time"
slsPop "github.com/aliyun/alibaba-cloud-sdk-go/services/sls"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudLogAudit() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudLogAuditCreate,
Read: resourceAlicloudLogAuditRead,
Update: resourceAlicloudLogAuditUpdate,
Delete: resourceAlicloudLogAuditDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"display_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"aliuid": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"variable_map": {
Type: schema.TypeMap,
Optional: true,
},
"multi_account": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
},
"resource_directory_type": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"custom", "all"}, true),
Optional: true,
},
},
}
}
func resourceAlicloudLogAuditCreate(d *schema.ResourceData, meta interface{}) error {
d.SetId(d.Get("display_name").(string))
return resourceAlicloudLogAuditUpdate(d, meta)
}
func resourceAlicloudLogAuditUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := slsPop.CreateAnalyzeAppLogRequest()
request.AppType = "audit"
request.DisplayName = d.Id()
var variableMap = map[string]interface{}{}
mutiAccount := expandStringList(d.Get("multi_account").(*schema.Set).List())
if resourceDirectoryType, ok := d.GetOk("resource_directory_type"); ok {
resourceDirectoryMap := map[string]interface{}{}
resourceDirectoryMap["type"] = resourceDirectoryType
resourceDirectoryMap["multi_account"] = mutiAccount
data, err := json.Marshal(resourceDirectoryMap)
if err != nil {
return WrapError(err)
}
resultResourceDirectory := string(data)
variableMap["resource_directory"] = resultResourceDirectory
} else if len(mutiAccount) > 0 {
mutiAccountList := []map[string]string{}
for _, v := range mutiAccount {
mutiAccountMap := map[string]string{}
mutiAccountMap["uid"] = v
mutiAccountList = append(mutiAccountList, mutiAccountMap)
}
data, err := json.Marshal(mutiAccountList)
if err != nil {
return WrapError(err)
}
resultMutiAccount := string(data)
variableMap["multi_account"] = resultMutiAccount
}
variableMap["region"] = client.RegionId
variableMap["aliuid"] = d.Get("aliuid").(string)
variableMap["project"] = fmt.Sprintf("slsaudit-center-%s-%s", variableMap["aliuid"], variableMap["region"])
variableMap["logstore"] = "slsaudit"
if tempMap, ok := d.GetOk("variable_map"); ok {
for k, v := range tempMap.(map[string]interface{}) {
if strings.HasSuffix(k, "_policy_setting") {
return Error("Does not support configuration %s in variable_map", k)
}
variableMap[k] = v
}
}
b, err := json.Marshal(variableMap)
if err != nil {
return WrapError(err)
} else {
request.VariableMap = string(b[:])
}
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
rep, err := client.WithLogPopClient(func(client *slsPop.Client) (interface{}, error) {
return client.AnalyzeAppLog(request)
})
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout}) {
time.Sleep(5 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), rep, request)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_log_audit", request.GetActionName(), AliyunLogGoSdkERROR)
}
return resourceAlicloudLogAuditRead(d, meta)
}
func resourceAlicloudLogAuditRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logService := LogService{client}
response, err := logService.DescribeLogAudit(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
displayName, initMap, err := getInitParameter(response.GetHttpContentString())
if err != nil {
return WrapError(err)
}
d.Set("display_name", displayName)
d.Set("aliuid", initMap["aliuid"].(string))
if multiAccount, ok := initMap["multi_account"]; ok {
account, err := analyzeMultiAccount(multiAccount.(string))
if err != nil {
return WrapError(err)
}
d.Set("multi_account", account)
}
if resourceDirectory, ok := initMap["resource_directory"]; ok {
resourceDirectoryMap := map[string]interface{}{}
err = json.Unmarshal([]byte(resourceDirectory.(string)), &resourceDirectoryMap)
if err != nil {
return WrapError(err)
}
if len(resourceDirectoryMap) > 0 {
if rd_type, ok := resourceDirectoryMap["type"]; ok {
d.Set("resource_directory_type", rd_type.(string))
}
if multiAccount, ok := resourceDirectoryMap["multi_account"]; ok {
d.Set("multi_account", multiAccount)
}
}
}
for k := range initMap {
if strings.HasSuffix(k, "_policy_setting") {
delete(initMap, k)
}
}
delete(initMap, "region")
delete(initMap, "aliuid")
delete(initMap, "project")
delete(initMap, "logstore")
delete(initMap, "multi_account")
delete(initMap, "resource_directory")
d.Set("variable_map", initMap)
return nil
}
func resourceAlicloudLogAuditDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudLogAuditInstance.")
return nil
}
func getInitParameter(rep string) (displayName string, initMap map[string]interface{}, err error) {
m := make(map[string]interface{})
err = json.Unmarshal([]byte(rep), &m)
if _, ok := m["AppModel"].(map[string]interface{}); ok {
model := make(map[string]interface{})
err = json.Unmarshal([]byte(rep), &model)
if d, ok := model["AppModel"].(map[string]interface{}); ok {
displayName = d["DisplayName"].(string)
configNew := d["Config"]
m := make(map[string]interface{})
err = json.Unmarshal([]byte(configNew.(string)), &m)
initMap = m["initParam"].(map[string]interface{})
}
}
return displayName, initMap, err
}
func analyzeMultiAccount(s string) ([]string, error) {
var m []map[string]interface{}
err := json.Unmarshal([]byte(s), &m)
if err != nil {
return nil, err
}
multiAccount := make([]string, len(m))
for i := range m {
if v, ok := m[i]["uid"].(string); ok {
multiAccount[i] = v
} else {
multiAccount[i] = fmt.Sprintf("%.0f", m[i]["uid"].(float64))
}
}
return multiAccount, nil
}
package alicloud
import (
"encoding/json"
"fmt"
"log"
"reflect"
"sort"
"time"
sls "github.com/aliyun/aliyun-log-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudLogDashboard() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudLogDashboardCreate,
Read: resourceAlicloudLogDashboardRead,
Update: resourceAlicloudLogDashboardUpdate,
Delete: resourceAlicloudLogDashboardDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"project_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"dashboard_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"display_name": {
Type: schema.TypeString,
Optional: true,
},
"char_list": {
Type: schema.TypeString,
DiffSuppressFunc: jsonPolicyDiffSuppress,
Required: true,
},
},
}
}
func resourceAlicloudLogDashboardCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var requestInfo *sls.Client
dashBoard := sls.Dashboard{
DashboardName: d.Get("dashboard_name").(string),
DisplayName: d.Get("display_name").(string),
}
jsonErr := json.Unmarshal([]byte(d.Get("char_list").(string)), &dashBoard.ChartList)
if jsonErr != nil {
return WrapError(jsonErr)
}
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
_, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return nil, slsClient.CreateDashboard(d.Get("project_name").(string), dashBoard)
})
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout}) {
time.Sleep(5 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug("CreateDashboard", dashBoard, requestInfo, map[string]interface{}{
"dashBoard": dashBoard,
})
d.SetId(fmt.Sprintf("%s%s%s", d.Get("project_name").(string), COLON_SEPARATED, d.Get("dashboard_name").(string)))
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_log_dashboard", "CreateDashboard", AliyunLogGoSdkERROR)
}
return resourceAlicloudLogDashboardRead(d, meta)
}
func resourceAlicloudLogDashboardRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logService := LogService{client}
parts, err := ParseResourceId(d.Id(), 2)
object, err := logService.DescribeLogDashboard(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("project_name", parts[0])
d.Set("dashboard_name", object.DashboardName)
d.Set("display_name", object.DisplayName)
charlist, err := json.Marshal(object.ChartList)
if err != nil {
return WrapError(err)
}
d.Set("char_list", string(charlist))
return nil
}
func resourceAlicloudLogDashboardUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
update := false
dashboard := sls.Dashboard{}
dashboard.DisplayName = d.Get("display_name").(string)
data := d.Get("char_list").(string)
err := json.Unmarshal([]byte(data), &dashboard.ChartList)
if err != nil {
return WrapError(err)
}
if d.HasChange("display_name") {
update = true
}
if d.HasChange("char_list") {
update = true
}
if update {
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
dashboard.DashboardName = parts[1]
_, err = client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
return nil, slsClient.UpdateDashboard(parts[0], dashboard)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "UpdateDashboard", AliyunLogGoSdkERROR)
}
}
return resourceAlicloudLogDashboardRead(d, meta)
}
func resourceAlicloudLogDashboardDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logService := LogService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
var requestInfo *sls.Client
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return nil, slsClient.DeleteDashboard(parts[0], parts[1])
})
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout, "RequestTimeout"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug("DeleteDashboard", raw, requestInfo, map[string]interface{}{
"project_name": parts[0],
"dashboard": parts[1],
})
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"DashboardNotExist", "ProjectNotExist"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DeleteDashboard", AliyunLogGoSdkERROR)
}
return WrapError(logService.WaitForLogDashboard(d.Id(), Deleted, DefaultTimeout))
}
func jsonPolicyDiffSuppress(k, old, new string, d *schema.ResourceData) bool {
if old == "" && new == "" {
return true
}
var oldChartList, newChartList []sls.Chart
if old != "" && new != "" {
if err := json.Unmarshal([]byte(old), &oldChartList); err != nil {
log.Printf("[ERROR] Could not unmarshal old chart list %s: %v", old, err)
return false
}
if err := json.Unmarshal([]byte(new), &newChartList); err != nil {
log.Printf("[ERROR] Could not unmarshal new chart list %s: %v", new, err)
return false
}
return compareChartList(newChartList, oldChartList)
}
return false
}
type chartSort []sls.Chart
func (a chartSort) Len() int {
return len(a)
}
func (a chartSort) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a chartSort) Less(i, j int) bool {
return a[i].Title < a[j].Title
}
func compareChartList(a, b []sls.Chart) bool {
if len(a) != len(b) {
return false
}
sort.Sort(chartSort(a))
sort.Sort(chartSort(b))
for i, chart := range a {
if !reflect.DeepEqual(chart, b[i]) {
return false
}
}
return true
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
sls "github.com/aliyun/aliyun-log-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudLogETL() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudLogETLCreate,
Read: resourceAlicloudLogETLRead,
Update: resourceAlicloudLogETLUpdate,
Delete: resourceAlicloudLogETLDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(2 * time.Minute),
Delete: schema.DefaultTimeout(3 * time.Minute),
Update: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"etl_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"project": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"display_name": {
Type: schema.TypeString,
Required: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"schedule": {
Type: schema.TypeString,
Optional: true,
Default: "Resident",
},
"etl_type": {
Type: schema.TypeString,
Optional: true,
Default: sls.ETLType,
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"STARTING", "RUNNING", "STOPPING", "STOPPED"}, false),
},
"create_time": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"last_modified_time": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"access_key_id": {
Type: schema.TypeString,
Sensitive: true,
Optional: true,
},
"access_key_secret": {
Type: schema.TypeString,
Sensitive: true,
Optional: true,
},
"kms_encrypted_access_key_id": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: kmsDiffSuppressFunc,
},
"kms_encryption_access_key_id_context": {
Type: schema.TypeMap,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("kms_encrypted_access_key_id").(string) == ""
},
Elem: schema.TypeString,
},
"kms_encrypted_access_key_secret": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: kmsDiffSuppressFunc,
},
"kms_encryption_access_key_secret_context": {
Type: schema.TypeMap,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("kms_encrypted_access_key_secret").(string) == ""
},
Elem: schema.TypeString,
},
"from_time": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"to_time": {
Type: schema.TypeInt,
Optional: true,
},
"script": {
Type: schema.TypeString,
Required: true,
},
"version": {
Type: schema.TypeInt,
Optional: true,
Default: sls.ETLVersion,
},
"logstore": {
Type: schema.TypeString,
Required: true,
},
"parameters": {
Type: schema.TypeMap,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"role_arn": {
Type: schema.TypeString,
Optional: true,
},
"etl_sinks": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"access_key_id": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"kms_encrypted_access_key_id": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: kmsDiffSuppressFunc,
},
"access_key_secret": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"kms_encrypted_access_key_secret": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: kmsDiffSuppressFunc,
},
"endpoint": {
Type: schema.TypeString,
Required: true,
},
"name": {
Type: schema.TypeString,
Required: true,
},
"project": {
Type: schema.TypeString,
Required: true,
},
"logstore": {
Type: schema.TypeString,
Required: true,
},
"role_arn": {
Type: schema.TypeString,
Optional: true,
},
"type": {
Type: schema.TypeString,
Optional: true,
Default: sls.ETLSinksType,
},
},
},
},
},
}
}
func resourceAlicloudLogETLCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var requestinfo *sls.Client
logService := LogService{client}
etlJob, err := getETLJob(d, meta)
if err != nil {
return err
}
project := d.Get("project").(string)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
raw, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestinfo = slsClient
return nil, slsClient.CreateETL(project, etlJob)
})
if err != nil {
if IsExpectedErrors(err, []string{"InternalServerError", LogClientTimeout}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if debugOn() {
addDebug("CreateETL", raw, requestinfo, map[string]interface{}{
"project": project,
"logstore": d.Get("logstore").(string),
})
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_log_etl", "CreateETL", AliyunLogGoSdkERROR)
}
d.SetId(fmt.Sprintf("%s%s%s", project, COLON_SEPARATED, d.Get("etl_name").(string)))
stateConf := BuildStateConf([]string{}, []string{"RUNNING"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, logService.LogOssShipperStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudLogETLRead(d, meta)
}
func resourceAlicloudLogETLRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logService := LogService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
etl, err := logService.DescribeLogEtl(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_log_etl LogService.DescribeLogEtl Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("etl_name", parts[1])
d.Set("project", parts[0])
d.Set("display_name", etl.DisplayName)
d.Set("description", etl.Description)
d.Set("schedule", etl.Schedule.Type)
d.Set("etl_type", etl.Type)
d.Set("status", etl.Status)
d.Set("create_time", etl.CreateTime)
d.Set("last_modified_time", etl.LastModifiedTime)
d.Set("from_time", etl.Configuration.FromTime)
d.Set("to_time", etl.Configuration.ToTime)
d.Set("script", etl.Configuration.Script)
d.Set("version", etl.Configuration.Version)
d.Set("logstore", etl.Configuration.Logstore)
d.Set("parameters", etl.Configuration.Parameters)
d.Set("role_arn", etl.Configuration.RoleArn)
var etl_sinks []map[string]interface{}
for _, etl_sink := range etl.Configuration.ETLSinks {
temp := map[string]interface{}{
"access_key_id": etl_sink.AccessKeyId,
"access_key_secret": etl_sink.AccessKeySecret,
"endpoint": etl_sink.Endpoint,
"name": etl_sink.Name,
"project": etl_sink.Project,
"logstore": etl_sink.Logstore,
"role_arn": etl_sink.RoleArn,
"type": etl_sink.Type,
}
etl_sinks = append(etl_sinks, temp)
}
d.Set("etl_sinks", etl_sinks)
return nil
}
func resourceAlicloudLogETLUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
if d.HasChange("status") {
logService := LogService{client}
status := d.Get("status").(string)
if status == "STARTING" || status == "RUNNING" {
if err := resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
_, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
return nil, slsClient.StartETL(parts[0], d.Get("etl_name").(string))
})
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "StartLogETL", AliyunLogGoSdkERROR)
}
stateConf := BuildStateConf([]string{}, []string{"RUNNING"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, logService.LogOssShipperStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
} else if status == "STOPPING" || status == "STOPPED" {
if err := resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
_, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
return nil, slsClient.StopETL(parts[0], d.Get("etl_name").(string))
})
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "StopLogETL", AliyunLogGoSdkERROR)
}
stateConf := BuildStateConf([]string{}, []string{"STOPPED"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, logService.LogOssShipperStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudLogETLRead(d, meta)
}
if err := resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
_, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
etl, err := getETLJob(d, meta)
if err != nil {
return nil, err
}
return nil, slsClient.UpdateETL(parts[0], etl)
})
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "UpdateLogETL", AliyunLogGoSdkERROR)
}
return resourceAlicloudLogETLRead(d, meta)
}
func resourceAlicloudLogETLDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logService := LogService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
var requestInfo *sls.Client
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
raw, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return nil, slsClient.DeleteETL(parts[0], parts[1])
})
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if debugOn() {
addDebug("DeleteLogETL", raw, requestInfo, map[string]interface{}{
"project_name": parts[0],
"elt_name": parts[1],
})
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_log_etl", "DeleteLogETL", AliyunLogGoSdkERROR)
}
return WrapError(logService.WaitForLogETL(d.Id(), Deleted, DefaultTimeout))
}
func getETLJob(d *schema.ResourceData, meta interface{}) (sls.ETL, error) {
client := meta.(*connectivity.AliyunClient)
var etlSinks = []sls.ETLSink{}
var config = sls.ETLConfiguration{}
var etlJob = sls.ETL{}
schedule := sls.ETLSchedule{
Type: d.Get("schedule").(string),
}
parms := map[string]string{}
if temp, ok := d.GetOk("parameters"); ok {
for k, v := range temp.(map[string]interface{}) {
parms[k] = v.(string)
}
}
config = sls.ETLConfiguration{
FromTime: int64(d.Get("from_time").(int)),
Logstore: d.Get("logstore").(string),
Parameters: parms,
Script: d.Get("script").(string),
ToTime: int32(d.Get("to_time").(int)),
Version: int8(d.Get("version").(int)),
}
for _, f := range d.Get("etl_sinks").(*schema.Set).List() {
v := f.(map[string]interface{})
sink := sls.ETLSink{
Endpoint: v["endpoint"].(string),
Name: v["name"].(string),
Project: v["project"].(string),
Type: v["type"].(string),
Logstore: v["logstore"].(string),
}
sinkResult, err := permissionParameterCheck(v, client, d)
if err != nil {
return etlJob, WrapError(err)
}
if len(sinkResult) == 1 {
sink.RoleArn = sinkResult["roleArn"]
} else {
sink.AccessKeyId = sinkResult["akId"]
sink.AccessKeySecret = sinkResult["ak"]
}
etlSinks = append(etlSinks, sink)
}
config.ETLSinks = etlSinks
configResult, err := permissionParameterCheck(nil, client, d)
if err != nil {
return etlJob, WrapError(err)
}
if len(configResult) == 1 {
config.RoleArn = configResult["roleArn"]
} else {
config.AccessKeyId = configResult["akId"]
config.AccessKeySecret = configResult["ak"]
}
etlJob = sls.ETL{
Configuration: config,
DisplayName: d.Get("display_name").(string),
Description: d.Get("description").(string),
Name: d.Get("etl_name").(string),
Schedule: schedule,
Type: d.Get("etl_type").(string),
Status: d.Get("status").(string),
CreateTime: int32(d.Get("create_time").(int)),
LastModifiedTime: int32(d.Get("last_modified_time").(int)),
}
return etlJob, nil
}
func permissionParameterCheck(v map[string]interface{}, client *connectivity.AliyunClient, d *schema.ResourceData) (map[string]string, error) {
if v != nil {
akId := v["access_key_id"].(string)
ak := v["access_key_secret"].(string)
roleArn := v["role_arn"].(string)
if akId != "" && ak != "" {
if roleArn != "" {
return nil, Error("(access_key_id, access_key_secret), (role_arn) only one can be selected to fill into the sink")
}
return map[string]string{"akId": akId, "ak": ak}, nil
}
if roleArn != "" {
return map[string]string{"roleArn": roleArn}, nil
}
kmsAkId := v["kms_encrypted_access_key_id"].(string)
kmsAk := v["kms_encrypted_access_key_secret"].(string)
if kmsAkId != "" && kmsAk != "" {
kmsService := KmsService{client}
akIdResp, akIdErr := kmsService.Decrypt(kmsAkId, d.Get("kms_encryption_access_key_id_context").(map[string]interface{}))
if akIdErr != nil {
return nil, akIdErr
}
akResp, akErr := kmsService.Decrypt(kmsAk, d.Get("kms_encryption_access_key_secret_context").(map[string]interface{}))
if akErr != nil {
return nil, akErr
}
return map[string]string{"akId": akIdResp, "ak": akResp}, nil
}
return nil, Error("(access_key_id, access_key_secret),(kms_encrypted_access_key_id, kms_encrypted_access_key_secret, kms_encryption_access_key_id_context, kms_encryption_access_key_secret_context),(role_arn) must fill in one of them into sink")
} else {
akId := d.Get("access_key_id").(string)
ak := d.Get("access_key_secret").(string)
roleArn := d.Get("role_arn").(string)
if akId != "" && ak != "" {
if roleArn != "" {
return nil, Error("(access_key_id, access_key_secret), (role_arn) only one can be selected to fill into the configuration")
}
return map[string]string{"akId": akId, "ak": ak}, nil
}
if roleArn != "" {
return map[string]string{"roleArn": roleArn}, nil
}
kmsAkId := d.Get("kms_encrypted_access_key_id").(string)
kmsAk := d.Get("kms_encrypted_access_key_secret").(string)
if kmsAkId != "" && kmsAk != "" {
kmsService := KmsService{client}
akIdResp, akIdErr := kmsService.Decrypt(kmsAkId, d.Get("kms_encryption_access_key_id_context").(map[string]interface{}))
if akIdErr != nil {
return nil, akIdErr
}
akResp, akErr := kmsService.Decrypt(kmsAk, d.Get("kms_encryption_access_key_secret_context").(map[string]interface{}))
if akErr != nil {
return nil, akErr
}
return map[string]string{"akId": akIdResp, "ak": akResp}, nil
}
return nil, Error("(access_key_id, access_key_secret),(kms_encrypted_access_key_id, kms_encrypted_access_key_secret, kms_encryption_access_key_id_context, kms_encryption_access_key_secret_context),(role_arn) must fill in one of them into configuration")
}
}
package alicloud
import (
"fmt"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
sls "github.com/aliyun/aliyun-log-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudLogMachineGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudLogMachineGroupCreate,
Read: resourceAlicloudLogMachineGroupRead,
Update: resourceAlicloudLogMachineGroupUpdate,
Delete: resourceAlicloudLogMachineGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"project": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"identify_type": {
Type: schema.TypeString,
Optional: true,
Default: sls.MachineIDTypeIP,
ValidateFunc: validation.StringInSlice([]string{sls.MachineIDTypeIP, sls.MachineIDTypeUserDefined}, false),
},
"topic": {
Type: schema.TypeString,
Optional: true,
},
"identify_list": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Required: true,
MinItems: 1,
},
},
}
}
func resourceAlicloudLogMachineGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
params := &sls.MachineGroup{
Name: d.Get("name").(string),
MachineIDType: d.Get("identify_type").(string),
MachineIDList: expandStringList(d.Get("identify_list").(*schema.Set).List()),
Attribute: sls.MachinGroupAttribute{
TopicName: d.Get("topic").(string),
},
}
var requestInfo *sls.Client
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return nil, slsClient.CreateMachineGroup(d.Get("project").(string), params)
})
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout}) {
time.Sleep(5 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if debugOn() {
addDebug("CreateMachineGroup", raw, requestInfo, map[string]interface{}{
"project": d.Get("project").(string),
"MachineGroup": params,
})
}
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_log_machine_group", "CreateMachineGroup", AliyunLogGoSdkERROR)
}
d.SetId(fmt.Sprintf("%s%s%s", d.Get("project").(string), COLON_SEPARATED, d.Get("name").(string)))
return resourceAlicloudLogMachineGroupRead(d, meta)
}
func resourceAlicloudLogMachineGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logService := LogService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
object, err := logService.DescribeLogMachineGroup(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("project", parts[0])
d.Set("name", object.Name)
d.Set("identify_type", object.MachineIDType)
d.Set("identify_list", object.MachineIDList)
d.Set("topic", object.Attribute.TopicName)
return nil
}
func resourceAlicloudLogMachineGroupUpdate(d *schema.ResourceData, meta interface{}) error {
if d.HasChange("identify_type") || d.HasChange("identify_list") || d.HasChange("topic") {
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
client := meta.(*connectivity.AliyunClient)
var requestInfo *sls.Client
params := &sls.MachineGroup{
Name: parts[1],
MachineIDType: d.Get("identify_type").(string),
MachineIDList: expandStringList(d.Get("identify_list").(*schema.Set).List()),
Attribute: sls.MachinGroupAttribute{
TopicName: d.Get("topic").(string),
},
}
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return nil, slsClient.UpdateMachineGroup(parts[0], params)
})
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout}) {
time.Sleep(5 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if debugOn() {
addDebug("UpdateMachineGroup", raw, requestInfo, map[string]interface{}{
"project": parts[0],
"MachineGroup": params,
})
}
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "UpdateMachineGroup", AliyunLogGoSdkERROR)
}
}
return resourceAlicloudLogMachineGroupRead(d, meta)
}
func resourceAlicloudLogMachineGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logService := LogService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
var requestInfo *sls.Client
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return nil, slsClient.DeleteMachineGroup(parts[0], parts[1])
})
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout}) {
time.Sleep(5 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if debugOn() {
addDebug("DeleteMachineGroup", raw, requestInfo, map[string]interface{}{
"project": parts[0],
"machineGroup": parts[1],
})
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_log_store", "ListShards", AliyunLogGoSdkERROR)
}
return WrapError(logService.WaitForLogMachineGroup(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
sls "github.com/aliyun/aliyun-log-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudLogOssShipper() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudLogOssShipperCreate,
Read: resourceAlicloudLogOssShipperRead,
Update: resourceAlicloudLogOssShipperUpdate,
Delete: resourceAlicloudLogOssShipperDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
Delete: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"project_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"logstore_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"shipper_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"oss_bucket": {
Type: schema.TypeString,
Required: true,
},
"oss_prefix": {
Type: schema.TypeString,
Optional: true,
},
"buffer_interval": {
Type: schema.TypeInt,
Required: true,
},
"buffer_size": {
Type: schema.TypeInt,
Required: true,
},
"role_arn": {
Type: schema.TypeString,
Optional: true,
},
"compress_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"none", "snappy"}, false),
Default: "none",
},
"path_format": {
Type: schema.TypeString,
Required: true,
},
"format": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"json", "parquet", "csv"}, false),
},
"json_enable_tag": {
Type: schema.TypeBool,
Optional: true,
},
"csv_config_delimiter": {
Type: schema.TypeString,
Optional: true,
},
"csv_config_header": {
Type: schema.TypeBool,
Optional: true,
},
"csv_config_linefeed": {
Type: schema.TypeString,
Optional: true,
},
"csv_config_columns": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"csv_config_nullidentifier": {
Type: schema.TypeString,
Optional: true,
},
"csv_config_quote": {
Type: schema.TypeString,
Optional: true,
},
"parquet_config": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"type": {
Type: schema.TypeString,
Required: true,
},
},
},
},
},
}
}
func resourceAlicloudLogOssShipperCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var requestInfo *sls.Client
projectName := d.Get("project_name").(string)
logstoreName := d.Get("logstore_name").(string)
shipperName := d.Get("shipper_name").(string)
wait := incrementalWait(3*time.Second, 3*time.Second)
if err := resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
raw, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
project, _ := sls.NewLogProject(projectName, slsClient.Endpoint, slsClient.AccessKeyID, slsClient.AccessKeySecret)
project, _ = project.WithToken(slsClient.SecurityToken)
logstore, _ := sls.NewLogStore(logstoreName, project)
return nil, logstore.CreateShipper(buildConfig(d))
})
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug("CreateLogShipper", raw, requestInfo, map[string]string{
"project_name": projectName,
"logstore_name": logstoreName,
"shipper_name": shipperName,
})
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_log_oss_shipper", "CreateLogOssShipper", AliyunLogGoSdkERROR)
}
d.SetId(fmt.Sprintf("%s%s%s%s%s", projectName, COLON_SEPARATED, logstoreName, COLON_SEPARATED, shipperName))
return resourceAlicloudLogOssShipperRead(d, meta)
}
func resourceAlicloudLogOssShipperRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logService := LogService{client}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
shipper, err := logService.DescribeLogOssShipper(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_log_oss_shipper LogService.DescribeLogOssShipper Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
ossShipperConfig := shipper.TargetConfiguration.(*sls.OSSShipperConfig)
d.Set("project_name", parts[0])
d.Set("logstore_name", parts[1])
d.Set("shipper_name", parts[2])
d.Set("oss_bucket", ossShipperConfig.OssBucket)
d.Set("oss_prefix", ossShipperConfig.OssPrefix)
d.Set("buffer_interval", ossShipperConfig.BufferInterval)
d.Set("buffer_size", ossShipperConfig.BufferSize)
d.Set("role_arn", ossShipperConfig.RoleArn)
d.Set("compress_type", ossShipperConfig.CompressType)
d.Set("path_format", ossShipperConfig.PathFormat)
d.Set("format", ossShipperConfig.Storage.Format)
if ossShipperConfig.Storage.Format == "json" {
detail := ossShipperConfig.Storage.Detail.(map[string]interface{})
d.Set("json_enable_tag", detail["enableTag"])
} else if ossShipperConfig.Storage.Format == "csv" {
detail := ossShipperConfig.Storage.Detail.(map[string]interface{})
d.Set("csv_config_delimiter", detail["delimiter"])
d.Set("csv_config_header", detail["header"])
d.Set("csv_config_linefeed", detail["linefeed"])
d.Set("csv_config_columns", detail["columns"])
d.Set("csv_config_nullidentifier", detail["nullidentifier"])
d.Set("csv_config_quote", detail["quote"])
} else if ossShipperConfig.Storage.Format == "parquet" {
var config []map[string]interface{}
detail := ossShipperConfig.Storage.Detail.(map[string]interface{})
tempConfigs := detail["columns"].([]interface{})
for _, temp := range tempConfigs {
parquetConfig := temp.(map[string]interface{})
tempMap := map[string]interface{}{
"name": parquetConfig["name"],
"type": parquetConfig["type"],
}
config = append(config, tempMap)
}
d.Set("parquet_config", config)
}
return nil
}
func resourceAlicloudLogOssShipperUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
if err := resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
_, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
project, _ := sls.NewLogProject(parts[0], slsClient.Endpoint, slsClient.AccessKeyID, slsClient.AccessKeySecret)
project, _ = project.WithToken(slsClient.SecurityToken)
logstore, _ := sls.NewLogStore(parts[1], project)
return nil, logstore.UpdateShipper(buildConfig(d))
})
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "UpdateLogOssShipper", AliyunLogGoSdkERROR)
}
return resourceAlicloudLogOssShipperRead(d, meta)
}
func resourceAlicloudLogOssShipperDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logService := LogService{client}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
var requestInfo *sls.Client
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
raw, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
project, _ := sls.NewLogProject(parts[0], slsClient.Endpoint, slsClient.AccessKeyID, slsClient.AccessKeySecret)
project, _ = project.WithToken(slsClient.SecurityToken)
logstore, _ := sls.NewLogStore(parts[1], project)
return nil, logstore.DeleteShipper(parts[2])
})
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if debugOn() {
addDebug("DeleteLogOssShipper", raw, requestInfo, map[string]interface{}{
"project_name": parts[0],
"logstore_name": parts[1],
"shipper_name": parts[2],
})
}
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ShipperNotExist"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, "alicloud_log_oss_shipper", "DeleteLogOssShipper", AliyunLogGoSdkERROR)
}
return WrapError(logService.WaitForLogOssShipper(d.Id(), Deleted, DefaultTimeout))
}
func buildConfig(d *schema.ResourceData) *sls.Shipper {
format := d.Get("format").(string)
var storage sls.ShipperStorage
if format == "json" {
enableTag := d.Get("json_enable_tag").(bool)
storage = sls.ShipperStorage{
Format: "json",
Detail: sls.OssStorageJsonDetail{EnableTag: enableTag},
}
} else if format == "parquet" {
detail := sls.OssStoreageParquet{}
for _, f := range d.Get("parquet_config").(*schema.Set).List() {
v := f.(map[string]interface{})
config := sls.ParquetConfig{
Name: v["name"].(string),
Type: v["type"].(string),
}
detail.Columns = append(detail.Columns, config)
}
storage = sls.ShipperStorage{
Format: "parquet",
Detail: detail,
}
} else if format == "csv" {
detail := sls.OssStoreageCsvDetail{
Delimiter: d.Get("csv_config_delimiter").(string),
Header: d.Get("csv_config_header").(bool),
LineFeed: d.Get("csv_config_linefeed").(string),
NullIdentifier: d.Get("csv_config_nullidentifier").(string),
Quote: d.Get("csv_config_quote").(string),
}
columns := []string{}
for _, v := range d.Get("csv_config_columns").([]interface{}) {
columns = append(columns, v.(string))
}
detail.Columns = columns
storage = sls.ShipperStorage{
Format: "csv",
Detail: detail,
}
}
ossShipperConfig := &sls.OSSShipperConfig{
OssBucket: d.Get("oss_bucket").(string),
OssPrefix: d.Get("oss_prefix").(string),
RoleArn: d.Get("role_arn").(string),
BufferInterval: d.Get("buffer_interval").(int),
BufferSize: d.Get("buffer_size").(int),
CompressType: d.Get("compress_type").(string),
PathFormat: d.Get("path_format").(string),
Storage: storage,
}
ossShipper := &sls.Shipper{
ShipperName: d.Get("shipper_name").(string),
TargetType: "oss",
TargetConfiguration: ossShipperConfig,
}
return ossShipper
}
package alicloud
import (
"time"
sls "github.com/aliyun/aliyun-log-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudLogProject() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudLogProjectCreate,
Read: resourceAlicloudLogProjectRead,
Update: resourceAlicloudLogProjectUpdate,
Delete: resourceAlicloudLogProjectDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(3 * time.Minute),
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"tags": tagsSchema(),
},
}
}
func resourceAlicloudLogProjectCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logService := LogService{client}
var requestInfo *sls.Client
request := map[string]string{
"name": d.Get("name").(string),
"description": d.Get("description").(string),
}
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return slsClient.CreateProject(request["name"], request["description"])
})
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout}) {
time.Sleep(5 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug("CreateProject", raw, requestInfo, request)
response, _ := raw.(*sls.LogProject)
d.SetId(response.Name)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_log_project", "CreateProject", AliyunLogGoSdkERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, logService.LogProjectStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudLogProjectUpdate(d, meta)
}
func resourceAlicloudLogProjectRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logService := LogService{client}
object, err := logService.DescribeLogProject(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", object.Name)
d.Set("description", object.Description)
projectTags, err := logService.DescribeLogProjectTags(object.Name)
if projectTags != nil {
tags := map[string]interface{}{}
for _, tag := range projectTags {
tags[tag.TagKey] = tag.TagValue
}
if err := d.Set("tags", tags); err != nil {
return WrapError(err)
}
}
return nil
}
func buildTags(projectName string, tags map[string]interface{}) *sls.ResourceTags {
slsTags := []sls.ResourceTag{}
for key, value := range tags {
tag := sls.ResourceTag{Key: key, Value: value.(string)}
slsTags = append(slsTags, tag)
}
projectTags := sls.NewProjectTags(projectName, slsTags)
return projectTags
}
func deleteProjectTags(client *connectivity.AliyunClient, slsTags []string, projectName string) error {
var requestInfo *sls.Client
projectUnTags := sls.NewProjectUnTags(projectName, slsTags)
raw, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return nil, slsClient.UnTagResources(projectName, projectUnTags)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, projectName, "DeletaTags", AliyunLogGoSdkERROR)
}
addDebug("DeletaTags", raw, requestInfo, map[string]string{
"name": projectName,
})
return nil
}
func resourceAlicloudLogProjectUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
d.Partial(true)
var requestInfo *sls.Client
logService := LogService{client}
projectName := d.Get("name").(string)
request := map[string]string{
"name": projectName,
"description": d.Get("description").(string),
}
if d.HasChange("description") {
raw, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return slsClient.UpdateProject(request["name"], request["description"])
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "UpdateProject", AliyunLogGoSdkERROR)
}
addDebug("UpdateProject", raw, requestInfo, request)
}
if d.HasChange("tags") {
projectTags, err := logService.DescribeLogProjectTags(projectName)
if err != nil {
return err
}
slsTags := []string{}
for _, value := range projectTags {
slsTags = append(slsTags, value.TagKey)
}
tags := d.Get("tags").(map[string]interface{})
if tags == nil || len(tags) == 0 {
if err := deleteProjectTags(client, slsTags, projectName); err != nil {
return WrapError(err)
}
} else {
if err := deleteProjectTags(client, slsTags, projectName); err != nil {
return WrapError(err)
}
projectNewTags := buildTags(projectName, tags)
raw, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return nil, slsClient.TagResources(projectName, projectNewTags)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "UpdateTags", AliyunLogGoSdkERROR)
}
addDebug("UpdateTags", raw, requestInfo, request)
}
d.SetPartial("tags")
}
d.Partial(false)
return resourceAlicloudLogProjectRead(d, meta)
}
func resourceAlicloudLogProjectDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logService := LogService{client}
var requestInfo *sls.Client
request := map[string]string{
"name": d.Get("name").(string),
"description": d.Get("description").(string),
}
err := resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return nil, slsClient.DeleteProject(request["name"])
})
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout, "RequestTimeout"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug("DeleteProject", raw, requestInfo, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ProjectNotExist"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DeleteProject", AliyunLogGoSdkERROR)
}
return WrapError(logService.WaitForLogProject(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"fmt"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
sls "github.com/aliyun/aliyun-log-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudLogStore() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudLogStoreCreate,
Read: resourceAlicloudLogStoreRead,
Update: resourceAlicloudLogStoreUpdate,
Delete: resourceAlicloudLogStoreDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(3 * time.Minute),
Delete: schema.DefaultTimeout(3 * time.Minute),
Read: schema.DefaultTimeout(2 * time.Minute),
},
Schema: map[string]*schema.Schema{
"project": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"retention_period": {
Type: schema.TypeInt,
Optional: true,
Default: 30,
ValidateFunc: validation.IntBetween(1, 3650),
},
"shard_count": {
Type: schema.TypeInt,
Optional: true,
Default: 2,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if old == "" {
return false
}
return true
},
},
"shards": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeInt,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"begin_key": {
Type: schema.TypeString,
Computed: true,
},
"end_key": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"auto_split": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"max_split_shard_count": {
Type: schema.TypeInt,
Optional: true,
Default: 0,
ValidateFunc: validation.IntBetween(0, 64),
},
"append_meta": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"enable_web_tracking": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"encrypt_conf": {
Type: schema.TypeSet,
ForceNew: true,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"encrypt_type": {
Type: schema.TypeString,
Optional: true,
Default: "default",
ValidateFunc: validation.StringInSlice([]string{"default", "m4"}, false),
},
"user_cmk_info": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cmk_key_id": {
Type: schema.TypeString,
Required: true,
},
"arn": {
Type: schema.TypeString,
Required: true,
},
"region_id": {
Type: schema.TypeString,
Required: true,
},
},
},
},
},
},
},
},
}
}
func resourceAlicloudLogStoreCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logstore := &sls.LogStore{
Name: d.Get("name").(string),
TTL: d.Get("retention_period").(int),
ShardCount: d.Get("shard_count").(int),
WebTracking: d.Get("enable_web_tracking").(bool),
AutoSplit: d.Get("auto_split").(bool),
MaxSplitShard: d.Get("max_split_shard_count").(int),
AppendMeta: d.Get("append_meta").(bool),
}
if encrypt := buildEncrypt(d); encrypt != nil {
logstore.EncryptConf = encrypt
}
var requestinfo *sls.Client
err := resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
raw, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestinfo = slsClient
return nil, slsClient.CreateLogStoreV2(d.Get("project").(string), logstore)
})
if err != nil {
if IsExpectedErrors(err, []string{"InternalServerError", LogClientTimeout}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if debugOn() {
addDebug("CreateLogStoreV2", raw, requestinfo, map[string]interface{}{
"project": d.Get("project").(string),
"logstore": logstore,
})
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_log_store", "CreateLogStoreV2", AliyunLogGoSdkERROR)
}
// Wait for the store to be available
time.Sleep(60 * time.Second)
d.SetId(fmt.Sprintf("%s%s%s", d.Get("project").(string), COLON_SEPARATED, d.Get("name").(string)))
return resourceAlicloudLogStoreUpdate(d, meta)
}
func resourceAlicloudLogStoreRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logService := LogService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
object, err := logService.DescribeLogStore(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return err
}
d.Set("project", parts[0])
d.Set("name", object.Name)
d.Set("retention_period", object.TTL)
d.Set("shard_count", object.ShardCount)
var shards []*sls.Shard
err = resource.Retry(d.Timeout(schema.TimeoutRead), func() *resource.RetryError {
shards, err = object.ListShards()
if err != nil {
if IsExpectedErrors(err, []string{"InternalServerError"}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug("ListShards", shards)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_log_store", "ListShards", AliyunLogGoSdkERROR)
}
var shardList []map[string]interface{}
for _, s := range shards {
mapping := map[string]interface{}{
"id": s.ShardID,
"status": s.Status,
"begin_key": s.InclusiveBeginKey,
"end_key": s.ExclusiveBeginKey,
}
shardList = append(shardList, mapping)
}
d.Set("shards", shardList)
d.Set("append_meta", object.AppendMeta)
d.Set("auto_split", object.AutoSplit)
d.Set("enable_web_tracking", object.WebTracking)
d.Set("max_split_shard_count", object.MaxSplitShard)
if encrypt := object.EncryptConf; encrypt != nil {
encryptMap := map[string]interface{}{
"enable": encrypt.Enable,
"encrypt_type": encrypt.EncryptType,
}
if userCmkInfo := encrypt.UserCmkInfo; userCmkInfo != nil {
userCmkInfoMap := map[string]interface{}{
"cmk_key_id": userCmkInfo.CmkKeyId,
"arn": userCmkInfo.Arn,
"region_id": userCmkInfo.RegionId,
}
encryptMap["user_cmk_info"] = []map[string]interface{}{userCmkInfoMap}
}
if err := d.Set("encrypt_conf", []map[string]interface{}{encryptMap}); err != nil {
return WrapError(err)
}
}
return nil
}
func resourceAlicloudLogStoreUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logService := LogService{client}
if d.IsNewResource() {
return resourceAlicloudLogStoreRead(d, meta)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Partial(true)
update := false
if d.HasChange("retention_period") {
update = true
d.SetPartial("retention_period")
}
if d.HasChange("max_split_shard_count") {
update = true
d.SetPartial("max_split_shard_count")
}
if d.HasChange("enable_web_tracking") {
update = true
d.SetPartial("enable_web_tracking")
}
if d.HasChange("append_meta") {
update = true
d.SetPartial("append_meta")
}
if d.HasChange("auto_split") {
update = true
d.SetPartial("auto_split")
}
if update {
store, err := logService.DescribeLogStore(d.Id())
if err != nil {
return WrapError(err)
}
store.MaxSplitShard = d.Get("max_split_shard_count").(int)
store.TTL = d.Get("retention_period").(int)
store.WebTracking = d.Get("enable_web_tracking").(bool)
store.AppendMeta = d.Get("append_meta").(bool)
store.AutoSplit = d.Get("auto_split").(bool)
var requestInfo *sls.Client
raw, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return nil, slsClient.UpdateLogStoreV2(parts[0], store)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "UpdateLogStoreV2", AliyunLogGoSdkERROR)
}
if debugOn() {
addDebug("UpdateLogStoreV2", raw, requestInfo, map[string]interface{}{
"project": parts[0],
"logstore": store,
})
}
}
d.Partial(false)
return resourceAlicloudLogStoreRead(d, meta)
}
func resourceAlicloudLogStoreDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logService := LogService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
var raw interface{}
var requestInfo *sls.Client
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
raw, err = client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return nil, slsClient.DeleteLogStore(parts[0], parts[1])
})
if err != nil {
if code, ok := err.(*sls.Error); ok {
if "LogStoreNotExist" == code.Code {
return nil
}
}
if IsExpectedErrors(err, []string{"ProjectForbidden", LogClientTimeout}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug("DeleteLogStore", raw, requestInfo, map[string]interface{}{
"project": parts[0],
"logstore": parts[1],
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_log_store", "DeleteLogStore", AliyunLogGoSdkERROR)
}
return WrapError(logService.WaitForLogStore(d.Id(), Deleted, DefaultTimeout))
}
func buildEncrypt(d *schema.ResourceData) *sls.EncryptConf {
var encryptConf *sls.EncryptConf
if field, ok := d.GetOk("encrypt_conf"); ok {
encryptConf = new(sls.EncryptConf)
value := field.(*schema.Set).List()[0].(map[string]interface{})
encryptConf.Enable = value["enable"].(bool)
encryptConf.EncryptType = value["encrypt_type"].(string)
cmkInfo := value["user_cmk_info"].(*schema.Set).List()
if len(cmkInfo) > 0 {
cmk := cmkInfo[0].(map[string]interface{})
encryptConf.UserCmkInfo = &sls.EncryptUserCmkConf{
CmkKeyId: cmk["cmk_key_id"].(string),
Arn: cmk["arn"].(string),
RegionId: cmk["region_id"].(string),
}
}
}
return encryptConf
}
package alicloud
import (
"fmt"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
sls "github.com/aliyun/aliyun-log-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudLogStoreIndex() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudLogStoreIndexCreate,
Read: resourceAlicloudLogStoreIndexRead,
Update: resourceAlicloudLogStoreIndexUpdate,
Delete: resourceAlicloudLogStoreIndexDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"project": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"logstore": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"full_text": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"case_sensitive": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"include_chinese": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"token": {
Type: schema.TypeString,
Optional: true,
},
},
},
MaxItems: 1,
},
//field search
"field_search": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"type": {
Type: schema.TypeString,
Optional: true,
Default: "long",
ValidateFunc: validation.StringInSlice([]string{"text", "long", "double", "json"}, false),
},
"alias": {
Type: schema.TypeString,
Optional: true,
},
"case_sensitive": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"include_chinese": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"token": {
Type: schema.TypeString,
Optional: true,
},
"enable_analytics": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"json_keys": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"type": {
Type: schema.TypeString,
Optional: true,
Default: "long",
},
"alias": {
Type: schema.TypeString,
Optional: true,
},
"doc_value": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
},
},
},
},
},
MinItems: 1,
},
},
}
}
func resourceAlicloudLogStoreIndexCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logService := LogService{client}
_, fullOk := d.GetOk("full_text")
_, fieldOk := d.GetOk("field_search")
if !fullOk && !fieldOk {
return WrapError(Error("At least one of the 'full_text' and 'field_search' should be specified."))
}
project := d.Get("project").(string)
store, err := logService.DescribeLogStore(fmt.Sprintf("%s%s%s", project, COLON_SEPARATED, d.Get("logstore").(string)))
if err != nil {
return WrapError(err)
}
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := store.GetIndex()
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout}) {
time.Sleep(5 * time.Second)
return resource.RetryableError(WrapErrorf(err, DefaultErrorMsg, "alicloud_log_store", "GetIndex", AliyunLogGoSdkERROR))
}
if !IsExpectedErrors(err, []string{"IndexConfigNotExist"}) {
return resource.NonRetryableError(WrapErrorf(err, DefaultErrorMsg, "alicloud_log_store", "GetIndex", AliyunLogGoSdkERROR))
}
}
if raw != nil {
return resource.NonRetryableError(WrapError(Error("There is aleady existing an index in the store %s. Please import it using id '%s%s%s'.",
store.Name, project, COLON_SEPARATED, store.Name)))
}
addDebug("GetIndex", raw)
return nil
}); err != nil {
return err
}
var index sls.Index
if fullOk {
index.Line = buildIndexLine(d)
}
if fieldOk {
index.Keys = buildIndexKeys(d)
}
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
if e := store.CreateIndex(index); e != nil {
if IsExpectedErrors(e, []string{"InternalServerError", LogClientTimeout}) {
return resource.RetryableError(e)
}
return resource.NonRetryableError(e)
}
addDebug("CreateIndex", nil)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_log_store_index", "CreateIndex", AliyunLogGoSdkERROR)
}
d.SetId(fmt.Sprintf("%s%s%s", project, COLON_SEPARATED, store.Name))
return resourceAlicloudLogStoreIndexRead(d, meta)
}
func resourceAlicloudLogStoreIndexRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logService := LogService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
index, err := logService.DescribeLogStoreIndex(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
if line := index.Line; line != nil {
mapping := map[string]interface{}{
"case_sensitive": line.CaseSensitive,
"include_chinese": line.Chn,
"token": strings.Join(line.Token, ""),
}
if err := d.Set("full_text", []map[string]interface{}{mapping}); err != nil {
return WrapError(err)
}
}
if keys := index.Keys; keys != nil {
var keySet []map[string]interface{}
for k, v := range keys {
mapping := map[string]interface{}{
"name": k,
"type": v.Type,
"alias": v.Alias,
"case_sensitive": v.CaseSensitive,
"include_chinese": v.Chn,
"token": strings.Join(v.Token, ""),
"enable_analytics": v.DocValue,
}
if len(v.JsonKeys) > 0 {
var result = []map[string]interface{}{}
for k1, v1 := range v.JsonKeys {
var value = map[string]interface{}{}
value["doc_value"] = v1.DocValue
value["alias"] = v1.Alias
value["type"] = v1.Type
value["name"] = k1
result = append(result, value)
}
mapping["json_keys"] = result
}
keySet = append(keySet, mapping)
}
if err := d.Set("field_search", keySet); err != nil {
return WrapError(err)
}
}
d.Set("project", parts[0])
d.Set("logstore", parts[1])
return nil
}
func resourceAlicloudLogStoreIndexUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
logService := LogService{client}
index, err := logService.DescribeLogStoreIndex(d.Id())
if err != nil {
return WrapError(err)
}
update := false
if d.HasChange("full_text") {
index.Line = buildIndexLine(d)
update = true
}
if d.HasChange("field_search") {
index.Keys = buildIndexKeys(d)
update = true
}
if update {
var requestInfo *sls.Client
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return nil, slsClient.UpdateIndex(parts[0], parts[1], *index)
})
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout}) {
time.Sleep(5 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if debugOn() {
addDebug("UpdateIndex", raw, requestInfo, map[string]interface{}{
"project": parts[0],
"logstore": parts[1],
"index": index,
})
}
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "UpdateIndex", AliyunLogGoSdkERROR)
}
}
return resourceAlicloudLogStoreIndexRead(d, meta)
}
func resourceAlicloudLogStoreIndexDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logService := LogService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
if _, err := logService.DescribeLogStoreIndex(d.Id()); err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
var requestInfo *sls.Client
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return nil, slsClient.DeleteIndex(parts[0], parts[1])
})
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout}) {
time.Sleep(5 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if debugOn() {
addDebug("DeleteIndex", raw, requestInfo, map[string]interface{}{
"project": parts[0],
"logstore": parts[1],
})
}
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DeleteIndex", AliyunLogGoSdkERROR)
}
return nil
}
func buildIndexLine(d *schema.ResourceData) *sls.IndexLine {
if fullText, ok := d.GetOk("full_text"); ok {
value := fullText.(*schema.Set).List()[0].(map[string]interface{})
return &sls.IndexLine{
CaseSensitive: value["case_sensitive"].(bool),
Chn: value["include_chinese"].(bool),
Token: strings.Split(value["token"].(string), ""),
}
}
return nil
}
func buildIndexKeys(d *schema.ResourceData) map[string]sls.IndexKey {
keys := make(map[string]sls.IndexKey)
if field, ok := d.GetOk("field_search"); ok {
for _, f := range field.(*schema.Set).List() {
v := f.(map[string]interface{})
indexKey := sls.IndexKey{
Type: v["type"].(string),
Alias: v["alias"].(string),
DocValue: v["enable_analytics"].(bool),
Token: strings.Split(v["token"].(string), ""),
CaseSensitive: v["case_sensitive"].(bool),
Chn: v["include_chinese"].(bool),
JsonKeys: map[string]*sls.JsonKey{},
}
jsonKeys := v["json_keys"].(*schema.Set).List()
for _, e := range jsonKeys {
value := e.(map[string]interface{})
name := value["name"].(string)
alias := value["alias"].(string)
keyType := value["type"].(string)
docValue := value["doc_value"].(bool)
indexKey.JsonKeys[name] = &sls.JsonKey{
Type: keyType,
Alias: alias,
DocValue: docValue,
}
}
keys[v["name"].(string)] = indexKey
}
}
return keys
}
package alicloud
import (
"fmt"
sls "github.com/aliyun/aliyun-log-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudLogtailAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudLogtailAttachmentCreate,
Read: resourceAlicloudLogtailAttachmentRead,
Delete: resourceAlicloudLogtailAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"project": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"logtail_config_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"machine_group_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudLogtailAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
project := d.Get("project").(string)
config_name := d.Get("logtail_config_name").(string)
group_name := d.Get("machine_group_name").(string)
var requestInfo *sls.Client
raw, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return nil, slsClient.ApplyConfigToMachineGroup(project, config_name, group_name)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_logtail_attachment", "ApplyConfigToMachineGroup", AliyunLogGoSdkERROR)
}
if debugOn() {
addDebug("ApplyConfigToMachineGroup", raw, requestInfo, map[string]string{
"project": project,
"confName": config_name,
"groupName": group_name,
})
}
d.SetId(fmt.Sprintf("%s%s%s%s%s", project, COLON_SEPARATED, config_name, COLON_SEPARATED, group_name))
return resourceAlicloudLogtailAttachmentRead(d, meta)
}
func resourceAlicloudLogtailAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logService := LogService{client}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
object, err := logService.DescribeLogtailAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("project", parts[0])
d.Set("logtail_config_name", parts[1])
d.Set("machine_group_name", object)
return nil
}
func resourceAlicloudLogtailAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logService := LogService{client}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
var requestInfo *sls.Client
raw, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return nil, slsClient.RemoveConfigFromMachineGroup(parts[0], parts[1], parts[2])
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "RemoveConfigFromMachineGroup", AliyunLogGoSdkERROR)
}
if debugOn() {
addDebug("RemoveConfigFromMachineGroup", raw, requestInfo, map[string]string{
"project": parts[0],
"confName": parts[1],
"groupName": parts[2],
})
}
return WrapError(logService.WaitForLogtailAttachment(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"encoding/json"
"fmt"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
sls "github.com/aliyun/aliyun-log-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudLogtailConfig() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudLogtailConfigCreate,
Read: resourceAlicloudLogtailConfigRead,
Update: resourceAlicloudLogtailConfiglUpdate,
Delete: resourceAlicloudLogtailConfigDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"input_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"file", "plugin"}, false),
},
"log_sample": {
Type: schema.TypeString,
Optional: true,
},
"project": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"logstore": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"output_type": {
Type: schema.TypeString,
Required: true,
},
"input_detail": {
Type: schema.TypeString,
Required: true,
StateFunc: func(v interface{}) string {
yaml, _ := normalizeJsonString(v)
return yaml
},
ValidateFunc: validation.ValidateJsonString,
},
},
}
}
func resourceAlicloudLogtailConfigCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var inputConfigInputDetail = make(map[string]interface{})
data := d.Get("input_detail").(string)
if jsonErr := json.Unmarshal([]byte(data), &inputConfigInputDetail); jsonErr != nil {
return WrapError(jsonErr)
}
var requestInfo *sls.Client
logconfig := &sls.LogConfig{
Name: d.Get("name").(string),
LogSample: d.Get("log_sample").(string),
InputType: d.Get("input_type").(string),
OutputType: d.Get("output_type").(string),
OutputDetail: sls.OutputDetail{
ProjectName: d.Get("project").(string),
LogStoreName: d.Get("logstore").(string),
},
}
raw, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
sls.AddNecessaryInputConfigField(inputConfigInputDetail)
covertInput, covertErr := assertInputDetailType(inputConfigInputDetail, logconfig)
if covertErr != nil {
return nil, WrapError(covertErr)
}
logconfig.InputDetail = covertInput
return nil, slsClient.CreateConfig(d.Get("project").(string), logconfig)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_logtail_config", "CreateConfig", AliyunLogGoSdkERROR)
}
if debugOn() {
addDebug("CreateConfig", raw, requestInfo, map[string]interface{}{
"project": d.Get("project").(string),
"config": logconfig,
})
}
d.SetId(fmt.Sprintf("%s%s%s%s%s", d.Get("project").(string), COLON_SEPARATED, d.Get("logstore").(string), COLON_SEPARATED, d.Get("name").(string)))
return resourceAlicloudLogtailConfigRead(d, meta)
}
func resourceAlicloudLogtailConfigRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logService := LogService{client}
split := strings.Split(d.Id(), COLON_SEPARATED)
config, err := logService.DescribeLogtailConfig(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
// Because the server will return redundant parameters, we filter here
inputDetail := d.Get("input_detail").(string)
var oMap map[string]interface{}
json.Unmarshal([]byte(inputDetail), &oMap)
nMap := config.InputDetail.(map[string]interface{})
if inputDetail != "" {
for nk := range nMap {
if _, ok := oMap[nk]; !ok {
delete(nMap, nk)
}
}
}
nMapJson, err := json.Marshal(nMap)
if err != nil {
return WrapError(err)
}
d.Set("input_detail", string(nMapJson))
d.Set("project", split[0])
d.Set("name", config.Name)
d.Set("logstore", split[1])
d.Set("input_type", config.InputType)
d.Set("log_sample", config.LogSample)
d.Set("output_type", config.OutputType)
return nil
}
func resourceAlicloudLogtailConfiglUpdate(d *schema.ResourceData, meta interface{}) error {
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
update := false
if d.HasChange("log_sample") {
update = true
}
if d.HasChange("input_detail") {
update = true
}
if d.HasChange("input_type") {
update = true
}
if update {
logconfig := &sls.LogConfig{
InputType: d.Get("input_type").(string),
}
inputConfigInputDetail := make(map[string]interface{})
data := d.Get("input_detail").(string)
conver_err := json.Unmarshal([]byte(data), &inputConfigInputDetail)
if conver_err != nil {
return WrapError(conver_err)
}
sls.AddNecessaryInputConfigField(inputConfigInputDetail)
covertInput, covertErr := assertInputDetailType(inputConfigInputDetail, logconfig)
if covertErr != nil {
return WrapError(covertErr)
}
logconfig.InputDetail = covertInput
client := meta.(*connectivity.AliyunClient)
var requestInfo *sls.Client
params := &sls.LogConfig{
Name: parts[2],
LogSample: d.Get("log_sample").(string),
InputType: d.Get("input_type").(string),
OutputType: d.Get("output_type").(string),
InputDetail: logconfig.InputDetail,
OutputDetail: sls.OutputDetail{
ProjectName: d.Get("project").(string),
LogStoreName: d.Get("logstore").(string),
},
}
raw, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return nil, slsClient.UpdateConfig(parts[0], params)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "UpdateConfig", AliyunLogGoSdkERROR)
}
if debugOn() {
addDebug("UpdateConfig", raw, requestInfo, map[string]interface{}{
"project": parts[0],
"config": params,
})
}
}
return resourceAlicloudLogtailConfigRead(d, meta)
}
func resourceAlicloudLogtailConfigDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
logService := LogService{client}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
var requestInfo *sls.Client
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return nil, slsClient.DeleteConfig(parts[0], parts[2])
})
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout}) {
time.Sleep(5 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if debugOn() {
addDebug("DeleteConfig", raw, requestInfo, map[string]string{
"project": parts[0],
"config": parts[2],
})
}
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ProjectNotExist", "LogStoreNotExist", "ConfigNotExist"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DeleteConfig", AliyunLogGoSdkERROR)
}
return WrapError(logService.WaitForLogtailConfig(d.Id(), Deleted, DefaultTimeout))
}
// This function is used to assert and convert the type to sls.LogConfig
func assertInputDetailType(inputConfigInputDetail map[string]interface{}, logconfig *sls.LogConfig) (sls.InputDetailInterface, error) {
if inputConfigInputDetail["logType"] == "json_log" {
JSONConfigInputDetail, ok := sls.ConvertToJSONConfigInputDetail(inputConfigInputDetail)
if ok != true {
return nil, WrapError(Error("covert to JSONConfigInputDetail false "))
}
logconfig.InputDetail = JSONConfigInputDetail
}
if inputConfigInputDetail["logType"] == "apsara_log" {
ApsaraLogConfigInputDetail, ok := sls.ConvertToApsaraLogConfigInputDetail(inputConfigInputDetail)
if ok != true {
return nil, WrapError(Error("covert to JSONConfigInputDetail false "))
}
logconfig.InputDetail = ApsaraLogConfigInputDetail
}
if inputConfigInputDetail["logType"] == "common_reg_log" {
RegexConfigInputDetail, ok := sls.ConvertToRegexConfigInputDetail(inputConfigInputDetail)
if ok != true {
return nil, WrapError(Error("covert to JSONConfigInputDetail false "))
}
logconfig.InputDetail = RegexConfigInputDetail
}
if inputConfigInputDetail["logType"] == "delimiter_log" {
DelimiterConfigInputDetail, ok := sls.ConvertToDelimiterConfigInputDetail(inputConfigInputDetail)
if ok != true {
return nil, WrapError(Error("covert to JSONConfigInputDetail false "))
}
logconfig.InputDetail = DelimiterConfigInputDetail
}
if logconfig.InputType == "plugin" {
PluginLogConfigInputDetail, ok := sls.ConvertToPluginLogConfigInputDetail(inputConfigInputDetail)
if ok != true {
return nil, WrapError(Error("covert to JSONConfigInputDetail false "))
}
logconfig.InputDetail = PluginLogConfigInputDetail
}
return logconfig.InputDetail, nil
}
package alicloud
import (
"encoding/json"
"fmt"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/services/market"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudMarketOrder() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudMarketOrderCreate,
Read: resourceAlicloudMarketOrderRead,
Delete: resourceAlicloudMarketOrderDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"product_code": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(8, 12),
},
"pay_type": {
Type: schema.TypeString,
Optional: true,
Default: "PostPaid",
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PrePaid", "PostPaid"}, false),
},
"duration": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Default: 1,
ValidateFunc: validation.IntBetween(1, 256),
},
"pricing_cycle": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Day", "Month", "Year"}, false),
},
"package_version": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"quantity": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Default: 1,
},
"coupon_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"components": {
Type: schema.TypeMap,
Optional: true,
Default: map[string]interface{}{},
ForceNew: true,
},
},
}
}
func resourceAlicloudMarketOrderCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request, err := buildAliyunMarketOrderArgs(d, meta)
if err != nil {
return WrapError(err)
}
request.RegionId = client.RegionId
raw, err := client.WithMarketClient(func(marketClient *market.Client) (interface{}, error) {
return marketClient.CreateOrder(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_market_order", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*market.CreateOrderResponse)
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetId(response.OrderId)
return resourceAlicloudMarketOrderRead(d, meta)
}
func resourceAlicloudMarketOrderRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
marketService := MarketService{client}
object, err := marketService.DescribeMarketOrder(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
err = d.Set("product_code", object.ProductCode)
if err != nil {
return WrapError(err)
}
orderPayType := "PostPaid"
if strings.Split(object.ProductSkuCode, "-")[1] == "prepay" {
orderPayType = "PrePaid"
}
err = d.Set("pay_type", orderPayType)
if err != nil {
return WrapError(err)
}
err = d.Set("quantity", object.Quantity)
if err != nil {
return WrapError(err)
}
return nil
}
func resourceAlicloudMarketOrderDelete(d *schema.ResourceData, meta interface{}) error {
return nil
}
func buildAliyunMarketOrderArgs(d *schema.ResourceData, meta interface{}) (*market.CreateOrderRequest, error) {
packageVersion := d.Get("package_version").(string)
couponId := ""
if v, ok := d.GetOk("coupon_id"); ok {
couponId = v.(string)
}
duration := d.Get("duration").(int)
pricingCycle := d.Get("pricing_cycle").(string)
productCode := d.Get("product_code").(string)
quantity := d.Get("quantity").(int)
orderPayType := "postpay"
if d.Get("pay_type").(string) == "PrePaid" {
orderPayType = "prepay"
}
skuCode := fmt.Sprintf("%s-%s", productCode, orderPayType)
components := d.Get("components").(map[string]interface{})
components["package_version"] = packageVersion
componentsJson, _ := json.Marshal(components)
commodity := fmt.Sprintf(`{
"components": %s,
"couponId": "%s",
"duration": %d,
"pricingCycle": "%s",
"productCode": "%s",
"quantity": %d,
"skuCode": "%s"
}`, componentsJson, couponId, duration, pricingCycle, productCode, quantity, skuCode)
request := market.CreateCreateOrderRequest()
request.ClientToken = buildClientToken(request.GetActionName())
request.OrderType = "INSTANCE_BUY"
request.PaymentType = "AUTO"
request.Commodity = commodity
return request, nil
}
package alicloud
import (
"encoding/json"
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudMaxcomputeProject() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudMaxcomputeProjectCreate,
Read: resourceAlicloudMaxcomputeProjectRead,
Delete: resourceAlicloudMaxcomputeProjectDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Delete: schema.DefaultTimeout(2 * time.Minute),
},
Schema: map[string]*schema.Schema{
"order_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo"}, false),
},
"project_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(3, 27),
ConflictsWith: []string{"name"},
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(3, 27),
ConflictsWith: []string{"project_name"},
},
"specification_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"OdpsStandard"}, false),
},
},
}
}
func resourceAlicloudMaxcomputeProjectCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateProject"
request := make(map[string]interface{})
conn, err := client.NewOdpsClient()
if err != nil {
return WrapError(err)
}
request["OrderType"] = d.Get("order_type")
if v, ok := d.GetOk("project_name"); ok {
request["ProjectName"] = v
} else if v, ok := d.GetOk("name"); ok {
request["ProjectName"] = v
} else {
return WrapError(Error(`[ERROR] Argument "name" or "project_name" must be set one!`))
}
request["OdpsRegionId"] = client.RegionId
request["OdpsSpecificationType"] = d.Get("specification_type")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_maxcompute_project", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
return WrapError(Error("CreateProject failed for " + response["Message"].(string)))
}
d.SetId(fmt.Sprint(request["ProjectName"]))
return resourceAlicloudMaxcomputeProjectRead(d, meta)
}
func resourceAlicloudMaxcomputeProjectRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
maxcomputeService := MaxcomputeService{client}
object, err := maxcomputeService.DescribeMaxcomputeProject(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_maxcompute_project maxcomputeService.DescribeMaxcomputeProject Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("project_name", d.Id())
d.Set("name", d.Id())
var data map[string]interface{}
if err := json.Unmarshal([]byte(object["Data"].(string)), &data); err != nil {
return WrapError(Error("%v", object))
}
d.Set("order_type", data["orderType"].(string))
d.Set("name", data["projectName"].(string))
return nil
}
func resourceAlicloudMaxcomputeProjectDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteProject"
var response map[string]interface{}
conn, err := client.NewOdpsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ProjectName": d.Id(),
}
request["RegionIdName"] = client.RegionId
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"500"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if IsExpectedErrorCodes(fmt.Sprintf("%v", response["Code"]), []string{"102", "403"}) {
return nil
}
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
return WrapError(Error("DeleteProject failed for " + response["Message"].(string)))
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudMhubApp() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudMhubAppCreate,
Read: resourceAlicloudMhubAppRead,
Update: resourceAlicloudMhubAppUpdate,
Delete: resourceAlicloudMhubAppDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"app_name": {
Type: schema.TypeString,
Required: true,
},
"product_id": {
Type: schema.TypeString,
Required: true,
},
"bundle_id": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"package_name"},
},
"encoded_icon": {
Type: schema.TypeString,
Optional: true,
},
"industry_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"package_name": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"bundle_id"},
},
"type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"Android", "iOS"}, false),
},
},
}
}
func resourceAlicloudMhubAppCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateApp"
request := make(map[string]interface{})
conn, err := client.NewMhubClient()
if err != nil {
return WrapError(err)
}
request["Name"] = d.Get("app_name")
request["ProductId"] = d.Get("product_id")
if v, ok := d.GetOk("package_name"); ok {
request["PackageName"] = v.(string)
} else if v, ok := d.GetOk("bundle_id"); ok {
request["BundleId"] = v.(string)
} else {
return WrapError(fmt.Errorf("either bundle_id or package_name must be set"))
}
request["Type"] = convertTypeRequest(d.Get("type").(string))
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-08-25"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_mhub_app", action, AlibabaCloudSdkGoERROR)
}
responseAppInfo := response["AppInfo"].(map[string]interface{})
d.SetId(fmt.Sprint(responseAppInfo["ProductId"], ":", responseAppInfo["AppKey"]))
return resourceAlicloudMhubAppUpdate(d, meta)
}
func resourceAlicloudMhubAppRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
mhubService := MhubService{client}
object, err := mhubService.DescribeMhubApp(d.Id())
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_mhub_app mhubService.DescribeMhubApp Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("app_name", object["Name"])
d.Set("bundle_id", object["BundleId"])
d.Set("product_id", parts[0])
d.Set("type", convertTypeResponse(formatInt(object["Type"])))
d.Set("encoded_icon", object["EncodedIcon"])
d.Set("industry_id", fmt.Sprint(formatInt(object["IndustryId"])))
d.Set("package_name", object["PackageName"])
return nil
}
func resourceAlicloudMhubAppUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AppKey": parts[1],
}
if !d.IsNewResource() && d.HasChange("app_name") {
update = true
request["Name"] = d.Get("app_name")
}
if d.HasChange("encoded_icon") {
update = true
if v, ok := d.GetOk("encoded_icon"); ok {
request["EncodedIcon"] = v
}
}
if d.HasChange("industry_id") {
update = true
if v, ok := d.GetOk("industry_id"); ok {
request["IndustryId"] = v
}
}
if update {
action := "ModifyApp"
conn, err := client.NewMhubClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-08-25"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudMhubAppRead(d, meta)
}
func resourceAlicloudMhubAppDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteApp"
var response map[string]interface{}
conn, err := client.NewMhubClient()
if err != nil {
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
request := map[string]interface{}{
"AppKey": parts[1],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-08-25"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func convertTypeResponse(source int) string {
switch source {
case 1:
return "iOS"
case 2:
return "Android"
}
return ""
}
func convertTypeRequest(source string) string {
switch source {
case "iOS":
return "1"
case "Android":
return "2"
}
return source
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudMhubProduct() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudMhubProductCreate,
Read: resourceAlicloudMhubProductRead,
Update: resourceAlicloudMhubProductUpdate,
Delete: resourceAlicloudMhubProductDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"product_name": {
Type: schema.TypeString,
Required: true,
},
},
}
}
func resourceAlicloudMhubProductCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateProduct"
request := make(map[string]interface{})
conn, err := client.NewMhubClient()
if err != nil {
return WrapError(err)
}
request["Name"] = d.Get("product_name")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-08-25"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_mhub_product", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["ProductId"]))
return resourceAlicloudMhubProductRead(d, meta)
}
func resourceAlicloudMhubProductRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
mhubService := MhubService{client}
object, err := mhubService.DescribeMhubProduct(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_mhub_product mhubService.DescribeMhubProduct Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("product_name", object["Name"])
return nil
}
func resourceAlicloudMhubProductUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
request := map[string]interface{}{
"ProductId": d.Id(),
}
if d.HasChange("product_name") {
request["Name"] = d.Get("product_name")
}
action := "ModifyProduct"
conn, err := client.NewMhubClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-08-25"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return resourceAlicloudMhubProductRead(d, meta)
}
func resourceAlicloudMhubProductDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteProduct"
var response map[string]interface{}
conn, err := client.NewMhubClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ProductId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-08-25"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ProductNotExist"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
ali_mns "github.com/aliyun/aliyun-mns-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudMNSQueue() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudMNSQueueCreate,
Read: resourceAlicloudMNSQueueRead,
Update: resourceAlicloudMNSQueueUpdate,
Delete: resourceAlicloudMNSQueueDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(3, 256),
},
"delay_seconds": {
Type: schema.TypeInt,
Optional: true,
Default: 0,
ValidateFunc: validation.IntBetween(0, 604800),
},
"maximum_message_size": {
Type: schema.TypeInt,
Optional: true,
Default: 65536,
ValidateFunc: validation.IntBetween(1024, 65536),
},
"message_retention_period": {
Type: schema.TypeInt,
Optional: true,
Default: 345600,
ValidateFunc: validation.IntBetween(60, 604800),
},
"visibility_timeout": {
Type: schema.TypeInt,
Optional: true,
Default: 30,
ValidateFunc: validation.IntBetween(1, 43200),
},
"polling_wait_seconds": {
Type: schema.TypeInt,
Optional: true,
Default: 0,
ValidateFunc: validation.IntBetween(0, 1800),
},
},
}
}
func resourceAlicloudMNSQueueCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
name := d.Get("name").(string)
var delaySeconds, maximumMessageSize, messageRetentionPeriod, visibilityTimeout, pollingWaitSeconds int
if v, ok := d.GetOk("delay_seconds"); ok {
delaySeconds = v.(int)
}
if v, ok := d.GetOk("maximum_message_size"); ok {
maximumMessageSize = v.(int)
}
if v, ok := d.GetOk("message_retention_period"); ok {
messageRetentionPeriod = v.(int)
}
if v, ok := d.GetOk("visibility_timeout"); ok {
visibilityTimeout = v.(int)
}
if v, ok := d.GetOk("polling_wait_seconds"); ok {
pollingWaitSeconds = v.(int)
}
raw, err := client.WithMnsQueueManager(func(queueManager ali_mns.AliQueueManager) (interface{}, error) {
return nil, queueManager.CreateQueue(name, int32(delaySeconds), int32(maximumMessageSize), int32(messageRetentionPeriod), int32(visibilityTimeout), int32(pollingWaitSeconds), 3)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_mns_queue", "CreateQueue", AliMnsERROR)
}
addDebug("CreateQueue", raw)
d.SetId(name)
return resourceAlicloudMNSQueueRead(d, meta)
}
func resourceAlicloudMNSQueueRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
mnsService := MnsService{client}
object, err := mnsService.DescribeMnsQueue(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", object.QueueName)
d.Set("delay_seconds", object.DelaySeconds)
d.Set("maximum_message_size", object.MaxMessageSize)
d.Set("message_retention_period", object.MessageRetentionPeriod)
d.Set("visibility_timeout", object.VisibilityTimeout)
d.Set("polling_wait_seconds", object.PollingWaitSeconds)
return nil
}
func resourceAlicloudMNSQueueUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
attributeUpdate := false
var delaySeconds, maximumMessageSize, messageRetentionPeriod, visibilityTimeouts, pollingWaitSeconds int
delaySeconds = d.Get("delay_seconds").(int)
maximumMessageSize = d.Get("maximum_message_size").(int)
messageRetentionPeriod = d.Get("message_retention_period").(int)
visibilityTimeouts = d.Get("visibility_timeout").(int)
pollingWaitSeconds = d.Get("polling_wait_seconds").(int)
name := d.Id()
if d.HasChange("delay_seconds") {
attributeUpdate = true
}
if d.HasChange("maximum_message_size") {
attributeUpdate = true
}
if d.HasChange("message_retention_period") {
attributeUpdate = true
}
if d.HasChange("visibility_timeout") {
attributeUpdate = true
}
if d.HasChange("polling_wait_seconds") {
attributeUpdate = true
}
if attributeUpdate {
raw, err := client.WithMnsQueueManager(func(queueManager ali_mns.AliQueueManager) (interface{}, error) {
return nil, queueManager.SetQueueAttributes(name, int32(delaySeconds), int32(maximumMessageSize), int32(messageRetentionPeriod), int32(visibilityTimeouts), int32(pollingWaitSeconds), 3)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "SetQueueAttributes", AliMnsERROR)
}
addDebug("SetQueueAttributes", raw)
}
return resourceAlicloudMNSQueueRead(d, meta)
}
func resourceAlicloudMNSQueueDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
mnsService := MnsService{client}
name := d.Id()
raw, err := client.WithMnsQueueManager(func(queueManager ali_mns.AliQueueManager) (interface{}, error) {
return nil, queueManager.DeleteQueue(name)
})
if err != nil {
if mnsService.QueueNotExistFunc(err) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DeleteQueue", AliMnsERROR)
}
addDebug("DeleteQueue", raw)
return WrapError(mnsService.WaitForMnsQueue(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
ali_mns "github.com/aliyun/aliyun-mns-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudMNSTopic() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudMNSTopicCreate,
Read: resourceAlicloudMNSTopicRead,
Update: resourceAlicloudMNSTopicUpdate,
Delete: resourceAlicloudMNSTopicDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(3, 256),
},
"maximum_message_size": {
Type: schema.TypeInt,
Optional: true,
Default: 65536,
ValidateFunc: validation.IntBetween(1024, 65536),
},
"logging_enabled": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func resourceAlicloudMNSTopicCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
name := d.Get("name").(string)
maximumMessageSize := d.Get("maximum_message_size").(int)
loggingEnabled := d.Get("logging_enabled").(bool)
raw, err := client.WithMnsTopicManager(func(topicManager ali_mns.AliTopicManager) (interface{}, error) {
return nil, topicManager.CreateTopic(name, int32(maximumMessageSize), loggingEnabled)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_mns_topic", "CreateTopic", AliMnsERROR)
}
addDebug("CreateTopic", raw)
d.SetId(name)
return resourceAlicloudMNSTopicRead(d, meta)
}
func resourceAlicloudMNSTopicRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
mnsService := MnsService{client}
object, err := mnsService.DescribeMnsTopic(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", object.TopicName)
d.Set("maximum_message_size", object.MaxMessageSize)
d.Set("logging_enabled", object.LoggingEnabled)
return nil
}
func resourceAlicloudMNSTopicUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
attributeUpdate := false
maximumMessageSize := d.Get("maximum_message_size").(int)
loggingEnabled := d.Get("logging_enabled").(bool)
if d.HasChange("maximum_message_size") {
attributeUpdate = true
}
if d.HasChange("logging_enabled") {
attributeUpdate = true
}
if attributeUpdate {
raw, err := client.WithMnsTopicManager(func(topicManager ali_mns.AliTopicManager) (interface{}, error) {
return nil, topicManager.SetTopicAttributes(d.Id(), int32(maximumMessageSize), loggingEnabled)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "SetTopicAttributes", AliMnsERROR)
}
addDebug("SetTopicAttributes", raw)
}
return resourceAlicloudMNSTopicRead(d, meta)
}
func resourceAlicloudMNSTopicDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
mnsService := MnsService{client}
raw, err := client.WithMnsTopicManager(func(topicManager ali_mns.AliTopicManager) (interface{}, error) {
return nil, topicManager.DeleteTopic(d.Id())
})
if err != nil {
if mnsService.TopicNotExistFunc(err) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DeleteTopic", AliMnsERROR)
}
addDebug("DeleteTopic", raw)
return WrapError(mnsService.WaitForMnsTopic(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
ali_mns "github.com/aliyun/aliyun-mns-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudMNSSubscription() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudMNSSubscriptionCreate,
Read: resourceAlicloudMNSSubscriptionRead,
Update: resourceAlicloudMNSSubscriptionUpdate,
Delete: resourceAlicloudMNSSubscriptionDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"topic_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(3, 256),
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(3, 256),
},
"endpoint": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"filter_tag": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(0, 16),
},
"notify_strategy": {
Type: schema.TypeString,
Optional: true,
Default: string(ali_mns.BACKOFF_RETRY),
ValidateFunc: validation.StringInSlice([]string{
string(ali_mns.BACKOFF_RETRY), string(ali_mns.EXPONENTIAL_DECAY_RETRY),
}, false),
},
"notify_content_format": {
Type: schema.TypeString,
Optional: true,
Default: string(ali_mns.SIMPLIFIED),
ForceNew: true,
},
},
}
}
func resourceAlicloudMNSSubscriptionCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
topicName := d.Get("topic_name").(string)
name := d.Get("name").(string)
endpoint := d.Get("endpoint").(string)
notifyStrategyStr := d.Get("notify_strategy").(string)
notifyContentFormatStr := d.Get("notify_content_format").(string)
var filterTag string
if v, ok := d.GetOk("filter_tag"); ok {
filterTag = v.(string)
}
notifyStrategy := ali_mns.NotifyStrategyType(notifyStrategyStr)
notifyContentFormat := ali_mns.NotifyContentFormatType(notifyContentFormatStr)
subRequest := ali_mns.MessageSubsribeRequest{
Endpoint: endpoint,
FilterTag: filterTag,
NotifyStrategy: notifyStrategy,
NotifyContentFormat: notifyContentFormat,
}
raw, err := client.WithMnsSubscriptionManagerByTopicName(topicName, func(subscriptionManager ali_mns.AliMNSTopic) (interface{}, error) {
return nil, subscriptionManager.Subscribe(name, subRequest)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_mns_topic_subscription", "Subscribe", AliMnsERROR)
}
addDebug("Subscribe", raw)
d.SetId(fmt.Sprintf("%s%s%s", topicName, COLON_SEPARATED, name))
return resourceAlicloudMNSSubscriptionRead(d, meta)
}
func resourceAlicloudMNSSubscriptionRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
mnsService := MnsService{client}
object, err := mnsService.DescribeMnsTopicSubscription(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("topic_name", object.TopicName)
d.Set("name", object.SubscriptionName)
d.Set("endpoint", object.Endpoint)
d.Set("filter_tag", object.FilterTag)
d.Set("notify_strategy", object.NotifyStrategy)
d.Set("notify_content_format", object.NotifyContentFormat)
return nil
}
func resourceAlicloudMNSSubscriptionUpdate(d *schema.ResourceData, meta interface{}) error {
if d.HasChange("notify_strategy") {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
topicName, name := parts[0], parts[1]
notifyStrategy := ali_mns.NotifyStrategyType(d.Get("notify_strategy").(string))
raw, err := client.WithMnsSubscriptionManagerByTopicName(topicName, func(subscriptionManager ali_mns.AliMNSTopic) (interface{}, error) {
return nil, subscriptionManager.SetSubscriptionAttributes(name, notifyStrategy)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "SetSubscriptionAttributes", AliMnsERROR)
}
addDebug("SetSubscriptionAttributes", raw)
}
return resourceAlicloudMNSSubscriptionRead(d, meta)
}
func resourceAlicloudMNSSubscriptionDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
mnsService := MnsService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
topicName, name := parts[0], parts[1]
raw, err := client.WithMnsSubscriptionManagerByTopicName(topicName, func(subscriptionManager ali_mns.AliMNSTopic) (interface{}, error) {
return nil, subscriptionManager.Unsubscribe(name)
})
if err != nil {
if mnsService.TopicNotExistFunc(err) || mnsService.SubscriptionNotExistFunc(err) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "Unsubscribe", AliMnsERROR)
}
addDebug("Unsubscribe", raw)
return WrapError(mnsService.WaitForMnsTopicSubscription(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudMongodbAccount() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudMongodbAccountCreate,
Read: resourceAlicloudMongodbAccountRead,
Update: resourceAlicloudMongodbAccountUpdate,
Delete: resourceAlicloudMongodbAccountDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"account_description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.All(validation.StringDoesNotMatch(regexp.MustCompile(`(^http://.*)|(^https://.*)`), "It cannot begin with \"http://\", \"https://\"."), validation.StringMatch(regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9_-]{1,255}$`), "It must be `2` to `256` characters in length, The description must start with a letter, and can contain letters, digits, underscores (_), and hyphens (-).")),
},
"account_name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"root"}, false),
},
"account_password": {
Type: schema.TypeString,
Required: true,
Sensitive: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`[a-zA-Z!#$%^&*()_+-=]{8,32}`), "account_password must consist of uppercase letters, lowercase letters, numbers, and special characters"),
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudMongodbAccountCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "ResetAccountPassword"
request := make(map[string]interface{})
conn, err := client.NewDdsClient()
if err != nil {
return WrapError(err)
}
request["AccountName"] = d.Get("account_name")
request["AccountPassword"] = d.Get("account_password")
request["DBInstanceId"] = d.Get("instance_id")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_mongodb_account", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["DBInstanceId"], ":", request["AccountName"]))
MongoDBService := MongoDBService{client}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, MongoDBService.MongodbAccountStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudMongodbAccountUpdate(d, meta)
}
func resourceAlicloudMongodbAccountRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
MongoDBService := MongoDBService{client}
object, err := MongoDBService.DescribeMongodbAccount(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_mongodb_account MongoDBService.DescribeMongodbAccount Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("account_name", object["AccountName"])
d.Set("instance_id", object["DBInstanceId"])
d.Set("account_description", object["AccountDescription"])
d.Set("status", object["AccountStatus"])
return nil
}
func resourceAlicloudMongodbAccountUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
MongoDBService := MongoDBService{client}
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Partial(true)
if d.HasChange("account_description") {
request := map[string]interface{}{
"AccountName": parts[1],
"DBInstanceId": parts[0],
}
if v, ok := d.GetOk("account_description"); ok {
request["AccountDescription"] = v
}
action := "ModifyAccountDescription"
conn, err := client.NewDdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, MongoDBService.MongodbAccountStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("account_description")
}
if !d.IsNewResource() && d.HasChange("account_password") {
request := map[string]interface{}{
"AccountName": parts[1],
"DBInstanceId": parts[0],
}
request["AccountPassword"] = d.Get("account_password")
action := "ResetAccountPassword"
conn, err := client.NewDdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, MongoDBService.MongodbAccountStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("account_password")
}
d.Partial(false)
return resourceAlicloudMongodbAccountRead(d, meta)
}
func resourceAlicloudMongodbAccountDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resource Alicloud Mongodb Account. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudMongodbAuditPolicy() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudMongodbAuditPolicyCreate,
Read: resourceAlicloudMongodbAuditPolicyRead,
Update: resourceAlicloudMongodbAuditPolicyUpdate,
Delete: resourceAlicloudMongodbAuditPolicyDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"db_instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"audit_status": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"disabled", "enable"}, false),
},
"storage_period": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(1, 30),
},
},
}
}
func resourceAlicloudMongodbAuditPolicyCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "ModifyAuditPolicy"
request := make(map[string]interface{})
conn, err := client.NewDdsClient()
if err != nil {
return WrapError(err)
}
request["DBInstanceId"] = d.Get("db_instance_id")
request["AuditStatus"] = d.Get("audit_status")
if v, ok := d.GetOk("storage_period"); ok {
request["StoragePeriod"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_mongodb_audit_policy", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["DBInstanceId"]))
return resourceAlicloudMongodbAuditPolicyRead(d, meta)
}
func resourceAlicloudMongodbAuditPolicyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
MongoDBService := MongoDBService{client}
object, err := MongoDBService.DescribeMongodbAuditPolicy(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_mongodb_audit_policy MongoDBService.DescribeMongodbAuditPolicy Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("db_instance_id", d.Id())
d.Set("audit_status", convertMongodbAuditPolicyResponse(object["LogAuditStatus"].(string)))
return nil
}
func resourceAlicloudMongodbAuditPolicyUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"DBInstanceId": d.Id(),
}
request["AuditStatus"] = d.Get("audit_status")
if d.HasChange("audit_status") {
update = true
}
if v, ok := d.GetOk("storage_period"); ok {
request["StoragePeriod"] = v
update = true
}
if update {
action := "ModifyAuditPolicy"
conn, err := client.NewDdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudMongodbAuditPolicyRead(d, meta)
}
func resourceAlicloudMongodbAuditPolicyDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resource Alicloud Mongodb AuditPolicy. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
func convertMongodbAuditPolicyResponse(source string) string {
switch source {
case "Enable":
return "enable"
case "Disabled":
return "disabled"
}
return source
}
package alicloud
import (
"fmt"
"log"
"strconv"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/dds"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudMongoDBInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudMongoDBInstanceCreate,
Read: resourceAlicloudMongoDBInstanceRead,
Update: resourceAlicloudMongoDBInstanceUpdate,
Delete: resourceAlicloudMongoDBInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
Update: schema.DefaultTimeout(30 * time.Minute),
Delete: schema.DefaultTimeout(30 * time.Minute),
},
Schema: map[string]*schema.Schema{
"engine_version": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"db_instance_class": {
Type: schema.TypeString,
Required: true,
},
"db_instance_storage": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(10, 2000),
Required: true,
},
"replication_factor": {
Type: schema.TypeInt,
ValidateFunc: validation.IntInSlice([]int{1, 3, 5, 7}),
Optional: true,
Computed: true,
},
"storage_engine": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"WiredTiger", "RocksDB"}, false),
Optional: true,
Computed: true,
ForceNew: true,
},
"instance_charge_type": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{string(PrePaid), string(PostPaid)}, false),
Optional: true,
Default: PostPaid,
},
"period": {
Type: schema.TypeInt,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 24, 36}),
Optional: true,
Computed: true,
DiffSuppressFunc: PostPaidDiffSuppressFunc,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
Computed: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"security_ip_list": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
Optional: true,
},
"security_group_id": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"account_password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"kms_encrypted_password": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: kmsDiffSuppressFunc,
},
"kms_encryption_context": {
Type: schema.TypeMap,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("kms_encrypted_password").(string) == ""
},
Elem: schema.TypeString,
},
"backup_period": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
Computed: true,
},
"backup_time": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice(BACKUP_TIME, false),
Optional: true,
Computed: true,
},
"ssl_action": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"Open", "Close", "Update"}, false),
Optional: true,
Computed: true,
},
//Computed
"retention_period": {
Type: schema.TypeInt,
Computed: true,
},
"replica_set_name": {
Type: schema.TypeString,
Computed: true,
},
"tde_status": {
Type: schema.TypeString,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return old != "" || d.Get("engine_version").(string) < "4.0"
},
ValidateFunc: validation.StringInSlice([]string{"enabled"}, false),
Optional: true,
},
"maintain_start_time": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"maintain_end_time": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"order_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"UPGRADE", "DOWNGRADE"}, false),
},
"ssl_status": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
"replica_sets": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
"connection_port": {
Type: schema.TypeString,
Computed: true,
},
"replica_set_role": {
Type: schema.TypeString,
Computed: true,
},
"connection_domain": {
Type: schema.TypeString,
Computed: true,
},
"vpc_cloud_instance_id": {
Type: schema.TypeString,
Computed: true,
},
"network_type": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"auto_renew": {
Type: schema.TypeBool,
Optional: true,
},
},
}
}
func buildMongoDBCreateRequest(d *schema.ResourceData, meta interface{}) (*dds.CreateDBInstanceRequest, error) {
client := meta.(*connectivity.AliyunClient)
request := dds.CreateCreateDBInstanceRequest()
request.RegionId = string(client.Region)
request.EngineVersion = Trim(d.Get("engine_version").(string))
request.Engine = "MongoDB"
request.DBInstanceStorage = requests.NewInteger(d.Get("db_instance_storage").(int))
request.DBInstanceClass = Trim(d.Get("db_instance_class").(string))
request.DBInstanceDescription = d.Get("name").(string)
request.AccountPassword = d.Get("account_password").(string)
if request.AccountPassword == "" {
if v := d.Get("kms_encrypted_password").(string); v != "" {
kmsService := KmsService{client}
decryptResp, err := kmsService.Decrypt(v, d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return request, WrapError(err)
}
request.AccountPassword = decryptResp
}
}
request.ZoneId = d.Get("zone_id").(string)
request.StorageEngine = d.Get("storage_engine").(string)
if replication_factor, ok := d.GetOk("replication_factor"); ok {
request.ReplicationFactor = strconv.Itoa(replication_factor.(int))
}
request.NetworkType = string(Classic)
vswitchId := Trim(d.Get("vswitch_id").(string))
if vswitchId != "" {
// check vswitchId in zone
vpcService := VpcService{client}
vsw, err := vpcService.DescribeVSwitch(vswitchId)
if err != nil {
return nil, WrapError(err)
}
if request.ZoneId == "" {
request.ZoneId = vsw.ZoneId
} else if strings.Contains(request.ZoneId, MULTI_IZ_SYMBOL) {
zonestr := strings.Split(strings.SplitAfter(request.ZoneId, "(")[1], ")")[0]
if !strings.Contains(zonestr, string([]byte(vsw.ZoneId)[len(vsw.ZoneId)-1])) {
return nil, WrapError(fmt.Errorf("The specified vswitch %s isn't in the multi zone %s.", vsw.VSwitchId, request.ZoneId))
}
} else if request.ZoneId != vsw.ZoneId {
return nil, WrapError(fmt.Errorf("The specified vswitch %s isn't in the zone %s.", vsw.VSwitchId, request.ZoneId))
}
request.VSwitchId = vswitchId
request.NetworkType = strings.ToUpper(string(Vpc))
request.VpcId = vsw.VpcId
}
request.ChargeType = d.Get("instance_charge_type").(string)
period, ok := d.GetOk("period")
if PayType(request.ChargeType) == PrePaid && ok {
request.Period = requests.NewInteger(period.(int))
}
request.SecurityIPList = LOCAL_HOST_IP
if len(d.Get("security_ip_list").(*schema.Set).List()) > 0 {
request.SecurityIPList = strings.Join(expandStringList(d.Get("security_ip_list").(*schema.Set).List())[:], COMMA_SEPARATED)
}
if v, ok := d.GetOk("auto_renew"); ok {
request.AutoRenew = strconv.FormatBool(v.(bool))
}
request.ClientToken = buildClientToken(request.GetActionName())
return request, nil
}
func resourceAlicloudMongoDBInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ddsService := MongoDBService{client}
request, err := buildMongoDBCreateRequest(d, meta)
if err != nil {
return WrapError(err)
}
raw, err := client.WithDdsClient(func(client *dds.Client) (interface{}, error) {
return client.CreateDBInstance(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_mongodb_instance", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*dds.CreateDBInstanceResponse)
d.SetId(response.DBInstanceId)
stateConf := BuildStateConf([]string{"Creating"}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 1*time.Minute, ddsService.RdsMongodbDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapError(err)
}
return resourceAlicloudMongoDBInstanceUpdate(d, meta)
}
func resourceAlicloudMongoDBInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ddsService := MongoDBService{client}
instance, err := ddsService.DescribeMongoDBInstance(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
if len(instance.ReplicaSets.ReplicaSet) > 0 {
replicaSets := make([]map[string]interface{}, 0)
for _, v := range instance.ReplicaSets.ReplicaSet {
replicaSets = append(replicaSets, map[string]interface{}{
"vswitch_id": v.VSwitchId,
"connection_port": v.ConnectionPort,
"replica_set_role": v.ReplicaSetRole,
"connection_domain": v.ConnectionDomain,
"vpc_cloud_instance_id": v.VPCCloudInstanceId,
"network_type": v.NetworkType,
"vpc_id": v.VPCId,
})
}
d.Set("replica_sets", replicaSets)
}
backupPolicy, err := ddsService.DescribeMongoDBBackupPolicy(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("backup_time", backupPolicy.PreferredBackupTime)
d.Set("backup_period", strings.Split(backupPolicy.PreferredBackupPeriod, ","))
d.Set("retention_period", backupPolicy.BackupRetentionPeriod)
ips, err := ddsService.DescribeMongoDBSecurityIps(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("security_ip_list", ips)
groupIp, err := ddsService.DescribeMongoDBSecurityGroupId(d.Id())
if err != nil {
return WrapError(err)
}
if len(groupIp.Items.RdsEcsSecurityGroupRel) > 0 {
d.Set("security_group_id", groupIp.Items.RdsEcsSecurityGroupRel[0].SecurityGroupId)
}
d.Set("name", instance.DBInstanceDescription)
d.Set("engine_version", instance.EngineVersion)
d.Set("db_instance_class", instance.DBInstanceClass)
d.Set("db_instance_storage", instance.DBInstanceStorage)
d.Set("zone_id", instance.ZoneId)
d.Set("instance_charge_type", instance.ChargeType)
if instance.ChargeType == "PrePaid" {
period, err := computePeriodByUnit(instance.CreationTime, instance.ExpireTime, d.Get("period").(int), "Month")
if err != nil {
return WrapError(err)
}
d.Set("period", period)
}
d.Set("vswitch_id", instance.VSwitchId)
d.Set("storage_engine", instance.StorageEngine)
d.Set("maintain_start_time", instance.MaintainStartTime)
d.Set("maintain_end_time", instance.MaintainEndTime)
d.Set("replica_set_name", instance.ReplicaSetName)
sslAction, err := ddsService.DescribeDBInstanceSSL(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("ssl_status", sslAction.SSLStatus)
if v, err := strconv.Atoi(instance.ReplicationFactor); err != nil {
log.Println(WrapError(err))
} else {
d.Set("replication_factor", v)
}
if instance.ReplicationFactor != "" && instance.ReplicationFactor != "1" {
tdeInfo, err := ddsService.DescribeMongoDBTDEInfo(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("tde_Status", tdeInfo.TDEStatus)
}
d.Set("tags", ddsService.tagsInAttributeToMap(instance.Tags.Tag))
return nil
}
func resourceAlicloudMongoDBInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ddsService := MongoDBService{client}
d.Partial(true)
if !d.IsNewResource() && (d.HasChange("instance_charge_type") && d.Get("instance_charge_type").(string) == "PrePaid") {
prePaidRequest := dds.CreateTransformToPrePaidRequest()
prePaidRequest.InstanceId = d.Id()
prePaidRequest.AutoPay = requests.NewBoolean(true)
prePaidRequest.Period = requests.NewInteger(d.Get("period").(int))
if v, ok := d.GetOk("auto_renew"); ok {
prePaidRequest.AutoRenew = strconv.FormatBool(v.(bool))
}
raw, err := client.WithDdsClient(func(client *dds.Client) (interface{}, error) {
return client.TransformToPrePaid(prePaidRequest)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), prePaidRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(prePaidRequest.GetActionName(), raw, prePaidRequest.RpcRequest, prePaidRequest)
// wait instance status is running after modifying
stateConf := BuildStateConf([]string{"DBInstanceClassChanging", "DBInstanceNetTypeChanging"}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 0, ddsService.RdsMongodbDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapError(err)
}
d.SetPartial("instance_charge_type")
d.SetPartial("period")
}
if d.HasChange("backup_time") || d.HasChange("backup_period") {
if err := ddsService.MotifyMongoDBBackupPolicy(d); err != nil {
return WrapError(err)
}
d.SetPartial("backup_time")
d.SetPartial("backup_period")
}
if d.HasChange("tde_status") {
request := dds.CreateModifyDBInstanceTDERequest()
request.RegionId = client.RegionId
request.DBInstanceId = d.Id()
request.TDEStatus = d.Get("tde_status").(string)
raw, err := client.WithDdsClient(func(client *dds.Client) (interface{}, error) {
return client.ModifyDBInstanceTDE(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("tde_status")
}
if d.HasChange("maintain_start_time") || d.HasChange("maintain_end_time") {
request := dds.CreateModifyDBInstanceMaintainTimeRequest()
request.RegionId = client.RegionId
request.DBInstanceId = d.Id()
request.MaintainStartTime = d.Get("maintain_start_time").(string)
request.MaintainEndTime = d.Get("maintain_end_time").(string)
raw, err := client.WithDdsClient(func(client *dds.Client) (interface{}, error) {
return client.ModifyDBInstanceMaintainTime(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("maintain_start_time")
d.SetPartial("maintain_end_time")
}
if d.HasChange("security_group_id") {
request := dds.CreateModifySecurityGroupConfigurationRequest()
request.RegionId = client.RegionId
request.DBInstanceId = d.Id()
request.SecurityGroupId = d.Get("security_group_id").(string)
wait := incrementalWait(2*time.Second, 3*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
raw, err := client.WithDdsClient(func(client *dds.Client) (interface{}, error) {
return client.ModifySecurityGroupConfiguration(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InstanceStatusInvalid"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("security_group_id")
}
if err := ddsService.setInstanceTags(d); err != nil {
return WrapError(err)
}
if d.IsNewResource() {
d.Partial(false)
return resourceAlicloudMongoDBInstanceRead(d, meta)
}
if d.HasChange("name") {
request := dds.CreateModifyDBInstanceDescriptionRequest()
request.DBInstanceId = d.Id()
request.DBInstanceDescription = d.Get("name").(string)
raw, err := client.WithDdsClient(func(ddsClient *dds.Client) (interface{}, error) {
return ddsClient.ModifyDBInstanceDescription(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("name")
}
if d.HasChange("security_ip_list") {
ipList := expandStringList(d.Get("security_ip_list").(*schema.Set).List())
ipstr := strings.Join(ipList[:], COMMA_SEPARATED)
// default disable connect from outside
if ipstr == "" {
ipstr = LOCAL_HOST_IP
}
if err := ddsService.ModifyMongoDBSecurityIps(d, ipstr); err != nil {
return WrapError(err)
}
d.SetPartial("security_ip_list")
}
if d.HasChange("account_password") || d.HasChange("kms_encrypted_password") {
var accountPassword string
if accountPassword = d.Get("account_password").(string); accountPassword != "" {
d.SetPartial("account_password")
} else if kmsPassword := d.Get("kms_encrypted_password").(string); kmsPassword != "" {
kmsService := KmsService{meta.(*connectivity.AliyunClient)}
decryptResp, err := kmsService.Decrypt(kmsPassword, d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return WrapError(err)
}
accountPassword = decryptResp
d.SetPartial("kms_encrypted_password")
d.SetPartial("kms_encryption_context")
}
err := ddsService.ResetAccountPassword(d, accountPassword)
if err != nil {
return WrapError(err)
}
}
if d.HasChange("ssl_action") {
request := dds.CreateModifyDBInstanceSSLRequest()
request.DBInstanceId = d.Id()
request.RegionId = client.RegionId
request.SSLAction = d.Get("ssl_action").(string)
raw, err := client.WithDdsClient(func(ddsClient *dds.Client) (interface{}, error) {
return ddsClient.ModifyDBInstanceSSL(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("ssl_action")
// wait instance status is running after modifying
stateConf := BuildStateConf([]string{"SSLModifying"}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 0, ddsService.RdsMongodbDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapError(err)
}
}
if d.HasChange("db_instance_storage") ||
d.HasChange("db_instance_class") ||
d.HasChange("replication_factor") {
request := dds.CreateModifyDBInstanceSpecRequest()
request.DBInstanceId = d.Id()
if d.Get("instance_charge_type").(string) == "PrePaid" {
if v, ok := d.GetOk("order_type"); ok {
request.OrderType = v.(string)
}
}
request.DBInstanceClass = d.Get("db_instance_class").(string)
request.DBInstanceStorage = strconv.Itoa(d.Get("db_instance_storage").(int))
request.ReplicationFactor = strconv.Itoa(d.Get("replication_factor").(int))
// wait instance status is running before modifying
stateConf := BuildStateConf([]string{"DBInstanceClassChanging", "DBInstanceNetTypeChanging"}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 1*time.Minute, ddsService.RdsMongodbDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapError(err)
}
raw, err := client.WithDdsClient(func(ddsClient *dds.Client) (interface{}, error) {
return ddsClient.ModifyDBInstanceSpec(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
if _, err := stateConf.WaitForState(); err != nil {
return WrapError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("db_instance_class")
d.SetPartial("db_instance_storage")
d.SetPartial("replication_factor")
// wait instance status is running after modifying
if _, err := stateConf.WaitForState(); err != nil {
return WrapError(err)
}
}
d.Partial(false)
return resourceAlicloudMongoDBInstanceRead(d, meta)
}
func resourceAlicloudMongoDBInstanceDelete(d *schema.ResourceData, meta interface{}) error {
// Pre paid instance can not be release.
if d.Get("instance_charge_type").(string) == string(PrePaid) {
log.Printf("[WARN] Cannot destroy resourceAlicloudMongoDBInstance. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
client := meta.(*connectivity.AliyunClient)
ddsService := MongoDBService{client}
request := dds.CreateDeleteDBInstanceRequest()
request.DBInstanceId = d.Id()
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
raw, err := client.WithDdsClient(func(ddsClient *dds.Client) (interface{}, error) {
return ddsClient.DeleteDBInstance(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound"}) {
return resource.NonRetryableError(err)
}
return resource.RetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"Creating", "Deleting"}, []string{}, d.Timeout(schema.TimeoutDelete), 1*time.Minute, ddsService.RdsMongodbDBInstanceStateRefreshFunc(d.Id(), []string{}))
_, err = stateConf.WaitForState()
return WrapError(err)
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudMongodbServerlessInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudMongodbServerlessInstanceCreate,
Read: resourceAlicloudMongodbServerlessInstanceRead,
Update: resourceAlicloudMongodbServerlessInstanceUpdate,
Delete: resourceAlicloudMongodbServerlessInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"account_password": {
Type: schema.TypeString,
Required: true,
Sensitive: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`[a-zA-Z!#$%^&*()_+-=]{8,32}`), "account_password must consist of uppercase letters, lowercase letters, numbers, and special characters"),
},
"auto_renew": {
Type: schema.TypeBool,
Optional: true,
},
"capacity_unit": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(100, 8000),
},
"db_instance_description": {
Type: schema.TypeString,
Optional: true,
},
"db_instance_storage": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(1, 100),
},
"engine": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"MongoDB"}, false),
},
"engine_version": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"4.2"}, false),
},
"maintain_end_time": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"maintain_start_time": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"period": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 24, 36}),
},
"period_price_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Day", "Month"}, false),
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"security_ip_groups": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"security_ip_group_attribute": {
Type: schema.TypeString,
Optional: true,
},
"security_ip_group_name": {
Type: schema.TypeString,
Optional: true,
},
"security_ip_list": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"storage_engine": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"WiredTiger"}, false),
},
"tags": tagsSchema(),
"vswitch_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"zone_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"vpc_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudMongodbServerlessInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateServerlessDBInstance"
request := make(map[string]interface{})
conn, err := client.NewDdsClient()
if err != nil {
return WrapError(err)
}
request["AccountPassword"] = d.Get("account_password")
if v, ok := d.GetOkExists("auto_renew"); ok {
request["AutoRenew"] = v
}
if v, ok := d.GetOk("db_instance_description"); ok {
request["DBInstanceDescription"] = v
}
request["DBInstanceStorage"] = d.Get("db_instance_storage")
request["CapacityUnit"] = d.Get("capacity_unit")
if v, ok := d.GetOk("engine"); ok {
request["Engine"] = v
}
request["EngineVersion"] = d.Get("engine_version")
if v, ok := d.GetOk("period"); ok {
request["Period"] = v
}
if v, ok := d.GetOk("period_price_type"); ok {
request["PeriodPriceType"] = v
}
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("storage_engine"); ok {
request["StorageEngine"] = v
}
request["ZoneId"] = d.Get("zone_id")
request["VpcId"] = d.Get("vpc_id")
request["VSwitchId"] = d.Get("vswitch_id")
request["RegionId"] = client.RegionId
request["ClientToken"] = buildClientToken("CreateServerlessDBInstance")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_mongodb_serverless_instance", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["DBInstanceId"]))
MongoDBService := MongoDBService{client}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, MongoDBService.MongodbServerlessInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudMongodbServerlessInstanceUpdate(d, meta)
}
func resourceAlicloudMongodbServerlessInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
mongoDBService := MongoDBService{client}
object, err := mongoDBService.DescribeMongodbServerlessInstance(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_mongodb_serverless_instance MongoDBService.DescribeMongodbServerlessInstance Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("capacity_unit", formatInt(object["CapacityUnit"]))
d.Set("db_instance_description", object["DBInstanceDescription"])
if v, ok := object["DBInstanceStorage"]; ok && fmt.Sprint(v) != "0" {
d.Set("db_instance_storage", formatInt(v))
}
d.Set("engine", object["Engine"])
d.Set("engine_version", object["EngineVersion"])
d.Set("maintain_end_time", object["MaintainEndTime"])
d.Set("maintain_start_time", object["MaintainStartTime"])
d.Set("resource_group_id", object["ResourceGroupId"])
d.Set("status", object["DBInstanceStatus"])
d.Set("storage_engine", convertMongodbServerlessInstanceStorageEngineResponse(object["StorageEngine"].(string)))
listTagResourcesObject, err := mongoDBService.ListTagResources(d.Id(), "INSTANCE")
if err != nil {
return WrapError(err)
}
d.Set("tags", tagsToMap(listTagResourcesObject))
d.Set("vswitch_id", object["VSwitchId"])
d.Set("zone_id", object["ZoneId"])
d.Set("vpc_id", object["VPCId"])
securityIpGroupsObject, err := mongoDBService.DescribeSecurityIps(d.Id())
if err != nil {
return WrapError(err)
}
if securityIpGroupsMap, ok := securityIpGroupsObject["SecurityIpGroups"].(map[string]interface{}); ok && securityIpGroupsMap != nil {
if securityIpGroup, ok := securityIpGroupsMap["SecurityIpGroup"]; ok && securityIpGroup != nil {
securityIpGroupMaps := make([]map[string]interface{}, 0)
for _, iPArrayListItem := range securityIpGroup.([]interface{}) {
if v, ok := iPArrayListItem.(map[string]interface{}); ok {
if v["SecurityIpGroupName"].(string) == "default" {
continue
}
iPArrayListItemMap := make(map[string]interface{})
iPArrayListItemMap["security_ip_group_attribute"] = v["SecurityIpGroupAttribute"]
iPArrayListItemMap["security_ip_group_name"] = v["SecurityIpGroupName"]
iPArrayListItemMap["security_ip_list"] = v["SecurityIpList"]
securityIpGroupMaps = append(securityIpGroupMaps, iPArrayListItemMap)
}
}
d.Set("security_ip_groups", securityIpGroupMaps)
}
}
return nil
}
func resourceAlicloudMongodbServerlessInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
MongoDBService := MongoDBService{client}
var response map[string]interface{}
d.Partial(true)
if d.HasChange("tags") {
if err := MongoDBService.SetResourceTags(d, "INSTANCE"); err != nil {
return WrapError(err)
}
}
if !d.IsNewResource() && d.HasChange("db_instance_description") {
request := map[string]interface{}{
"DBInstanceId": d.Id(),
}
if v, ok := d.GetOk("db_instance_description"); ok {
request["DBInstanceDescription"] = v
}
action := "ModifyDBInstanceDescription"
conn, err := client.NewDdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("db_instance_description")
}
if d.HasChange("maintain_end_time") || d.HasChange("maintain_start_time") {
request := map[string]interface{}{
"DBInstanceId": d.Id(),
}
request["MaintainStartTime"] = d.Get("maintain_start_time")
request["MaintainEndTime"] = d.Get("maintain_end_time")
action := "ModifyDBInstanceMaintainTime"
conn, err := client.NewDdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("maintain_end_time")
d.SetPartial("maintain_start_time")
}
if d.HasChange("security_ip_groups") {
oraw, nraw := d.GetChange("security_ip_groups")
remove := oraw.(*schema.Set).Difference(nraw.(*schema.Set)).List()
create := nraw.(*schema.Set).Difference(oraw.(*schema.Set)).List()
if len(remove) > 0 {
removeSecurityIpsReq := map[string]interface{}{
"DBInstanceId": d.Id(),
"ModifyMode": "Delete",
}
for _, whiteList := range remove {
whiteListArg := whiteList.(map[string]interface{})
removeSecurityIpsReq["SecurityIpGroupAttribute"] = whiteListArg["security_ip_group_attribute"]
removeSecurityIpsReq["SecurityIpGroupName"] = whiteListArg["security_ip_group_name"]
removeSecurityIpsReq["SecurityIps"] = whiteListArg["security_ip_list"]
action := "ModifySecurityIps"
conn, err := client.NewDdsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, removeSecurityIpsReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, removeSecurityIpsReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
}
if len(create) > 0 {
createSecurityIpsReq := map[string]interface{}{
"DBInstanceId": d.Id(),
"ModifyMode": "Append",
}
for _, whiteList := range create {
whiteListArg := whiteList.(map[string]interface{})
createSecurityIpsReq["SecurityIpGroupAttribute"] = whiteListArg["security_ip_group_attribute"]
createSecurityIpsReq["SecurityIpGroupName"] = whiteListArg["security_ip_group_name"]
createSecurityIpsReq["SecurityIps"] = whiteListArg["security_ip_list"]
action := "ModifySecurityIps"
conn, err := client.NewDdsClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, createSecurityIpsReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, createSecurityIpsReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
}
d.SetPartial("security_ip_groups")
}
if !d.IsNewResource() && (d.HasChange("db_instance_storage") || d.HasChange("capacity_unit")) {
request := map[string]interface{}{
"DBInstanceId": d.Id(),
}
if v, ok := d.GetOk("capacity_unit"); ok {
request["DBInstanceClass"] = v
}
if v, ok := d.GetOk("db_instance_storage"); ok {
request["DBInstanceStorage"] = v
}
action := "ModifyDBInstanceSpec"
conn, err := client.NewDdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, MongoDBService.MongodbServerlessInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("capacity_unit")
d.SetPartial("db_instance_storage")
}
d.Partial(false)
return resourceAlicloudMongodbServerlessInstanceRead(d, meta)
}
func resourceAlicloudMongodbServerlessInstanceDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resource Alicloud Resource Mongodb Serverless Subscription Instance. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
func convertMongodbServerlessInstancePayTypeResponse(source string) string {
switch source {
case "PrePaid":
return "Subscription"
}
return source
}
func convertMongodbServerlessInstanceStorageEngineResponse(source string) string {
switch source {
case "wiredTiger":
return "WiredTiger"
}
return source
}
package alicloud
import (
"log"
"strconv"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/dds"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudMongoDBShardingInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudMongoDBShardingInstanceCreate,
Read: resourceAlicloudMongoDBShardingInstanceRead,
Update: resourceAlicloudMongoDBShardingInstanceUpdate,
Delete: resourceAlicloudMongoDBShardingInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
Update: schema.DefaultTimeout(30 * time.Minute),
Delete: schema.DefaultTimeout(30 * time.Minute),
},
Schema: map[string]*schema.Schema{
"engine_version": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"storage_engine": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"WiredTiger", "RocksDB"}, false),
Optional: true,
Computed: true,
ForceNew: true,
},
"instance_charge_type": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{string(PrePaid), string(PostPaid)}, false),
Optional: true,
Computed: true,
},
"period": {
Type: schema.TypeInt,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 24, 36}),
Optional: true,
Computed: true,
DiffSuppressFunc: PostPaidDiffSuppressFunc,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vswitch_id": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"security_ip_list": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
Optional: true,
},
"security_group_id": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"account_password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"kms_encrypted_password": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: kmsDiffSuppressFunc,
},
"kms_encryption_context": {
Type: schema.TypeMap,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("kms_encrypted_password").(string) == ""
},
Elem: schema.TypeString,
},
"tde_status": {
Type: schema.TypeString,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return old != "" || d.Get("engine_version").(string) < "4.0"
},
ValidateFunc: validation.StringInSlice([]string{"enabled"}, false),
Optional: true,
ForceNew: true,
},
"backup_period": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
Computed: true,
},
"backup_time": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice(BACKUP_TIME, false),
Optional: true,
Computed: true,
},
"retention_period": {
Type: schema.TypeInt,
Computed: true,
},
"shard_list": {
Type: schema.TypeList,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"node_class": {
Type: schema.TypeString,
Required: true,
},
"node_storage": {
Type: schema.TypeInt,
Required: true,
},
"readonly_replicas": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(0, 5),
Computed: true,
},
//Computed
"node_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
Required: true,
MinItems: 2,
MaxItems: 32,
},
"mongo_list": {
Type: schema.TypeList,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"node_class": {
Type: schema.TypeString,
Required: true,
},
//Computed
"node_id": {
Type: schema.TypeString,
Computed: true,
},
"connect_string": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeInt,
Computed: true,
},
},
},
Required: true,
MinItems: 2,
MaxItems: 32,
},
"order_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"UPGRADE", "DOWNGRADE"}, false),
},
"tags": tagsSchema(),
"auto_renew": {
Type: schema.TypeBool,
Optional: true,
},
"config_server_list": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"max_iops": {
Type: schema.TypeInt,
Computed: true,
},
"connect_string": {
Type: schema.TypeString,
Computed: true,
},
"node_class": {
Type: schema.TypeString,
Computed: true,
},
"max_connections": {
Type: schema.TypeInt,
Computed: true,
},
"port": {
Type: schema.TypeInt,
Computed: true,
},
"node_description": {
Type: schema.TypeString,
Computed: true,
},
"node_id": {
Type: schema.TypeString,
Computed: true,
},
"node_storage": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}
func buildMongoDBShardingCreateRequest(d *schema.ResourceData, meta interface{}) (*dds.CreateShardingDBInstanceRequest, error) {
client := meta.(*connectivity.AliyunClient)
request := dds.CreateCreateShardingDBInstanceRequest()
request.RegionId = string(client.Region)
request.EngineVersion = Trim(d.Get("engine_version").(string))
request.Engine = "MongoDB"
request.DBInstanceDescription = d.Get("name").(string)
request.AccountPassword = d.Get("account_password").(string)
if request.AccountPassword == "" {
if v := d.Get("kms_encrypted_password").(string); v != "" {
kmsService := KmsService{client}
decryptResp, err := kmsService.Decrypt(v, d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return request, WrapError(err)
}
request.AccountPassword = decryptResp
}
}
request.ZoneId = d.Get("zone_id").(string)
shardList, ok := d.GetOk("shard_list")
if ok {
replicaSets := []dds.CreateShardingDBInstanceReplicaSet{}
for _, rew := range shardList.([]interface{}) {
item := rew.(map[string]interface{})
readonlyReplicas := 0
if item["readonly_replicas"] != nil {
readonlyReplicas = item["readonly_replicas"].(int)
}
class := item["node_class"].(string)
nodeStorage := item["node_storage"].(int)
replicaSets = append(replicaSets, dds.CreateShardingDBInstanceReplicaSet{ReadonlyReplicas: strconv.Itoa(readonlyReplicas), Storage: strconv.Itoa(nodeStorage), Class: class})
}
request.ReplicaSet = &replicaSets
}
mongoList, ok := d.GetOk("mongo_list")
if ok {
mongos := []dds.CreateShardingDBInstanceMongos{}
for _, rew := range mongoList.([]interface{}) {
item := rew.(map[string]interface{})
class := item["node_class"].(string)
mongos = append(mongos, dds.CreateShardingDBInstanceMongos{Class: class})
}
request.Mongos = &mongos
}
request.ConfigServer = &[]dds.CreateShardingDBInstanceConfigServer{{Storage: "20", Class: "dds.cs.mid"}}
request.NetworkType = string(Classic)
vswitchId := Trim(d.Get("vswitch_id").(string))
if vswitchId != "" {
// check vswitchId in zone
vpcService := VpcService{client}
vsw, err := vpcService.DescribeVSwitch(vswitchId)
if err != nil {
return nil, WrapError(err)
}
if request.ZoneId == "" {
request.ZoneId = vsw.ZoneId
} else if strings.Contains(request.ZoneId, MULTI_IZ_SYMBOL) {
zonestr := strings.Split(strings.SplitAfter(request.ZoneId, "(")[1], ")")[0]
if !strings.Contains(zonestr, string([]byte(vsw.ZoneId)[len(vsw.ZoneId)-1])) {
return nil, WrapError(Error("The specified vswitch " + vsw.VSwitchId + " isn't in multi the zone " + request.ZoneId))
}
} else if request.ZoneId != vsw.ZoneId {
return nil, WrapError(Error("The specified vswitch " + vsw.VSwitchId + " isn't in the zone " + request.ZoneId))
}
request.VSwitchId = vswitchId
request.NetworkType = strings.ToUpper(string(Vpc))
request.VpcId = vsw.VpcId
}
request.ChargeType = d.Get("instance_charge_type").(string)
period, ok := d.GetOk("period")
if ok && PayType(request.ChargeType) == PrePaid {
request.Period = requests.NewInteger(period.(int))
}
request.SecurityIPList = LOCAL_HOST_IP
if len(d.Get("security_ip_list").(*schema.Set).List()) > 0 {
request.SecurityIPList = strings.Join(expandStringList(d.Get("security_ip_list").(*schema.Set).List()), COMMA_SEPARATED)
}
if v, ok := d.GetOk("auto_renew"); ok {
request.AutoRenew = strconv.FormatBool(v.(bool))
}
request.ClientToken = buildClientToken(request.GetActionName())
return request, nil
}
func resourceAlicloudMongoDBShardingInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ddsService := MongoDBService{client}
request, err := buildMongoDBShardingCreateRequest(d, meta)
if err != nil {
return WrapError(err)
}
raw, err := client.WithDdsClient(func(client *dds.Client) (interface{}, error) {
return client.CreateShardingDBInstance(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_mongodb_sharding_instance", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*dds.CreateShardingDBInstanceResponse)
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetId(response.DBInstanceId)
stateConf := BuildStateConf([]string{"Creating"}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 5*time.Minute, ddsService.RdsMongodbDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapError(err)
}
return resourceAlicloudMongoDBShardingInstanceUpdate(d, meta)
}
func resourceAlicloudMongoDBShardingInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ddsService := MongoDBService{client}
instance, err := ddsService.DescribeMongoDBInstance(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
backupPolicy, err := ddsService.DescribeMongoDBBackupPolicy(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("backup_time", backupPolicy.PreferredBackupTime)
d.Set("backup_period", strings.Split(backupPolicy.PreferredBackupPeriod, ","))
d.Set("retention_period", backupPolicy.BackupRetentionPeriod)
d.Set("name", instance.DBInstanceDescription)
d.Set("engine_version", instance.EngineVersion)
d.Set("storage_engine", instance.StorageEngine)
d.Set("zone_id", instance.ZoneId)
d.Set("instance_charge_type", instance.ChargeType)
if instance.ChargeType == "PrePaid" {
period, err := computePeriodByUnit(instance.CreationTime, instance.ExpireTime, d.Get("period").(int), "Month")
if err != nil {
return WrapError(err)
}
d.Set("period", period)
}
d.Set("vswitch_id", instance.VSwitchId)
mongosList := []map[string]interface{}{}
for _, item := range instance.MongosList.MongosAttribute {
mongo := map[string]interface{}{
"node_class": item.NodeClass,
"node_id": item.NodeId,
"port": item.Port,
"connect_string": item.ConnectSting,
}
mongosList = append(mongosList, mongo)
}
err = d.Set("mongo_list", mongosList)
if err != nil {
return WrapError(err)
}
shardList := []map[string]interface{}{}
for _, item := range instance.ShardList.ShardAttribute {
shard := map[string]interface{}{
"node_id": item.NodeId,
"node_storage": item.NodeStorage,
"node_class": item.NodeClass,
"readonly_replicas": item.ReadonlyReplicas,
}
shardList = append(shardList, shard)
}
err = d.Set("shard_list", shardList)
if err != nil {
return WrapError(err)
}
tdeInfo, err := ddsService.DescribeMongoDBTDEInfo(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("tde_Status", tdeInfo.TDEStatus)
ips, err := ddsService.DescribeMongoDBSecurityIps(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("security_ip_list", ips)
groupIp, err := ddsService.DescribeMongoDBSecurityGroupId(d.Id())
if err != nil {
return WrapError(err)
}
if len(groupIp.Items.RdsEcsSecurityGroupRel) > 0 {
d.Set("security_group_id", groupIp.Items.RdsEcsSecurityGroupRel[0].SecurityGroupId)
}
d.Set("tags", ddsService.tagsInAttributeToMap(instance.Tags.Tag))
configServerSets := make([]map[string]interface{}, 0)
for _, v := range instance.ConfigserverList.ConfigserverAttribute {
configServerSets = append(configServerSets, map[string]interface{}{
"max_iops": v.MaxIOPS,
"connect_string": v.ConnectString,
"node_class": v.NodeClass,
"max_connections": v.MaxConnections,
"port": v.Port,
"node_description": v.NodeDescription,
"node_id": v.NodeId,
"node_storage": v.NodeStorage,
})
}
err = d.Set("config_server_list", configServerSets)
return nil
}
func resourceAlicloudMongoDBShardingInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ddsService := MongoDBService{client}
d.Partial(true)
if d.HasChange("backup_time") || d.HasChange("backup_period") {
if err := ddsService.MotifyMongoDBBackupPolicy(d); err != nil {
return WrapError(err)
}
d.SetPartial("backup_time")
d.SetPartial("backup_period")
}
if d.HasChange("tde_status") {
request := dds.CreateModifyDBInstanceTDERequest()
request.RegionId = client.RegionId
request.DBInstanceId = d.Id()
request.TDEStatus = d.Get("tde_status").(string)
raw, err := client.WithDdsClient(func(client *dds.Client) (interface{}, error) {
return client.ModifyDBInstanceTDE(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("tde_status")
}
if d.HasChange("security_group_id") {
request := dds.CreateModifySecurityGroupConfigurationRequest()
request.RegionId = client.RegionId
request.DBInstanceId = d.Id()
request.SecurityGroupId = d.Get("security_group_id").(string)
wait := incrementalWait(2*time.Second, 3*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
raw, err := client.WithDdsClient(func(client *dds.Client) (interface{}, error) {
return client.ModifySecurityGroupConfiguration(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InstanceStatusInvalid"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("security_group_id")
}
if err := ddsService.setInstanceTags(d); err != nil {
return WrapError(err)
}
if d.IsNewResource() {
d.Partial(false)
return resourceAlicloudMongoDBShardingInstanceRead(d, meta)
}
if d.HasChange("shard_list") {
state, diff := d.GetChange("shard_list")
err := ddsService.ModifyMongodbShardingInstanceNode(d, MongoDBShardingNodeShard, state.([]interface{}), diff.([]interface{}))
if err != nil {
return WrapError(err)
}
d.SetPartial("shard_list")
}
if d.HasChange("mongo_list") {
state, diff := d.GetChange("mongo_list")
err := ddsService.ModifyMongodbShardingInstanceNode(d, MongoDBShardingNodeMongos, state.([]interface{}), diff.([]interface{}))
if err != nil {
return WrapError(err)
}
d.SetPartial("mongo_list")
}
if d.HasChange("name") {
request := dds.CreateModifyDBInstanceDescriptionRequest()
request.RegionId = client.RegionId
request.DBInstanceId = d.Id()
request.DBInstanceDescription = d.Get("name").(string)
raw, err := client.WithDdsClient(func(ddsClient *dds.Client) (interface{}, error) {
return ddsClient.ModifyDBInstanceDescription(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("name")
}
if d.HasChange("account_password") || d.HasChange("kms_encrypted_password") {
var accountPassword string
if accountPassword = d.Get("account_password").(string); accountPassword != "" {
d.SetPartial("account_password")
} else if kmsPassword := d.Get("kms_encrypted_password").(string); kmsPassword != "" {
kmsService := KmsService{meta.(*connectivity.AliyunClient)}
decryptResp, err := kmsService.Decrypt(kmsPassword, d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return WrapError(err)
}
accountPassword = decryptResp
d.SetPartial("kms_encrypted_password")
d.SetPartial("kms_encryption_context")
}
err := ddsService.ResetAccountPassword(d, accountPassword)
if err != nil {
return WrapError(err)
}
d.SetPartial("account_password")
}
if d.HasChange("security_ip_list") {
ipList := expandStringList(d.Get("security_ip_list").(*schema.Set).List())
ipstr := strings.Join(ipList[:], COMMA_SEPARATED)
// default disable connect from outside
if ipstr == "" {
ipstr = LOCAL_HOST_IP
}
if err := ddsService.ModifyMongoDBSecurityIps(d, ipstr); err != nil {
return WrapError(err)
}
d.SetPartial("security_ip_list")
}
if !d.IsNewResource() && (d.HasChange("instance_charge_type") && d.Get("instance_charge_type").(string) == "PrePaid") {
prePaidRequest := dds.CreateTransformToPrePaidRequest()
prePaidRequest.InstanceId = d.Id()
prePaidRequest.AutoPay = requests.NewBoolean(true)
prePaidRequest.Period = requests.NewInteger(d.Get("period").(int))
if v, ok := d.GetOk("auto_renew"); ok {
prePaidRequest.AutoRenew = strconv.FormatBool(v.(bool))
}
raw, err := client.WithDdsClient(func(client *dds.Client) (interface{}, error) {
return client.TransformToPrePaid(prePaidRequest)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), prePaidRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(prePaidRequest.GetActionName(), raw, prePaidRequest.RpcRequest, prePaidRequest)
// wait instance status is running after modifying
stateConf := BuildStateConf([]string{"DBInstanceClassChanging", "DBInstanceNetTypeChanging"}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 0, ddsService.RdsMongodbDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapError(err)
}
d.SetPartial("instance_charge_type")
d.SetPartial("period")
}
d.Partial(false)
return resourceAlicloudMongoDBShardingInstanceRead(d, meta)
}
func resourceAlicloudMongoDBShardingInstanceDelete(d *schema.ResourceData, meta interface{}) error {
if d.Get("instance_charge_type").(string) == string(PrePaid) {
log.Printf("[WARN] Cannot destroy resourceAlicloudMongoDBShardingInstance. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
client := meta.(*connectivity.AliyunClient)
ddsService := MongoDBService{client}
request := dds.CreateDeleteDBInstanceRequest()
request.RegionId = client.RegionId
request.DBInstanceId = d.Id()
err := resource.Retry(10*5*time.Minute, func() *resource.RetryError {
raw, err := client.WithDdsClient(func(ddsClient *dds.Client) (interface{}, error) {
return ddsClient.DeleteDBInstance(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound"}) {
return resource.NonRetryableError(err)
}
return resource.RetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"Creating", "Deleting"}, []string{}, d.Timeout(schema.TimeoutDelete), 1*time.Minute, ddsService.RdsMongodbDBInstanceStateRefreshFunc(d.Id(), []string{}))
_, err = stateConf.WaitForState()
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudMongodbShardingNetworkPublicAddress() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudMongodbShardingNetworkPublicAddressCreate,
Read: resourceAlicloudMongodbShardingNetworkPublicAddressRead,
Delete: resourceAlicloudMongodbShardingNetworkPublicAddressDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
Delete: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"db_instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"node_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"network_address": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"expired_time": {
Type: schema.TypeString,
Computed: true,
},
"ip_address": {
Type: schema.TypeString,
Computed: true,
},
"network_address": {
Type: schema.TypeString,
Computed: true,
},
"network_type": {
Type: schema.TypeString,
Computed: true,
},
"node_id": {
Type: schema.TypeString,
Computed: true,
},
"node_type": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeString,
Computed: true,
},
"role": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}
func resourceAlicloudMongodbShardingNetworkPublicAddressCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AllocatePublicNetworkAddress"
request := make(map[string]interface{})
conn, err := client.NewDdsClient()
if err != nil {
return WrapError(err)
}
request["DBInstanceId"] = d.Get("db_instance_id")
request["NodeId"] = d.Get("node_id")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_mongodb_sharding_network_public_address", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["DBInstanceId"], ":", request["NodeId"]))
MongoDBService := MongoDBService{client}
nodeType, err := MongoDBService.DescribeShardingNodeType(d.Id())
if err != nil {
return WrapError(err)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, MongoDBService.MongodbShardingNetworkPublicAddressStateRefreshFunc(d.Id(), nodeType, []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudMongodbShardingNetworkPublicAddressRead(d, meta)
}
func resourceAlicloudMongodbShardingNetworkPublicAddressRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
MongoDBService := MongoDBService{client}
object, err := MongoDBService.DescribeMongodbShardingNetworkPublicAddress(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_mongodb_sharding_network_public_address MongoDBService.DescribeMongodbShardingNetworkPublicAddress Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("db_instance_id", parts[0])
d.Set("node_id", parts[1])
s := make([]map[string]interface{}, 0)
for _, item := range object["NetworkAddress"].([]map[string]interface{}) {
mapping := map[string]interface{}{
"expired_time": item["ExpiredTime"],
"ip_address": item["IPAddress"],
"network_address": item["NetworkAddress"],
"network_type": item["NetworkType"],
"node_type": item["NodeType"],
"port": item["Port"],
"role": item["Role"],
"vpc_id": item["VPCId"],
"vswitch_id": item["VswitchId"],
"node_id": parts[1],
}
s = append(s, mapping)
}
d.Set("network_address", s)
return nil
}
func resourceAlicloudMongodbShardingNetworkPublicAddressDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "ReleasePublicNetworkAddress"
var response map[string]interface{}
conn, err := client.NewDdsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DBInstanceId": parts[0],
"NodeId": parts[1],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
MongoDBService := MongoDBService{client}
nodeType, err := MongoDBService.DescribeShardingNodeType(d.Id())
if err != nil {
return WrapError(err)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutDelete), 5*time.Second, MongoDBService.MongodbShardingNetworkPublicAddressStateRefreshFunc(d.Id(), nodeType, []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudMscSubContact() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudMscSubContactCreate,
Read: resourceAlicloudMscSubContactRead,
Update: resourceAlicloudMscSubContactUpdate,
Delete: resourceAlicloudMscSubContactDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"contact_name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile("^[\u4E00-\u9FA5a-zA-Z]{2,12}$"), "The name must be 2 to 12 characters in length."),
},
"email": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$`), "The email must has correct format."),
},
"mobile": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[0-9]+$`), "The mobile only has digit."),
},
"position": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"CEO", "Finance Director", "Maintenance Director", "Other", "Project Director", "Technical Director"}, false),
},
},
}
}
func resourceAlicloudMscSubContactCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateContact"
request := make(map[string]interface{})
conn, err := client.NewMscopensubscriptionClient()
if err != nil {
return WrapError(err)
}
request["ContactName"] = d.Get("contact_name")
request["Email"] = d.Get("email")
request["Mobile"] = d.Get("mobile")
request["Position"] = d.Get("position")
request["ClientToken"] = buildClientToken("CreateContact")
request["Locale"] = "en"
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-07-13"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_msc_sub_contact", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetId(fmt.Sprint(formatInt(response["ContactId"])))
return resourceAlicloudMscSubContactRead(d, meta)
}
func resourceAlicloudMscSubContactRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
mscOpenSubscriptionService := MscOpenSubscriptionService{client}
object, err := mscOpenSubscriptionService.DescribeMscSubContact(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_msc_sub_contact mscOpenSubscriptionService.DescribeMscSubContact Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("contact_name", object["ContactName"])
d.Set("email", object["Email"])
d.Set("mobile", object["Mobile"])
d.Set("position", convertMscSubContactPositionResponse(fmt.Sprint(object["Position"])))
return nil
}
func resourceAlicloudMscSubContactUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"ContactId": d.Id(),
}
if d.HasChange("contact_name") {
update = true
}
request["ContactName"] = d.Get("contact_name")
if d.HasChange("email") {
update = true
}
request["Email"] = d.Get("email")
if d.HasChange("mobile") {
update = true
}
request["Mobile"] = d.Get("mobile")
if update {
action := "UpdateContact"
conn, err := client.NewMscopensubscriptionClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("UpdateContact")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-07-13"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
}
return resourceAlicloudMscSubContactRead(d, meta)
}
func resourceAlicloudMscSubContactDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteContact"
var response map[string]interface{}
conn, err := client.NewMscopensubscriptionClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ContactId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-07-13"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if IsExpectedErrors(err, []string{"ResourceNotFound"}) {
return nil
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
return nil
}
func convertMscSubContactPositionResponse(source string) string {
switch source {
case "Others":
return "Other"
}
return source
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudMscSubSubscription() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudMscSubSubscriptionCreate,
Read: resourceAlicloudMscSubSubscriptionRead,
Update: resourceAlicloudMscSubSubscriptionUpdate,
Delete: resourceAlicloudMscSubSubscriptionDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"channel": {
Type: schema.TypeString,
Computed: true,
},
"contact_ids": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"email_status": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{-1, -2, 0, 1}),
},
"item_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"pmsg_status": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{-1, -2, 0, 1}),
},
"sms_status": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{-1, -2, 0, 1}),
},
"tts_status": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{-1, -2, 0, 1}),
},
"webhook_ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"webhook_status": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{-1, -2, 0, 1}),
},
},
}
}
func resourceAlicloudMscSubSubscriptionCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateSubscriptionItem"
request := make(map[string]interface{})
conn, err := client.NewMscopensubscriptionClient()
if err != nil {
return WrapError(err)
}
request["ItemName"] = d.Get("item_name")
request["Locale"] = "en"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-07-13"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_msc_sub_subscription", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
responseSubscriptionItem := response["SubscriptionItem"].(map[string]interface{})
d.SetId(fmt.Sprint(responseSubscriptionItem["ItemId"]))
return resourceAlicloudMscSubSubscriptionUpdate(d, meta)
}
func resourceAlicloudMscSubSubscriptionRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
mscOpenSubscriptionService := MscOpenSubscriptionService{client}
object, err := mscOpenSubscriptionService.DescribeMscSubSubscription(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_msc_sub_subscription mscOpenSubscriptionService.DescribeMscSubSubscription Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("channel", object["Channel"])
if contactIds, ok := object["ContactIds"]; ok && contactIds != nil {
d.Set("contact_ids", convertJsonStringToStringList(contactIds))
}
d.Set("description", object["Description"])
if v, ok := object["EmailStatus"]; ok {
d.Set("email_status", formatInt(v))
}
d.Set("item_name", object["ItemName"])
if v, ok := object["PmsgStatus"]; ok {
d.Set("pmsg_status", formatInt(v))
}
if v, ok := object["SmsStatus"]; ok {
d.Set("sms_status", formatInt(v))
}
if v, ok := object["TtsStatus"]; ok {
d.Set("tts_status", formatInt(v))
}
if webhookIds, ok := object["WebhookIds"]; ok && webhookIds != nil {
d.Set("webhook_ids", convertJsonStringToStringList(webhookIds))
}
if v, ok := object["WebhookStatus"]; ok {
d.Set("webhook_status", formatInt(v))
}
return nil
}
func resourceAlicloudMscSubSubscriptionUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"ItemId": d.Id(),
}
if d.HasChange("email_status") {
update = true
}
if v, ok := d.GetOkExists("email_status"); ok {
request["EmailStatus"] = v
}
if d.HasChange("pmsg_status") {
update = true
}
if v, ok := d.GetOkExists("pmsg_status"); ok {
request["PmsgStatus"] = v
}
if d.HasChange("sms_status") {
update = true
}
if v, ok := d.GetOkExists("sms_status"); ok {
request["SmsStatus"] = v
}
if d.HasChange("tts_status") {
update = true
}
if v, ok := d.GetOkExists("tts_status"); ok {
request["TtsStatus"] = v
}
if d.HasChange("webhook_status") {
update = true
}
if v, ok := d.GetOkExists("webhook_status"); ok {
request["WebhookStatus"] = v
}
if d.HasChange("contact_ids") {
update = true
if v, ok := d.GetOk("contact_ids"); ok {
request["ContactIds"] = convertListToJsonString(v.([]interface{}))
}
}
request["Locale"] = "en"
request["RegionId"] = client.RegionId
if d.HasChange("webhook_ids") {
update = true
if v, ok := d.GetOk("webhook_ids"); ok {
request["WebhookIds"] = convertListToJsonString(v.([]interface{}))
}
}
if update {
action := "UpdateSubscriptionItem"
conn, err := client.NewMscopensubscriptionClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("UpdateSubscriptionItem")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-07-13"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
}
return resourceAlicloudMscSubSubscriptionRead(d, meta)
}
func resourceAlicloudMscSubSubscriptionDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudMscSubSubscription. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudMscSubWebhook() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudMscSubWebhookCreate,
Read: resourceAlicloudMscSubWebhookRead,
Update: resourceAlicloudMscSubWebhookUpdate,
Delete: resourceAlicloudMscSubWebhookDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"server_url": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^https://oapi.dingtalk.com/robot/send\?access_token=[a-zA-Z0-9]+$`), "The serverUrl of the Webhook."),
},
"webhook_name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-zA-Z]{2,12}$`), "The name must be 2 to 12 characters in length, and can contain uppercase and lowercase letters."),
},
},
}
}
func resourceAlicloudMscSubWebhookCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateWebhook"
request := make(map[string]interface{})
conn, err := client.NewMscopensubscriptionClient()
if err != nil {
return WrapError(err)
}
request["Locale"] = "en"
request["ServerUrl"] = d.Get("server_url")
request["WebhookName"] = d.Get("webhook_name")
request["ClientToken"] = buildClientToken("CreateWebhook")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-07-13"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_msc_sub_webhook", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "200" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
d.SetId(fmt.Sprint(response["WebhookId"]))
return resourceAlicloudMscSubWebhookRead(d, meta)
}
func resourceAlicloudMscSubWebhookRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
mscOpenSubscriptionService := MscOpenSubscriptionService{client}
object, err := mscOpenSubscriptionService.DescribeMscSubWebhook(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_msc_sub_webhook mscOpenSubscriptionService.DescribeMscSubWebhook Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("server_url", object["ServerUrl"])
d.Set("webhook_name", object["WebhookName"])
return nil
}
func resourceAlicloudMscSubWebhookUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"WebhookId": d.Id(),
}
if d.HasChange("server_url") {
update = true
}
request["ServerUrl"] = d.Get("server_url")
if d.HasChange("webhook_name") {
update = true
}
request["WebhookName"] = d.Get("webhook_name")
if update {
request["Locale"] = "en"
action := "UpdateWebhook"
conn, err := client.NewMscopensubscriptionClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("UpdateWebhook")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-07-13"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
}
return resourceAlicloudMscSubWebhookRead(d, meta)
}
func resourceAlicloudMscSubWebhookDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteWebhook"
var response map[string]interface{}
conn, err := client.NewMscopensubscriptionClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"WebhookId": d.Id(),
"Locale": "en",
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-07-13"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ResourceNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudMseCluster() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudMseClusterCreate,
Read: resourceAlicloudMseClusterRead,
Update: resourceAlicloudMseClusterUpdate,
Delete: resourceAlicloudMseClusterDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(11 * time.Minute),
Delete: schema.DefaultTimeout(11 * time.Minute),
},
Schema: map[string]*schema.Schema{
"acl_entry_list": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"cluster_alias_name": {
Type: schema.TypeString,
Optional: true,
},
"cluster_specification": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"MSE_SC_1_2_200_c", "MSE_SC_2_4_200_c", "MSE_SC_4_8_200_c", "MSE_SC_8_16_200_c"}, false),
},
"cluster_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Eureka", "Nacos-Ans", "ZooKeeper"}, false),
},
"cluster_version": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"disk_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"instance_count": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
},
"net_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"privatenet", "pubnet"}, false),
},
"private_slb_specification": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"pub_network_flow": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"pub_slb_specification": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudMseClusterCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
mseService := MseService{client}
var response map[string]interface{}
action := "CreateCluster"
request := make(map[string]interface{})
conn, err := client.NewMseClient()
if err != nil {
return WrapError(err)
}
request["ClusterSpecification"] = d.Get("cluster_specification")
request["ClusterType"] = d.Get("cluster_type")
request["ClusterVersion"] = d.Get("cluster_version")
if v, ok := d.GetOk("disk_type"); ok {
request["DiskType"] = v
}
request["InstanceCount"] = d.Get("instance_count")
request["NetType"] = d.Get("net_type")
if v, ok := d.GetOk("private_slb_specification"); ok {
request["PrivateSlbSpecification"] = v
}
if v, ok := d.GetOk("pub_network_flow"); ok {
request["PubNetworkFlow"] = v
}
if v, ok := d.GetOk("pub_slb_specification"); ok {
request["PubSlbSpecification"] = v
}
request["Region"] = client.RegionId
vswitchId := Trim(d.Get("vswitch_id").(string))
if vswitchId != "" {
vpcService := VpcService{client}
vsw, err := vpcService.DescribeVSwitch(vswitchId)
if err != nil {
return WrapError(err)
}
request["VpcId"] = vsw.VpcId
request["VSwitchId"] = vswitchId
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-05-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_mse_cluster", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["InstanceId"]))
stateConf := BuildStateConf([]string{}, []string{"INIT_SUCCESS"}, d.Timeout(schema.TimeoutCreate), 60*time.Second, mseService.MseClusterStateRefreshFunc(d.Id(), []string{"INIT_FAILED"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudMseClusterUpdate(d, meta)
}
func resourceAlicloudMseClusterRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
mseService := MseService{client}
object, err := mseService.DescribeMseCluster(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_mse_cluster mseService.DescribeMseCluster Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("cluster_type", object["ClusterType"])
d.Set("instance_count", formatInt(object["InstanceCount"]))
d.Set("pub_network_flow", object["PubNetworkFlow"])
d.Set("status", object["InitStatus"])
return nil
}
func resourceAlicloudMseClusterUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
d.Partial(true)
if d.HasChange("acl_entry_list") {
request := map[string]interface{}{
"InstanceId": d.Id(),
}
request["AclEntryList"] = convertListToCommaSeparate(d.Get("acl_entry_list").(*schema.Set).List())
action := "UpdateAcl"
conn, err := client.NewMseClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-05-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("acl_entry_list")
}
update := false
request := map[string]interface{}{
"InstanceId": d.Id(),
}
if d.HasChange("cluster_alias_name") {
update = true
request["ClusterAliasName"] = d.Get("cluster_alias_name")
}
if update {
action := "UpdateCluster"
conn, err := client.NewMseClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-05-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("cluster_alias_name")
}
d.Partial(false)
return resourceAlicloudMseClusterRead(d, meta)
}
func resourceAlicloudMseClusterDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
mseService := MseService{client}
action := "DeleteCluster"
var response map[string]interface{}
conn, err := client.NewMseClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"InstanceId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-05-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"DESTROY_SUCCESS"}, d.Timeout(schema.TimeoutDelete), 60*time.Second, mseService.MseClusterStateRefreshFunc(d.Id(), []string{"DESTROY_FAILED"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudNasAccessGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudNasAccessGroupCreate,
Read: resourceAlicloudNasAccessGroupRead,
Update: resourceAlicloudNasAccessGroupUpdate,
Delete: resourceAlicloudNasAccessGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"access_group_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"name"},
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"access_group_name"},
},
"access_group_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Classic", "Vpc"}, false),
ConflictsWith: []string{"type"},
},
"type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Classic", "Vpc"}, false),
ConflictsWith: []string{"access_group_type"},
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"file_system_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"extreme", "standard"}, false),
Default: "standard",
},
},
}
}
func resourceAlicloudNasAccessGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateAccessGroup"
request := make(map[string]interface{})
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("access_group_name"); ok {
request["AccessGroupName"] = v
} else if v, ok := d.GetOk("name"); ok {
request["AccessGroupName"] = v
} else {
return WrapError(Error(`[ERROR] Argument "name" or "access_group_name" must be set one!`))
}
if v, ok := d.GetOk("access_group_type"); ok {
request["AccessGroupType"] = v
} else if v, ok := d.GetOk("type"); ok {
request["AccessGroupType"] = v
} else {
return WrapError(Error(`[ERROR] Argument "type" or "access_group_type" must be set one!`))
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("file_system_type"); ok {
request["FileSystemType"] = v
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"InternalError", "ServiceTimeout", "ServiceUnavailable"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_nas_access_group", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["AccessGroupName"], ":", request["FileSystemType"]))
return resourceAlicloudNasAccessGroupRead(d, meta)
}
func resourceAlicloudNasAccessGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
nasService := NasService{client}
if len(strings.Split(d.Id(), ":")) != 2 {
d.SetId(fmt.Sprintf("%v:%v", d.Id(), "standard"))
}
object, err := nasService.DescribeNasAccessGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_nas_access_group nasService.DescribeNasAccessGroup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("access_group_name", parts[0])
d.Set("name", parts[0])
d.Set("file_system_type", parts[1])
d.Set("access_group_type", object["AccessGroupType"])
d.Set("type", object["AccessGroupType"])
d.Set("description", object["Description"])
return nil
}
func resourceAlicloudNasAccessGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
if len(strings.Split(d.Id(), ":")) != 2 {
d.SetId(fmt.Sprintf("%v:%v", d.Id(), "standard"))
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
if d.HasChange("description") {
request := map[string]interface{}{
"AccessGroupName": parts[0],
"FileSystemType": parts[1],
}
request["Description"] = d.Get("description")
action := "ModifyAccessGroup"
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudNasAccessGroupRead(d, meta)
}
func resourceAlicloudNasAccessGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
if len(strings.Split(d.Id(), ":")) != 2 {
d.SetId(fmt.Sprintf("%v:%v", d.Id(), "standard"))
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteAccessGroup"
var response map[string]interface{}
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AccessGroupName": parts[0],
"FileSystemType": parts[1],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"Forbidden.NasNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudNasAccessRule() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudNasAccessRuleCreate,
Read: resourceAlicloudNasAccessRuleRead,
Update: resourceAlicloudNasAccessRuleUpdate,
Delete: resourceAlicloudNasAccessRuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"access_group_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"source_cidr_ip": {
Type: schema.TypeString,
Required: true,
},
"rw_access_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"RDWR", "RDONLY"}, false),
Default: "RDWR",
},
"user_access_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"no_squash", "root_squash", "all_squash"}, false),
Default: "no_squash",
},
"priority": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
ValidateFunc: validation.IntBetween(1, 100),
},
"access_rule_id": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudNasAccessRuleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateAccessRule"
request := make(map[string]interface{})
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
request["RegionId"] = client.Region
request["AccessGroupName"] = d.Get("access_group_name")
request["SourceCidrIp"] = d.Get("source_cidr_ip")
if v, ok := d.GetOk("rw_access_type"); ok && v.(string) != "" {
request["RWAccessType"] = v
}
if v, ok := d.GetOk("user_access_type"); ok && v.(string) != "" {
request["UserAccessType"] = v
}
request["Priority"] = d.Get("priority")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_nas_access_rule", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["AccessGroupName"], ":", response["AccessRuleId"]))
return resourceAlicloudNasAccessRuleRead(d, meta)
}
func resourceAlicloudNasAccessRuleUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
err = WrapError(err)
return err
}
request := map[string]interface{}{
"RegionId": client.RegionId,
"AccessGroupName": parts[0],
"AccessRuleId": parts[1],
}
update := false
if d.HasChange("source_cidr_ip") {
update = true
}
request["SourceCidrIp"] = d.Get("source_cidr_ip")
if d.HasChange("rw_access_type") {
update = true
}
request["RWAccessType"] = d.Get("rw_access_type")
if d.HasChange("user_access_type") {
update = true
}
request["UserAccessType"] = d.Get("user_access_type")
if d.HasChange("priority") {
update = true
}
request["Priority"] = d.Get("priority")
if update {
action := "ModifyAccessRule"
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudNasAccessRuleRead(d, meta)
}
func resourceAlicloudNasAccessRuleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
nasService := NasService{client}
object, err := nasService.DescribeNasAccessRule(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_nas_access_rule nasService.DescribeNasAccessRule Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("access_rule_id", object["AccessRuleId"])
d.Set("source_cidr_ip", object["SourceCidrIp"])
d.Set("access_group_name", parts[0])
d.Set("priority", formatInt(object["Priority"]))
d.Set("rw_access_type", object["RWAccess"])
d.Set("user_access_type", object["UserAccess"])
return nil
}
func resourceAlicloudNasAccessRuleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteAccessRule"
var response map[string]interface{}
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
err = WrapError(err)
return err
}
request := map[string]interface{}{
"RegionId": client.RegionId,
"AccessGroupName": parts[0],
"AccessRuleId": parts[1],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"Forbidden.NasNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudNasAutoSnapshotPolicy() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudNasAutoSnapshotPolicyCreate,
Read: resourceAlicloudNasAutoSnapshotPolicyRead,
Update: resourceAlicloudNasAutoSnapshotPolicyUpdate,
Delete: resourceAlicloudNasAutoSnapshotPolicyDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
Delete: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"auto_snapshot_policy_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.All(validation.StringDoesNotMatch(regexp.MustCompile(`(^http://.*)|(^https://.*)`), "It cannot begin with 'http://', 'https://'."), validation.StringMatch(regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9:_-]{1,127}$`), `The name must start with a letter. It must be 2 to 128 characters in length. It can contain digits, colons (:), underscores (_), and hyphens (-).`)),
},
"repeat_weekdays": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"retention_days": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.Any(validation.IntInSlice([]int{-1}), validation.IntBetween(1, 65536)),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"time_points": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
}
}
func resourceAlicloudNasAutoSnapshotPolicyCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateAutoSnapshotPolicy"
request := make(map[string]interface{})
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("auto_snapshot_policy_name"); ok {
request["AutoSnapshotPolicyName"] = v
}
request["FileSystemType"] = "extreme"
request["RepeatWeekdays"] = convertListToCommaSeparate(d.Get("repeat_weekdays").(*schema.Set).List())
if v, ok := d.GetOk("retention_days"); ok {
request["RetentionDays"] = v
}
request["TimePoints"] = convertListToCommaSeparate(d.Get("time_points").(*schema.Set).List())
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_nas_auto_snapshot_policy", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["AutoSnapshotPolicyId"]))
nasService := NasService{client}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, nasService.NasAutoSnapshotPolicyStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudNasAutoSnapshotPolicyRead(d, meta)
}
func resourceAlicloudNasAutoSnapshotPolicyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
nasService := NasService{client}
object, err := nasService.DescribeNasAutoSnapshotPolicy(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_nas_auto_snapshot_policy nasService.DescribeNasAutoSnapshotPolicy Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("auto_snapshot_policy_name", object["AutoSnapshotPolicyName"])
d.Set("repeat_weekdays", strings.Split(object["RepeatWeekdays"].(string), ","))
d.Set("retention_days", formatInt(object["RetentionDays"]))
d.Set("status", object["Status"])
d.Set("time_points", strings.Split(object["TimePoints"].(string), ","))
return nil
}
func resourceAlicloudNasAutoSnapshotPolicyUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
nasService := NasService{client}
var response map[string]interface{}
update := false
request := map[string]interface{}{
"AutoSnapshotPolicyId": d.Id(),
}
if d.HasChange("auto_snapshot_policy_name") {
update = true
if v, ok := d.GetOk("auto_snapshot_policy_name"); ok {
request["AutoSnapshotPolicyName"] = v
}
}
if d.HasChange("repeat_weekdays") {
update = true
request["RepeatWeekdays"] = convertListToCommaSeparate(d.Get("repeat_weekdays").(*schema.Set).List())
}
if d.HasChange("retention_days") {
update = true
if v, ok := d.GetOk("retention_days"); ok {
request["RetentionDays"] = v
}
}
if d.HasChange("time_points") {
update = true
request["TimePoints"] = convertListToCommaSeparate(d.Get("time_points").(*schema.Set).List())
}
if update {
action := "ModifyAutoSnapshotPolicy"
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, nasService.NasAutoSnapshotPolicyStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudNasAutoSnapshotPolicyRead(d, meta)
}
func resourceAlicloudNasAutoSnapshotPolicyDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
nasService := NasService{client}
action := "DeleteAutoSnapshotPolicy"
var response map[string]interface{}
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AutoSnapshotPolicyId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidLifecyclePolicy.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, nasService.NasAutoSnapshotPolicyStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudNasDataFlow() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudNasDataFlowCreate,
Read: resourceAlicloudNasDataFlowRead,
Update: resourceAlicloudNasDataFlowUpdate,
Delete: resourceAlicloudNasDataFlowDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"data_flow_id": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.All(validation.StringLenBetween(2, 256), validation.StringDoesNotMatch(regexp.MustCompile(`(^http://.*)|(^https://.*)`), "It cannot begin with \"http://\", \"https://\".")),
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"file_system_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"fset_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"source_security_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"SSL", "NONE"}, false),
},
"source_storage": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Running", "Stopped"}, false),
},
"throughput": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntInSlice([]int{600, 1200, 1500}),
},
},
}
}
func resourceAlicloudNasDataFlowCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateDataFlow"
request := make(map[string]interface{})
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["FileSystemId"] = d.Get("file_system_id")
request["FsetId"] = d.Get("fset_id")
if v, ok := d.GetOk("source_security_type"); ok {
request["SourceSecurityType"] = v
}
request["SourceStorage"] = d.Get("source_storage")
request["Throughput"] = d.Get("throughput")
request["ClientToken"] = buildClientToken("CreateDataFlow")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_nas_data_flow", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["FileSystemId"], ":", response["DataFlowId"]))
nasService := NasService{client}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, nasService.NasDataFlowStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudNasDataFlowRead(d, meta)
}
func resourceAlicloudNasDataFlowRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
nasService := NasService{client}
object, err := nasService.DescribeNasDataFlow(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_nas_data_flow nasService.DescribeNasDataFlow Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("data_flow_id", object["DataFlowId"])
d.Set("file_system_id", object["FileSystemId"])
d.Set("description", object["Description"])
d.Set("fset_id", object["FsetId"])
d.Set("source_security_type", object["SourceSecurityType"])
d.Set("source_storage", object["SourceStorage"])
d.Set("status", object["Status"])
d.Set("throughput", formatInt(object["Throughput"]))
return nil
}
func resourceAlicloudNasDataFlowUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
nasService := NasService{client}
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Partial(true)
update := false
modifyDataFlowReq := map[string]interface{}{
"DataFlowId": parts[1],
"FileSystemId": parts[0],
}
if d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
modifyDataFlowReq["Description"] = v
}
}
if d.HasChange("throughput") {
update = true
modifyDataFlowReq["Throughput"] = d.Get("throughput")
}
if update {
if v, ok := d.GetOkExists("dry_run"); ok {
modifyDataFlowReq["DryRun"] = v
}
action := "ModifyDataFlow"
modifyDataFlowReq["ClientToken"] = buildClientToken("ModifyDataFlow")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, modifyDataFlowReq, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyDataFlowReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, nasService.NasDataFlowStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("description")
d.SetPartial("throughput")
}
if d.HasChange("status") {
object, err := nasService.DescribeNasDataFlow(d.Id())
if err != nil {
return WrapError(err)
}
target := d.Get("status").(string)
if object["Status"].(string) != target {
if target == "Running" {
request := map[string]interface{}{
"DataFlowId": parts[1],
"FileSystemId": parts[0],
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
action := "StartDataFlow"
request["ClientToken"] = buildClientToken("StartDataFlow")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, nasService.NasDataFlowStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if target == "Stopped" {
request := map[string]interface{}{
"DataFlowId": parts[1],
"FileSystemId": parts[0],
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
action := "StopDataFlow"
request["ClientToken"] = buildClientToken("StopDataFlow")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Stopped"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, nasService.NasDataFlowStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.SetPartial("status")
}
}
d.Partial(false)
return resourceAlicloudNasDataFlowRead(d, meta)
}
func resourceAlicloudNasDataFlowDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteDataFlow"
var response map[string]interface{}
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DataFlowId": parts[1],
"FileSystemId": parts[0],
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["ClientToken"] = buildClientToken("DeleteDataFlow")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
nasService := NasService{client}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, nasService.NasDataFlowStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudNasFileSystem() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudNasFileSystemCreate,
Read: resourceAlicloudNasFileSystemRead,
Update: resourceAlicloudNasFileSystemUpdate,
Delete: resourceAlicloudNasFileSystemDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"storage_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
"Capacity",
"Performance",
"standard",
"advance",
"advance_100",
"advance_200",
}, false),
},
"protocol_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
"NFS",
"SMB",
"cpfs",
}, false),
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
},
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"encrypt_type": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IntInSlice([]int{0, 1, 2}),
Default: 0,
},
"file_system_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"extreme", "standard", "cpfs"}, false),
Default: "standard",
},
"capacity": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"kms_key_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"tags": tagsSchema(),
},
}
}
func resourceAlicloudNasFileSystemCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateFileSystem"
request := make(map[string]interface{})
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
request["RegionId"] = client.RegionId
request["ProtocolType"] = d.Get("protocol_type")
if v, ok := d.GetOk("file_system_type"); ok {
request["FileSystemType"] = v
}
request["StorageType"] = d.Get("storage_type")
request["EncryptType"] = d.Get("encrypt_type")
if v, ok := d.GetOk("zone_id"); ok {
request["ZoneId"] = v
}
if v, ok := d.GetOk("capacity"); ok {
request["Capacity"] = v
}
if v, ok := d.GetOk("kms_key_id"); ok {
request["KmsKeyId"] = v
}
if v, ok := d.GetOk("vpc_id"); ok {
request["VpcId"] = v
}
if v, ok := d.GetOk("vswitch_id"); ok {
request["VSwitchId"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) && IsExpectedErrors(err, []string{InvalidFileSystemStatus_Ordering}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_nas_file_system", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["FileSystemId"]))
// Creating an extreme/cpfs filesystem is asynchronous, so you need to block and wait until the creation is complete
if d.Get("file_system_type") == "extreme" || d.Get("file_system_type") == "cpfs" {
nasService := NasService{client}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 3*time.Second, nasService.DescribeNasFileSystemStateRefreshFunc(d.Id(), "Pending", []string{"Stopped", "Stopping", "Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudNasFileSystemUpdate(d, meta)
}
func resourceAlicloudNasFileSystemUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
nasService := NasService{client}
var response map[string]interface{}
request := map[string]interface{}{
"RegionId": client.RegionId,
"FileSystemId": d.Id(),
}
d.Partial(true)
if d.HasChange("tags") {
if err := nasService.SetResourceTags(d, "filesystem"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
if d.HasChange("description") {
request["Description"] = d.Get("description")
action := "ModifyFileSystem"
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) && IsExpectedErrors(err, []string{InvalidFileSystemStatus_Ordering}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("description")
}
d.Partial(false)
return resourceAlicloudNasFileSystemRead(d, meta)
}
func resourceAlicloudNasFileSystemRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
nasService := NasService{client}
object, err := nasService.DescribeNasFileSystem(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_nas_file_system nasService.DescribeNasFileSystem Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", object["Description"])
d.Set("protocol_type", object["ProtocolType"])
d.Set("storage_type", object["StorageType"])
d.Set("encrypt_type", object["EncryptType"])
d.Set("file_system_type", object["FileSystemType"])
d.Set("capacity", object["Capacity"])
d.Set("zone_id", object["ZoneId"])
d.Set("kms_key_id", object["KMSKeyId"])
tagResp, _ := nasService.ListTagResources(d.Id(), "filesystem")
d.Set("tags", tagsToMap(tagResp))
return nil
}
func resourceAlicloudNasFileSystemDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteFileSystem"
var response map[string]interface{}
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"FileSystemId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) && IsExpectedErrors(err, []string{InvalidFileSystemStatus_Ordering}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidFileSystem.NotFound", "Forbidden.NasNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if d.Get("file_system_type") == "cpfs" {
nasService := NasService{client}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 3*time.Second, nasService.DescribeNasFileSystemStateRefreshFunc(d.Id(), "Running", []string{"Pending"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudNasFileset() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudNasFilesetCreate,
Read: resourceAlicloudNasFilesetRead,
Update: resourceAlicloudNasFilesetUpdate,
Delete: resourceAlicloudNasFilesetDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(2 * time.Minute),
Delete: schema.DefaultTimeout(2 * time.Minute),
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.All(validation.StringLenBetween(2, 128), validation.StringDoesNotMatch(regexp.MustCompile(`(^http://.*)|(^https://.*)`), "It cannot begin with \"http://\", \"https://\".")),
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"file_system_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"file_system_path": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"fileset_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudNasFilesetCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateFileset"
request := make(map[string]interface{})
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["FileSystemId"] = d.Get("file_system_id")
request["FileSystemPath"] = d.Get("file_system_path")
request["ClientToken"] = buildClientToken("CreateFileset")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_nas_fileset", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["FileSystemId"], ":", response["FsetId"]))
nasService := NasService{client}
stateConf := BuildStateConf([]string{}, []string{"CREATED"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, nasService.NasFilesetStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudNasFilesetRead(d, meta)
}
func resourceAlicloudNasFilesetRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
nasService := NasService{client}
object, err := nasService.DescribeNasFileset(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_nas_fileset nasService.DescribeNasFileset Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("file_system_id", parts[0])
d.Set("fileset_id", parts[1])
d.Set("description", object["Description"])
d.Set("file_system_path", object["FileSystemPath"])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudNasFilesetUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"FileSystemId": parts[0],
"FsetId": parts[1],
}
if d.HasChange("description") {
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
action := "ModifyFileset"
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("ModifyFileset")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return resourceAlicloudNasFilesetRead(d, meta)
}
func resourceAlicloudNasFilesetDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteFileset"
var response map[string]interface{}
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"FileSystemId": parts[0],
"FsetId": parts[1],
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["ClientToken"] = buildClientToken("DeleteFileset")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
nasService := NasService{client}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutCreate), 5*time.Second, nasService.NasFilesetStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudNasLifecyclePolicy() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudNasLifecyclePolicyCreate,
Read: resourceAlicloudNasLifecyclePolicyRead,
Update: resourceAlicloudNasLifecyclePolicyUpdate,
Delete: resourceAlicloudNasLifecyclePolicyDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"file_system_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"lifecycle_policy_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"lifecycle_rule_name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"DEFAULT_ATIME_14", "DEFAULT_ATIME_30", "DEFAULT_ATIME_60", "DEFAULT_ATIME_90"}, false),
},
"paths": {
Type: schema.TypeList,
Required: true,
MaxItems: 10,
Elem: &schema.Schema{Type: schema.TypeString},
ForceNew: true,
},
"storage_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"InfrequentAccess"}, false),
},
},
}
}
func resourceAlicloudNasLifecyclePolicyCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateLifecyclePolicy"
request := make(map[string]interface{})
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
request["FileSystemId"] = d.Get("file_system_id")
request["LifecyclePolicyName"] = d.Get("lifecycle_policy_name")
request["LifecycleRuleName"] = d.Get("lifecycle_rule_name")
request["Paths"] = d.Get("paths")
request["StorageType"] = d.Get("storage_type")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_nas_lifecycle_policy", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["FileSystemId"], ":", request["LifecyclePolicyName"]))
return resourceAlicloudNasLifecyclePolicyRead(d, meta)
}
func resourceAlicloudNasLifecyclePolicyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
nasService := NasService{client}
object, err := nasService.DescribeNasLifecyclePolicy(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_nas_lifecycle_policy nasService.DescribeNasLifecyclePolicy Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("file_system_id", object["FileSystemId"])
d.Set("lifecycle_policy_name", object["LifecyclePolicyName"])
d.Set("lifecycle_rule_name", object["LifecycleRuleName"])
d.Set("paths", object["Paths"])
d.Set("storage_type", object["StorageType"])
return nil
}
func resourceAlicloudNasLifecyclePolicyUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"FileSystemId": parts[0],
"LifecyclePolicyName": parts[1],
}
request["LifecycleRuleName"] = d.Get("lifecycle_rule_name")
if d.HasChange("lifecycle_rule_name") {
update = true
}
if update {
action := "ModifyLifecyclePolicy"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudNasLifecyclePolicyRead(d, meta)
}
func resourceAlicloudNasLifecyclePolicyDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteLifecyclePolicy"
var response map[string]interface{}
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"FileSystemId": parts[0],
"LifecyclePolicyName": parts[1],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidFileSystem.NotFound", "InvalidLifecyclePolicy.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudNasMountTarget() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudNasMountTargetCreate,
Read: resourceAlicloudNasMountTargetRead,
Update: resourceAlicloudNasMountTargetUpdate,
Delete: resourceAlicloudNasMountTargetDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(40 * time.Minute),
Delete: schema.DefaultTimeout(40 * time.Minute),
},
Schema: map[string]*schema.Schema{
"access_group_name": {
Type: schema.TypeString,
Optional: true,
},
"file_system_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"security_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Inactive"}, false),
},
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudNasMountTargetCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
nasService := NasService{client}
var response map[string]interface{}
action := "CreateMountTarget"
request := make(map[string]interface{})
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("access_group_name"); ok {
request["AccessGroupName"] = v
}
request["FileSystemId"] = d.Get("file_system_id")
request["NetworkType"] = string(Classic)
if v, ok := d.GetOk("security_group_id"); ok {
request["SecurityGroupId"] = v
}
vswitchId := Trim(d.Get("vswitch_id").(string))
if vswitchId != "" {
vpcService := VpcService{client}
vsw, err := vpcService.DescribeVSwitchWithTeadsl(vswitchId)
if err != nil {
return WrapError(err)
}
request["NetworkType"] = string(Vpc)
request["VpcId"] = vsw["VpcId"]
request["VSwitchId"] = vswitchId
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_nas_mount_target", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["FileSystemId"], ":", response["MountTargetDomain"]))
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutCreate), 10*time.Second, nasService.NasMountTargetStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudNasMountTargetUpdate(d, meta)
}
func resourceAlicloudNasMountTargetRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
nasService := NasService{client}
if len(strings.Split(d.Id(), ":")) != 2 {
d.SetId(fmt.Sprintf("%v:%v", strings.Split(d.Id(), "-")[0], d.Id()))
}
object, err := nasService.DescribeNasMountTarget(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_nas_mount_target nasService.DescribeNasMountTarget Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("file_system_id", parts[0])
d.Set("access_group_name", object["AccessGroup"])
d.Set("status", object["Status"])
d.Set("vswitch_id", object["VswId"])
return nil
}
func resourceAlicloudNasMountTargetUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
if len(strings.Split(d.Id(), ":")) != 2 {
d.SetId(fmt.Sprintf("%v:%v", strings.Split(d.Id(), "-")[0], d.Id()))
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"FileSystemId": parts[0],
"MountTargetDomain": parts[1],
}
if !d.IsNewResource() && d.HasChange("access_group_name") {
update = true
request["AccessGroupName"] = d.Get("access_group_name")
}
if d.HasChange("status") {
update = true
request["Status"] = d.Get("status")
}
if update {
action := "ModifyMountTarget"
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudNasMountTargetRead(d, meta)
}
func resourceAlicloudNasMountTargetDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
if len(strings.Split(d.Id(), ":")) != 2 {
d.SetId(fmt.Sprintf("%v:%v", strings.Split(d.Id(), "-")[0], d.Id()))
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteMountTarget"
var response map[string]interface{}
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"FileSystemId": parts[0],
"MountTargetDomain": parts[1],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"Forbidden.NasNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
nasService := NasService{client}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 10*time.Second, nasService.NasMountTargetStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudNasSnapshot() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudNasSnapshotCreate,
Read: resourceAlicloudNasSnapshotRead,
Delete: resourceAlicloudNasSnapshotDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
Delete: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.All(validation.StringLenBetween(2, 256), validation.StringDoesNotMatch(regexp.MustCompile(`(^http://.*)|(^https://.*)`), "It must be `2` to `256` characters in length and cannot start with `https://` or `https://`.")),
},
"file_system_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"retention_days": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"snapshot_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.All(validation.StringLenBetween(2, 128), validation.StringDoesNotMatch(regexp.MustCompile(`(^http://.*)|(^https://.*)`), "It must be `2` to `128` characters in length and must start with a letter, but cannot start with `https://` or `https://`.")),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudNasSnapshotCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateSnapshot"
request := make(map[string]interface{})
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["FileSystemId"] = d.Get("file_system_id")
if v, ok := d.GetOk("retention_days"); ok {
request["RetentionDays"] = v
}
if v, ok := d.GetOk("snapshot_name"); ok {
request["SnapshotName"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_nas_snapshot", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["SnapshotId"]))
nasService := NasService{client}
stateConf := BuildStateConf([]string{}, []string{"accomplished"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, nasService.NasSnapshotStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudNasSnapshotRead(d, meta)
}
func resourceAlicloudNasSnapshotRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
nasService := NasService{client}
object, err := nasService.DescribeNasSnapshot(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_nas_snapshot nasService.DescribeNasSnapshot Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", object["Description"])
if v, ok := object["RetentionDays"]; ok && fmt.Sprint(v) != "0" {
d.Set("retention_days", formatInt(v))
}
d.Set("snapshot_name", object["SnapshotName"])
d.Set("file_system_id", object["SourceFileSystemId"])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudNasSnapshotDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
nasService := NasService{client}
action := "DeleteSnapshot"
var response map[string]interface{}
conn, err := client.NewNasClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"SnapshotId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidFileSystem.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, nasService.NasSnapshotStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"strconv"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudNatGateway() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudNatGatewayCreate,
Read: resourceAlicloudNatGatewayRead,
Update: resourceAlicloudNatGatewayUpdate,
Delete: resourceAlicloudNatGatewayDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"force": {
Type: schema.TypeBool,
Optional: true,
},
"forward_table_ids": {
Type: schema.TypeString,
Computed: true,
},
"internet_charge_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PayByLcu", "PayBySpec"}, false),
},
"nat_gateway_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"name"},
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"nat_gateway_name"},
},
"nat_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Enhanced", "Normal"}, false),
Computed: true,
},
"payment_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo", "Subscription"}, false),
ConflictsWith: []string{"instance_charge_type"},
},
"instance_charge_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PostPaid", "PrePaid"}, false),
ConflictsWith: []string{"payment_type"},
},
"period": {
Type: schema.TypeInt,
Optional: true,
DiffSuppressFunc: PostPaidDiffSuppressFunc,
ValidateFunc: validation.Any(
validation.IntBetween(1, 9),
validation.IntInSlice([]int{12, 24, 36})),
},
"bandwidth_packages": {
Type: schema.TypeList,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ip_count": {
Type: schema.TypeInt,
Required: true,
},
"bandwidth": {
Type: schema.TypeInt,
Required: true,
},
"zone": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"public_ip_addresses": {
Type: schema.TypeString,
Computed: true,
},
},
},
MaxItems: 4,
Optional: true,
Removed: "Field 'bandwidth_packages' has been removed from provider version 1.121.0.",
},
"bandwidth_package_ids": {
Type: schema.TypeString,
Computed: true,
Removed: "Field 'bandwidth_package_ids' has been removed from provider version 1.121.0.",
},
"spec": {
Type: schema.TypeString,
Optional: true,
Removed: "Field 'spec' has been removed from provider version 1.121.0, replace by 'specification'.",
},
"snat_table_ids": {
Type: schema.TypeString,
Computed: true,
},
"specification": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Large", "Middle", "Small", "XLarge.1"}, false),
Computed: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("internet_charge_type").(string) == "PayByLcu"
},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("nat_type").(string) != "Enhanced"
},
},
"vpc_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"deletion_protection": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"network_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"internet", "intranet"}, false),
},
},
}
}
func resourceAlicloudNatGatewayCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
action := "CreateNatGateway"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("internet_charge_type"); ok {
request["InternetChargeType"] = v
}
if v, ok := d.GetOk("nat_gateway_name"); ok {
request["Name"] = v
} else if v, ok := d.GetOk("name"); ok {
request["Name"] = v
}
request["NatType"] = d.Get("nat_type")
if v, ok := d.GetOk("payment_type"); ok {
request["InstanceChargeType"] = convertNatGatewayPaymentTypeRequest(v.(string))
} else if v, ok := d.GetOk("instance_charge_type"); ok {
request["InstanceChargeType"] = v
}
if v, ok := request["InstanceChargeType"]; ok && v.(string) == "PrePaid" {
period := d.Get("period").(int)
request["Duration"] = strconv.Itoa(period)
request["PricingCycle"] = "Month"
if period > 9 {
request["Duration"] = strconv.Itoa(period / 12)
request["PricingCycle"] = string(Year)
}
request["AutoPay"] = true
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("specification"); ok {
request["Spec"] = v
}
if v, ok := d.GetOk("vswitch_id"); ok {
request["VSwitchId"] = v
}
if v, ok := d.GetOk("network_type"); ok {
request["NetworkType"] = v
}
request["VpcId"] = d.Get("vpc_id")
request["ClientToken"] = buildClientToken("CreateNatGateway")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"TaskConflict", "VswitchStatusError"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_nat_gateway", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["NatGatewayId"]))
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, vpcService.NatGatewayStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudNatGatewayUpdate(d, meta)
}
func resourceAlicloudNatGatewayRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeNatGateway(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_nat_gateway vpcService.DescribeNatGateway Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", object["Description"])
if v, ok := object["ForwardTableIds"].(map[string]interface{})["ForwardTableId"].([]interface{}); ok {
ids := []string{}
for _, id := range v {
ids = append(ids, id.(string))
}
d.Set("forward_table_ids", strings.Join(ids, ","))
}
d.Set("internet_charge_type", object["InternetChargeType"])
d.Set("nat_gateway_name", object["Name"])
d.Set("name", object["Name"])
d.Set("nat_type", object["NatType"])
d.Set("payment_type", convertNatGatewayPaymentTypeResponse(object["InstanceChargeType"].(string)))
d.Set("instance_charge_type", object["InstanceChargeType"])
d.Set("network_type", object["NetworkType"])
//if object["InstanceChargeType"] == "PrePaid" {
// period, err := computePeriodByUnit(object["CreationTime"], object["ExpiredTime"], d.Get("period").(int), "Month")
// if err != nil {
// return WrapError(err)
// }
// d.Set("period", period)
//}
if v, ok := object["SnatTableIds"].(map[string]interface{})["SnatTableId"].([]interface{}); ok {
ids := []string{}
for _, id := range v {
ids = append(ids, id.(string))
}
d.Set("snat_table_ids", strings.Join(ids, ","))
}
d.Set("specification", object["Spec"])
d.Set("status", object["Status"])
d.Set("vswitch_id", object["NatGatewayPrivateInfo"].(map[string]interface{})["VswitchId"])
d.Set("vpc_id", object["VpcId"])
listTagResourcesObject, err := vpcService.ListTagResources(d.Id(), "NATGATEWAY")
if err != nil {
return WrapError(err)
}
d.Set("tags", tagsToMap(listTagResourcesObject))
d.Set("deletion_protection", object["DeletionProtection"])
return nil
}
func resourceAlicloudNatGatewayUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
d.Partial(true)
if d.HasChange("tags") {
if err := vpcService.SetResourceTags(d, "NATGATEWAY"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
if d.HasChange("deletion_protection") {
var response map[string]interface{}
action := "DeletionProtection"
request := map[string]interface{}{
"RegionId": client.RegionId,
"InstanceId": d.Id(),
"ProtectionEnable": d.Get("deletion_protection"),
"Type": "NATGW",
}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken(action)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("deletion_protection")
}
update := false
request := map[string]interface{}{
"NatGatewayId": d.Id(),
}
request["RegionId"] = client.RegionId
if !d.IsNewResource() && d.HasChange("description") {
update = true
request["Description"] = d.Get("description")
}
if !d.IsNewResource() && d.HasChange("nat_gateway_name") {
update = true
request["Name"] = d.Get("nat_gateway_name")
}
if !d.IsNewResource() && d.HasChange("name") {
update = true
request["Name"] = d.Get("name")
}
if update {
action := "ModifyNatGatewayAttribute"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("description")
d.SetPartial("name")
d.SetPartial("nat_gateway_name")
}
if !d.IsNewResource() && d.HasChange("specification") {
request := map[string]interface{}{
"NatGatewayId": d.Id(),
}
request["RegionId"] = client.RegionId
request["Spec"] = d.Get("specification")
action := "ModifyNatGatewaySpec"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, vpcService.NatGatewayStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("specification")
}
update = false
updateNatGatewayNatTypeReq := map[string]interface{}{
"NatGatewayId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("nat_type") {
update = true
}
updateNatGatewayNatTypeReq["NatType"] = d.Get("nat_type")
updateNatGatewayNatTypeReq["RegionId"] = client.RegionId
if !d.IsNewResource() && d.HasChange("vswitch_id") {
update = true
}
updateNatGatewayNatTypeReq["VSwitchId"] = d.Get("vswitch_id")
if update {
if _, ok := d.GetOkExists("dry_run"); ok {
updateNatGatewayNatTypeReq["DryRun"] = d.Get("dry_run")
}
action := "UpdateNatGatewayNatType"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
updateNatGatewayNatTypeReq["ClientToken"] = buildClientToken("UpdateNatGatewayNatType")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, updateNatGatewayNatTypeReq, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"OperationFailed.NatGwRouteInMiddleStatus", "TaskConflict", "Throttling", "UnknownError"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, updateNatGatewayNatTypeReq)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, vpcService.NatGatewayStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("nat_type")
d.SetPartial("vswitch_id")
d.SetPartial("dry_run")
}
d.Partial(false)
return resourceAlicloudNatGatewayRead(d, meta)
}
func resourceAlicloudNatGatewayDelete(d *schema.ResourceData, meta interface{}) error {
if d.Get("payment_type").(string) == "Subscription" || d.Get("instance_charge_type").(string) == "Prepaid" {
log.Printf("[WARN] Cannot destroy Subscription resource: alicloud_nat_gateway. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
action := "DeleteNatGateway"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"NatGatewayId": d.Id(),
}
if v, ok := d.GetOkExists("force"); ok {
request["Force"] = v
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"DependencyViolation.BandwidthPackages"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"INSTANCE_NOT_EXISTS", "IncorrectStatus.NatGateway", "InvalidNatGatewayId.NotFound", "InvalidRegionId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, vpcService.NatGatewayStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
func convertNatGatewayPaymentTypeRequest(source string) string {
switch source {
case "PayAsYouGo":
return "PostPaid"
case "Subscription":
return "PrePaid"
}
return source
}
func convertNatGatewayPaymentTypeResponse(source string) string {
switch source {
case "PostPaid":
return "PayAsYouGo"
case "PrePaid":
return "Subscription"
}
return source
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudNetworkAcl() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudNetworkAclCreate,
Read: resourceAlicloudNetworkAclRead,
Update: resourceAlicloudNetworkAclUpdate,
Delete: resourceAlicloudNetworkAclDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"egress_acl_entries": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
},
"destination_cidr_ip": {
Type: schema.TypeString,
Optional: true,
},
"network_acl_entry_name": {
Type: schema.TypeString,
Optional: true,
},
"policy": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"accept", "drop"}, false),
},
"port": {
Type: schema.TypeString,
Optional: true,
},
"protocol": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"icmp", "gre", "tcp", "udp", "all"}, false),
},
},
},
},
"ingress_acl_entries": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
},
"network_acl_entry_name": {
Type: schema.TypeString,
Optional: true,
},
"policy": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"accept", "drop"}, false),
},
"port": {
Type: schema.TypeString,
Optional: true,
},
"protocol": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"icmp", "gre", "tcp", "udp", "all"}, false),
},
"source_cidr_ip": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"network_acl_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"name"},
ValidateFunc: validation.StringLenBetween(2, 128),
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Field 'name' has been deprecated from provider version 1.122.0. New field 'network_acl_name' instead",
ConflictsWith: []string{"network_acl_name"},
ValidateFunc: validation.StringLenBetween(2, 128),
},
"resources": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"resource_id": {
Type: schema.TypeString,
Optional: true,
},
"resource_type": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudNetworkAclCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
action := "CreateNetworkAcl"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("network_acl_name"); ok {
request["NetworkAclName"] = v
} else if v, ok := d.GetOk("name"); ok {
request["NetworkAclName"] = v
}
request["RegionId"] = client.RegionId
request["VpcId"] = d.Get("vpc_id")
request["ClientToken"] = buildClientToken("CreateNetworkAcl")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_network_acl", action, AlibabaCloudSdkGoERROR)
}
responseNetworkAclAttribute := response["NetworkAclAttribute"].(map[string]interface{})
d.SetId(fmt.Sprint(responseNetworkAclAttribute["NetworkAclId"]))
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, vpcService.NetworkAclStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudNetworkAclUpdate(d, meta)
}
func resourceAlicloudNetworkAclRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeNetworkAcl(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_network_acl vpcService.DescribeNetworkAcl Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", object["Description"])
egressAclEntry := make([]map[string]interface{}, 0)
if egressAclEntryList, ok := object["EgressAclEntries"].(map[string]interface{})["EgressAclEntry"].([]interface{}); ok {
for _, v := range egressAclEntryList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"description": m1["Description"],
"destination_cidr_ip": m1["DestinationCidrIp"],
"network_acl_entry_name": m1["NetworkAclEntryName"],
"policy": m1["Policy"],
"port": m1["Port"],
"protocol": m1["Protocol"],
}
egressAclEntry = append(egressAclEntry, temp1)
}
}
}
if err := d.Set("egress_acl_entries", egressAclEntry); err != nil {
return WrapError(err)
}
ingressAclEntry := make([]map[string]interface{}, 0)
if ingressAclEntryList, ok := object["IngressAclEntries"].(map[string]interface{})["IngressAclEntry"].([]interface{}); ok {
for _, v := range ingressAclEntryList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"description": m1["Description"],
"network_acl_entry_name": m1["NetworkAclEntryName"],
"policy": m1["Policy"],
"port": m1["Port"],
"protocol": m1["Protocol"],
"source_cidr_ip": m1["SourceCidrIp"],
}
ingressAclEntry = append(ingressAclEntry, temp1)
}
}
}
if err := d.Set("ingress_acl_entries", ingressAclEntry); err != nil {
return WrapError(err)
}
d.Set("network_acl_name", object["NetworkAclName"])
d.Set("name", object["NetworkAclName"])
resourceMap := make([]map[string]interface{}, 0)
if resourceMapList, ok := object["Resources"].(map[string]interface{})["Resource"].([]interface{}); ok {
for _, v := range resourceMapList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"resource_id": m1["ResourceId"],
"resource_type": m1["ResourceType"],
}
resourceMap = append(resourceMap, temp1)
}
}
}
if err := d.Set("resources", resourceMap); err != nil {
return WrapError(err)
}
d.Set("status", object["Status"])
d.Set("vpc_id", object["VpcId"])
return nil
}
func resourceAlicloudNetworkAclUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"NetworkAclId": d.Id(),
}
request["RegionId"] = client.RegionId
if !d.IsNewResource() && d.HasChange("description") {
update = true
request["Description"] = d.Get("description")
}
if !d.IsNewResource() && d.HasChange("network_acl_name") {
update = true
request["NetworkAclName"] = d.Get("network_acl_name")
}
if !d.IsNewResource() && d.HasChange("name") {
update = true
request["NetworkAclName"] = d.Get("name")
}
if update {
action := "ModifyNetworkAclAttributes"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("ModifyNetworkAclAttributes")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, vpcService.NetworkAclStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("description")
d.SetPartial("name")
d.SetPartial("network_acl_name")
}
update = false
updateNetworkAclEntriesReq := map[string]interface{}{
"NetworkAclId": d.Id(),
}
updateNetworkAclEntriesReq["RegionId"] = client.RegionId
if d.HasChange("egress_acl_entries") {
updateNetworkAclEntriesReq["UpdateEgressAclEntries"] = true
update = true
EgressAclEntries := make([]map[string]interface{}, len(d.Get("egress_acl_entries").([]interface{})))
for i, EgressAclEntriesValue := range d.Get("egress_acl_entries").([]interface{}) {
EgressAclEntriesMap := EgressAclEntriesValue.(map[string]interface{})
EgressAclEntries[i] = make(map[string]interface{})
EgressAclEntries[i]["Description"] = EgressAclEntriesMap["description"]
EgressAclEntries[i]["DestinationCidrIp"] = EgressAclEntriesMap["destination_cidr_ip"]
EgressAclEntries[i]["NetworkAclEntryName"] = EgressAclEntriesMap["network_acl_entry_name"]
EgressAclEntries[i]["Policy"] = EgressAclEntriesMap["policy"]
EgressAclEntries[i]["Port"] = EgressAclEntriesMap["port"]
EgressAclEntries[i]["Protocol"] = EgressAclEntriesMap["protocol"]
}
updateNetworkAclEntriesReq["EgressAclEntries"] = EgressAclEntries
}
if d.HasChange("ingress_acl_entries") {
updateNetworkAclEntriesReq["UpdateIngressAclEntries"] = true
update = true
IngressAclEntries := make([]map[string]interface{}, len(d.Get("ingress_acl_entries").([]interface{})))
for i, IngressAclEntriesValue := range d.Get("ingress_acl_entries").([]interface{}) {
IngressAclEntriesMap := IngressAclEntriesValue.(map[string]interface{})
IngressAclEntries[i] = make(map[string]interface{})
IngressAclEntries[i]["Description"] = IngressAclEntriesMap["description"]
IngressAclEntries[i]["NetworkAclEntryName"] = IngressAclEntriesMap["network_acl_entry_name"]
IngressAclEntries[i]["Policy"] = IngressAclEntriesMap["policy"]
IngressAclEntries[i]["Port"] = IngressAclEntriesMap["port"]
IngressAclEntries[i]["Protocol"] = IngressAclEntriesMap["protocol"]
IngressAclEntries[i]["SourceCidrIp"] = IngressAclEntriesMap["source_cidr_ip"]
}
updateNetworkAclEntriesReq["IngressAclEntries"] = IngressAclEntries
}
if update {
action := "UpdateNetworkAclEntries"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("UpdateNetworkAclEntries")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, updateNetworkAclEntriesReq, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"TaskConflict"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, updateNetworkAclEntriesReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, vpcService.NetworkAclStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("egress_acl_entries")
d.SetPartial("ingress_acl_entries")
}
d.Partial(false)
if d.HasChange("resources") {
oldResources, newResources := d.GetChange("resources")
oldResourcesSet := oldResources.(*schema.Set)
newResourcesSet := newResources.(*schema.Set)
removed := oldResourcesSet.Difference(newResourcesSet)
added := newResourcesSet.Difference(oldResourcesSet)
if added.Len() > 0 {
associatenetworkaclrequest := map[string]interface{}{
"NetworkAclId": d.Id(),
}
resourcesMaps := make([]map[string]interface{}, 0)
for _, resources := range added.List() {
resourcesArg := resources.(map[string]interface{})
resourcesMap := map[string]interface{}{
"ResourceId": resourcesArg["resource_id"],
"ResourceType": resourcesArg["resource_type"],
}
resourcesMaps = append(resourcesMaps, resourcesMap)
}
associatenetworkaclrequest["Resource"] = resourcesMaps
associatenetworkaclrequest["RegionId"] = client.RegionId
action := "AssociateNetworkAcl"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("AssociateNetworkAcl")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, associatenetworkaclrequest, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, associatenetworkaclrequest)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, vpcService.NetworkAclStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("resources")
}
if removed.Len() > 0 {
unassociatenetworkaclrequest := map[string]interface{}{
"NetworkAclId": d.Id(),
}
resourcesMaps := make([]map[string]interface{}, 0)
for _, resources := range removed.List() {
resourcesArg := resources.(map[string]interface{})
resourcesMap := map[string]interface{}{
"ResourceId": resourcesArg["resource_id"],
"ResourceType": resourcesArg["resource_type"],
}
resourcesMaps = append(resourcesMaps, resourcesMap)
}
unassociatenetworkaclrequest["Resource"] = resourcesMaps
unassociatenetworkaclrequest["RegionId"] = client.RegionId
action := "UnassociateNetworkAcl"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("UnassociateNetworkAcl")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, unassociatenetworkaclrequest, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, unassociatenetworkaclrequest)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, vpcService.NetworkAclStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("resources")
}
}
return resourceAlicloudNetworkAclRead(d, meta)
}
func resourceAlicloudNetworkAclDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
// Delete binging resources before delete the ACL
_, err := vpcService.DeleteAclResources(d.Id())
if err != nil {
return WrapError(err)
}
action := "DeleteNetworkAcl"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"NetworkAclId": d.Id(),
}
request["RegionId"] = client.RegionId
request["ClientToken"] = buildClientToken("DeleteNetworkAcl")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, vpcService.NetworkAclStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliyunNetworkAclAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunNetworkAclAttachmentCreate,
Read: resourceAliyunNetworkAclAttachmentRead,
Update: resourceAliyunNetworkAclAttachmentUpdate,
Delete: resourceAliyunNetworkAclAttachmentDelete,
Schema: map[string]*schema.Schema{
"network_acl_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"resources": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"resource_id": {
Type: schema.TypeString,
Required: true,
},
"resource_type": {
Type: schema.TypeString,
Required: true,
},
},
},
},
},
}
}
func resourceAliyunNetworkAclAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
d.SetId(d.Get("network_acl_id").(string) + COLON_SEPARATED + resource.UniqueId())
return resourceAliyunNetworkAclAttachmentUpdate(d, meta)
}
func resourceAliyunNetworkAclAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
networkAclId := parts[0]
vpcResource := []vpc.Resource{}
for _, e := range d.Get("resources").(*schema.Set).List() {
resourceId := e.(map[string]interface{})["resource_id"]
resourceType := e.(map[string]interface{})["resource_type"]
vpcResource = append(vpcResource, vpc.Resource{
ResourceId: resourceId.(string),
ResourceType: resourceType.(string),
})
}
err = vpcService.DescribeNetworkAclAttachment(networkAclId, vpcResource)
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("network_acl_id", networkAclId)
d.Set("resources", vpcResource)
return nil
}
func resourceAliyunNetworkAclAttachmentUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
networkAclId := parts[0]
if d.HasChange("resources") {
oraw, nraw := d.GetChange("resources")
o := oraw.(*schema.Set)
n := nraw.(*schema.Set)
remove := o.Difference(n).List()
create := n.Difference(o).List()
if len(remove) > 0 {
request := vpc.CreateUnassociateNetworkAclRequest()
request.RegionId = client.RegionId
request.NetworkAclId = networkAclId
request.ClientToken = buildClientToken(request.GetActionName())
var resources []vpc.UnassociateNetworkAclResource
vpcResource := []vpc.Resource{}
for _, t := range remove {
s := t.(map[string]interface{})
var resourceId, resourceType string
if v, ok := s["resource_id"]; ok {
resourceId = v.(string)
}
if v, ok := s["resource_type"]; ok {
resourceType = v.(string)
}
resources = append(resources, vpc.UnassociateNetworkAclResource{
ResourceId: resourceId,
ResourceType: resourceType,
})
vpcResource = append(vpcResource, vpc.Resource{
ResourceId: resourceId,
ResourceType: resourceType,
})
}
request.Resource = &resources
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.UnassociateNetworkAcl(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
if err := vpcService.WaitForNetworkAclAttachment(request.NetworkAclId, vpcResource, Available, Timeout5Minute); err != nil {
return WrapError(err)
}
}
if len(create) > 0 {
request := vpc.CreateAssociateNetworkAclRequest()
request.RegionId = client.RegionId
request.NetworkAclId = networkAclId
request.ClientToken = buildClientToken(request.GetActionName())
var resources []vpc.AssociateNetworkAclResource
vpcResource := []vpc.Resource{}
for _, t := range create {
s := t.(map[string]interface{})
var resourceId, resourceType string
if v, ok := s["resource_id"]; ok {
resourceId = v.(string)
}
if v, ok := s["resource_type"]; ok {
resourceType = v.(string)
}
resources = append(resources, vpc.AssociateNetworkAclResource{
ResourceId: resourceId,
ResourceType: resourceType,
})
vpcResource = append(vpcResource, vpc.Resource{
ResourceId: resourceId,
ResourceType: resourceType,
})
}
request.Resource = &resources
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.AssociateNetworkAcl(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
if err := vpcService.WaitForNetworkAclAttachment(request.NetworkAclId, vpcResource, Available, Timeout5Minute); err != nil {
return WrapError(err)
}
}
d.SetPartial("resources")
}
return resourceAliyunNetworkAclAttachmentRead(d, meta)
}
func resourceAliyunNetworkAclAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
networkAclId := parts[0]
resources := []vpc.UnassociateNetworkAclResource{}
object, err := vpcService.DescribeNetworkAcl(networkAclId)
vpcResource := []vpc.Resource{}
request := vpc.CreateUnassociateNetworkAclRequest()
request.RegionId = client.RegionId
request.NetworkAclId = networkAclId
request.ClientToken = buildClientToken(request.GetActionName())
res, _ := object["Resources"].(map[string]interface{})["Resource"].([]interface{})
for _, e := range res {
item := e.(map[string]interface{})
resources = append(resources, vpc.UnassociateNetworkAclResource{
ResourceId: item["ResourceId"].(string),
ResourceType: item["ResourceType"].(string),
})
vpcResource = append(vpcResource, vpc.Resource{
ResourceId: item["ResourceId"].(string),
ResourceType: item["ResourceType"].(string),
})
}
request.Resource = &resources
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.UnassociateNetworkAcl(request)
})
//Waiting for unassociate the network acl
if err != nil {
if IsExpectedErrors(err, []string{"TaskConflict"}) {
return resource.RetryableError(err)
}
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return vpcService.WaitForNetworkAclAttachment(networkAclId, vpcResource, Deleted, Timeout5Minute)
}
package alicloud
import (
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliyunNetworkAclEntries() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunNetworkAclEntriesCreate,
Read: resourceAliyunNetworkAclEntriesRead,
Update: resourceAliyunNetworkAclEntriesUpdate,
Delete: resourceAliyunNetworkAclEntriesDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"network_acl_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ingress": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"source_cidr_ip": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"entry_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"policy": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"port": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"protocol": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
},
},
},
"egress": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"destination_cidr_ip": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"entry_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"policy": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"port": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"protocol": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
},
},
},
},
}
}
func resourceAliyunNetworkAclEntriesCreate(d *schema.ResourceData, meta interface{}) error {
d.SetId(d.Get("network_acl_id").(string) + COLON_SEPARATED + resource.UniqueId())
return resourceAliyunNetworkAclEntriesUpdate(d, meta)
}
func resourceAliyunNetworkAclEntriesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
object, err := vpcService.DescribeNetworkAcl(parts[0])
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
var ingress []map[string]interface{}
if ingressAclEntryList, ok := object["IngressAclEntries"].(map[string]interface{})["IngressAclEntry"].([]interface{}); ok {
for _, ob := range ingressAclEntryList {
if v, ok := ob.(map[string]interface{}); ok {
mapping := map[string]interface{}{
"description": v["Description"],
"source_cidr_ip": v["SourceCidrIp"],
"entry_type": "custom",
"name": v["NetworkAclEntryName"],
"policy": v["Policy"],
"port": v["Port"],
"protocol": v["Protocol"],
}
ingress = append(ingress, mapping)
}
}
}
var egress []map[string]interface{}
if egressAclEntryList, ok := object["EgressAclEntries"].(map[string]interface{})["EgressAclEntry"].([]interface{}); ok {
for _, ob := range egressAclEntryList {
if v, ok := ob.(map[string]interface{}); ok {
mapping := map[string]interface{}{
"description": v["Description"],
"destination_cidr_ip": v["DestinationCidrIp"],
"entry_type": "custom",
"name": v["NetworkAclEntryName"],
"policy": v["Policy"],
"port": v["Port"],
"protocol": v["Protocol"],
}
egress = append(egress, mapping)
}
}
}
d.Set("network_acl_id", object["NetworkAclId"])
d.Set("egress", egress)
d.Set("ingress", ingress)
return nil
}
func resourceAliyunNetworkAclEntriesUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
networkAclId := parts[0]
request := vpc.CreateUpdateNetworkAclEntriesRequest()
request.RegionId = client.RegionId
request.NetworkAclId = networkAclId
if d.HasChange("ingress") {
ingress := []vpc.UpdateNetworkAclEntriesIngressAclEntries{}
for _, e := range d.Get("ingress").([]interface{}) {
ingress = append(ingress, vpc.UpdateNetworkAclEntriesIngressAclEntries{
Protocol: e.(map[string]interface{})["protocol"].(string),
Port: e.(map[string]interface{})["port"].(string),
SourceCidrIp: e.(map[string]interface{})["source_cidr_ip"].(string),
NetworkAclEntryName: e.(map[string]interface{})["name"].(string),
EntryType: e.(map[string]interface{})["entry_type"].(string),
Policy: e.(map[string]interface{})["policy"].(string),
Description: e.(map[string]interface{})["description"].(string),
})
}
request.IngressAclEntries = &ingress
request.UpdateIngressAclEntries = requests.NewBoolean(true)
}
if d.HasChange("egress") {
egress := []vpc.UpdateNetworkAclEntriesEgressAclEntries{}
for _, e := range d.Get("egress").([]interface{}) {
egress = append(egress, vpc.UpdateNetworkAclEntriesEgressAclEntries{
Protocol: e.(map[string]interface{})["protocol"].(string),
Port: e.(map[string]interface{})["port"].(string),
DestinationCidrIp: e.(map[string]interface{})["destination_cidr_ip"].(string),
NetworkAclEntryName: e.(map[string]interface{})["name"].(string),
EntryType: e.(map[string]interface{})["entry_type"].(string),
Policy: e.(map[string]interface{})["policy"].(string),
Description: e.(map[string]interface{})["description"].(string),
})
}
request.EgressAclEntries = &egress
request.UpdateEgressAclEntries = requests.NewBoolean(true)
}
// Check the network acl status.
if err := vpcService.WaitForNetworkAcl(networkAclId, Available, DefaultTimeout); err != nil {
return WrapError(err)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.UpdateNetworkAclEntries(request)
})
//Waiting for deleting the network acl entries
if err != nil {
if IsExpectedErrors(err, []string{"TaskConflict"}) {
return resource.RetryableError(err)
}
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return vpcService.WaitForNetworkAcl(networkAclId, Available, DefaultTimeout)
}
func resourceAliyunNetworkAclEntriesDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
networkAclId := parts[0]
request := vpc.CreateUpdateNetworkAclEntriesRequest()
request.RegionId = client.RegionId
request.NetworkAclId = networkAclId
ingress := []vpc.UpdateNetworkAclEntriesIngressAclEntries{}
egress := []vpc.UpdateNetworkAclEntriesEgressAclEntries{}
request.IngressAclEntries = &ingress
request.EgressAclEntries = &egress
request.UpdateIngressAclEntries = requests.NewBoolean(true)
request.UpdateEgressAclEntries = requests.NewBoolean(true)
// Check the network acl status.
if err := vpcService.WaitForNetworkAcl(networkAclId, Available, DefaultTimeout); err != nil {
return WrapError(err)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.UpdateNetworkAclEntries(request)
})
//Waiting for deleting the network acl entries
if err != nil {
if IsExpectedErrors(err, []string{"TaskConflict"}) {
return resource.RetryableError(err)
}
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return vpcService.WaitForNetworkAcl(networkAclId, Available, DefaultTimeout)
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudOnsGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudOnsGroupCreate,
Read: resourceAlicloudOnsGroupRead,
Update: resourceAlicloudOnsGroupUpdate,
Delete: resourceAlicloudOnsGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(4 * time.Minute),
Delete: schema.DefaultTimeout(4 * time.Minute),
},
Schema: map[string]*schema.Schema{
"group_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validateOnsGroupId,
ConflictsWith: []string{"group_id"},
},
"group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validateOnsGroupId,
Deprecated: "Field 'group_id' has been deprecated from version 1.98.0. Use 'group_name' instead.",
ConflictsWith: []string{"group_name"},
},
"group_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"http", "tcp"}, false),
Default: "tcp",
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"read_enable": {
Type: schema.TypeBool,
Optional: true,
},
"remark": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(1, 256),
},
"tags": tagsSchema(),
},
}
}
func resourceAlicloudOnsGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "OnsGroupCreate"
request := make(map[string]interface{})
conn, err := client.NewOnsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("group_name"); ok {
request["GroupId"] = v
} else if v, ok := d.GetOk("group_id"); ok {
request["GroupId"] = v
} else {
return WrapError(Error(`[ERROR] Argument "group_id" or "group_name" must be set one!`))
}
if v, ok := d.GetOk("group_type"); ok {
request["GroupType"] = v
}
request["InstanceId"] = d.Get("instance_id")
if v, ok := d.GetOk("remark"); ok {
request["Remark"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-02-14"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ons_group", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["InstanceId"], ":", request["GroupId"]))
return resourceAlicloudOnsGroupUpdate(d, meta)
}
func resourceAlicloudOnsGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
onsService := OnsService{client}
object, err := onsService.DescribeOnsGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ons_group onsService.DescribeOnsGroup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("group_name", parts[1])
d.Set("group_id", parts[1])
d.Set("instance_id", parts[0])
d.Set("group_type", object["GroupType"])
d.Set("remark", object["Remark"])
d.Set("tags", tagsToMap(object["Tags"].(map[string]interface{})["Tag"]))
return nil
}
func resourceAlicloudOnsGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
onsService := OnsService{client}
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Partial(true)
if d.HasChange("tags") {
if err := onsService.SetResourceTags(d, "GROUP"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
if d.HasChange("read_enable") {
request := map[string]interface{}{
"GroupId": parts[1],
"InstanceId": parts[0],
}
request["ReadEnable"] = d.Get("read_enable")
action := "OnsGroupConsumerUpdate"
conn, err := client.NewOnsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-02-14"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("read_enable")
}
d.Partial(false)
return resourceAlicloudOnsGroupRead(d, meta)
}
func resourceAlicloudOnsGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "OnsGroupDelete"
var response map[string]interface{}
conn, err := client.NewOnsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"GroupId": parts[1],
"InstanceId": parts[0],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-02-14"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"AUTH_RESOURCE_OWNER_ERROR"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudOnsInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudOnsInstanceCreate,
Read: resourceAlicloudOnsInstanceRead,
Update: resourceAlicloudOnsInstanceUpdate,
Delete: resourceAlicloudOnsInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(6 * time.Minute),
Delete: schema.DefaultTimeout(6 * time.Minute),
},
Schema: map[string]*schema.Schema{
"instance_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"name"},
ValidateFunc: validation.StringLenBetween(3, 64),
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Field 'name' has been deprecated from version 1.97.0. Use 'instance_name' instead.",
ConflictsWith: []string{"instance_name"},
ValidateFunc: validation.StringLenBetween(3, 64),
},
"instance_type": {
Type: schema.TypeInt,
Computed: true,
},
"release_time": {
Type: schema.TypeString,
Computed: true,
},
"remark": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(0, 128),
},
"status": {
Type: schema.TypeInt,
Computed: true,
},
"instance_status": {
Type: schema.TypeInt,
Computed: true,
},
"tags": tagsSchema(),
},
}
}
func resourceAlicloudOnsInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "OnsInstanceCreate"
request := make(map[string]interface{})
conn, err := client.NewOnsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("instance_name"); ok {
request["InstanceName"] = v
} else if v, ok := d.GetOk("name"); ok {
request["InstanceName"] = v
} else {
return WrapError(Error(`[ERROR] Argument "name" or "instance_name" must be set one!`))
}
if v, ok := d.GetOk("remark"); ok {
request["Remark"] = v
}
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-02-14"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ons_instance", action, AlibabaCloudSdkGoERROR)
}
responseData := response["Data"].(map[string]interface{})
d.SetId(fmt.Sprint(responseData["InstanceId"]))
return resourceAlicloudOnsInstanceUpdate(d, meta)
}
func resourceAlicloudOnsInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
onsService := OnsService{client}
object, err := onsService.DescribeOnsInstance(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ons_instance onsService.DescribeOnsInstance Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_name", object["InstanceName"])
d.Set("name", object["InstanceName"])
d.Set("instance_type", formatInt(object["InstanceType"]))
d.Set("release_time", fmt.Sprint(formatInt(object["ReleaseTime"])))
d.Set("remark", object["Remark"])
d.Set("status", formatInt(object["InstanceStatus"]))
d.Set("instance_status", formatInt(object["InstanceStatus"]))
listTagResourcesObject, err := onsService.ListTagResources(d.Id(), "INSTANCE")
if err != nil {
return WrapError(err)
}
d.Set("tags", tagsToMap(listTagResourcesObject))
return nil
}
func resourceAlicloudOnsInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
onsService := OnsService{client}
var response map[string]interface{}
d.Partial(true)
if d.HasChange("tags") {
if err := onsService.SetResourceTags(d, "INSTANCE"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
update := false
request := map[string]interface{}{
"InstanceId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("instance_name") {
update = true
request["InstanceName"] = d.Get("instance_name")
}
if !d.IsNewResource() && d.HasChange("name") {
update = true
request["InstanceName"] = d.Get("name")
}
if !d.IsNewResource() && d.HasChange("remark") {
update = true
request["Remark"] = d.Get("remark")
}
if update {
action := "OnsInstanceUpdate"
conn, err := client.NewOnsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-02-14"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("name")
d.SetPartial("instance_name")
d.SetPartial("remark")
}
d.Partial(false)
return resourceAlicloudOnsInstanceRead(d, meta)
}
func resourceAlicloudOnsInstanceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "OnsInstanceDelete"
var response map[string]interface{}
conn, err := client.NewOnsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"InstanceId": d.Id(),
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-02-14"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"INSTANCE_NOT_EMPTY", "Throttling.User"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudOnsTopic() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudOnsTopicCreate,
Read: resourceAlicloudOnsTopicRead,
Update: resourceAlicloudOnsTopicUpdate,
Delete: resourceAlicloudOnsTopicDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(6 * time.Minute),
Delete: schema.DefaultTimeout(6 * time.Minute),
},
Schema: map[string]*schema.Schema{
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"message_type": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
ValidateFunc: validation.IntInSlice([]int{0, 1, 2, 4, 5}),
},
"perm": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{2, 4, 6}),
},
"remark": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(1, 128),
},
"tags": tagsSchema(),
"topic_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"topic"},
ValidateFunc: validation.StringLenBetween(1, 64),
},
"topic": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Deprecated: "Field 'topic' has been deprecated from version 1.97.0. Use 'topic_name' instead.",
ConflictsWith: []string{"topic_name"},
ValidateFunc: validation.StringLenBetween(1, 64),
},
},
}
}
func resourceAlicloudOnsTopicCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "OnsTopicCreate"
request := make(map[string]interface{})
conn, err := client.NewOnsClient()
if err != nil {
return WrapError(err)
}
request["InstanceId"] = d.Get("instance_id")
request["MessageType"] = d.Get("message_type")
if v, ok := d.GetOk("remark"); ok {
request["Remark"] = v
}
if v, ok := d.GetOk("topic_name"); ok {
request["Topic"] = v
} else if v, ok := d.GetOk("topic"); ok {
request["Topic"] = v
} else {
return WrapError(Error(`[ERROR] Argument "topic" or "topic_name" must be set one!`))
}
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-02-14"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ons_topic", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["InstanceId"], ":", request["Topic"]))
return resourceAlicloudOnsTopicUpdate(d, meta)
}
func resourceAlicloudOnsTopicRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
onsService := OnsService{client}
object, err := onsService.DescribeOnsTopic(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ons_topic onsService.DescribeOnsTopic Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("instance_id", parts[0])
d.Set("topic_name", parts[1])
d.Set("topic", parts[1])
d.Set("message_type", formatInt(object["MessageType"]))
d.Set("remark", object["Remark"])
d.Set("tags", tagsToMap(object["Tags"].(map[string]interface{})["Tag"]))
onsTopicStatusObject, err := onsService.OnsTopicStatus(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("perm", formatInt(onsTopicStatusObject["Perm"]))
return nil
}
func resourceAlicloudOnsTopicUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
onsService := OnsService{client}
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Partial(true)
if d.HasChange("tags") {
if err := onsService.SetResourceTags(d, "TOPIC"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
if d.HasChange("perm") {
request := map[string]interface{}{
"InstanceId": parts[0],
"Topic": parts[1],
}
request["Perm"] = d.Get("perm")
action := "OnsTopicUpdate"
conn, err := client.NewOnsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-02-14"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("perm")
}
d.Partial(false)
return resourceAlicloudOnsTopicRead(d, meta)
}
func resourceAlicloudOnsTopicDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "OnsTopicDelete"
var response map[string]interface{}
conn, err := client.NewOnsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"InstanceId": parts[0],
"Topic": parts[1],
}
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-02-14"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"AUTH_RESOURCE_OWNER_ERROR"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudOosApplication() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudOosApplicationCreate,
Read: resourceAlicloudOosApplicationRead,
Update: resourceAlicloudOosApplicationUpdate,
Delete: resourceAlicloudOosApplicationDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"application_name": {
Type: schema.TypeString,
Required: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"tags": tagsSchema(),
},
}
}
func resourceAlicloudOosApplicationCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateApplication"
request := make(map[string]interface{})
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["Name"] = d.Get("application_name")
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("tags"); ok {
respJson, err := convertMaptoJsonString(v.(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request["Tags"] = respJson
}
request["ClientToken"] = buildClientToken("CreateApplication")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_oos_application", action, AlibabaCloudSdkGoERROR)
}
responseApplication := response["Application"].(map[string]interface{})
d.SetId(fmt.Sprint(responseApplication["Name"]))
return resourceAlicloudOosApplicationRead(d, meta)
}
func resourceAlicloudOosApplicationRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
oosService := OosService{client}
object, err := oosService.DescribeOosApplication(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_oos_application oosService.DescribeOosApplication Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", object["Description"])
d.Set("application_name", object["Name"])
d.Set("resource_group_id", object["ResourceGroupId"])
d.Set("tags", tagsToMap(object["Tags"]))
return nil
}
func resourceAlicloudOosApplicationUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"Name": d.Id(),
}
if d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
}
request["RegionId"] = client.RegionId
if d.HasChange("tags") {
update = true
if v, ok := d.GetOk("tags"); ok {
respJson, err := convertMaptoJsonString(v.(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request["Tags"] = respJson
}
}
if update {
action := "UpdateApplication"
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudOosApplicationRead(d, meta)
}
func resourceAlicloudOosApplicationDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteApplication"
var response map[string]interface{}
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"Name": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Application"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudOosApplicationGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudOosApplicationGroupCreate,
Read: resourceAlicloudOosApplicationGroupRead,
Delete: resourceAlicloudOosApplicationGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"application_group_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"application_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"deploy_region_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"import_tag_key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"import_tag_value": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
},
}
}
func resourceAlicloudOosApplicationGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateApplicationGroup"
request := make(map[string]interface{})
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
request["Name"] = d.Get("application_group_name")
request["ApplicationName"] = d.Get("application_name")
request["DeployRegionId"] = d.Get("deploy_region_id")
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("import_tag_key"); ok {
if _, ok := d.GetOk("import_tag_value"); !ok {
return WrapError(fmt.Errorf("The tag key must be passed in at the same time as the tag value (import_tag_value) or none, not just one. "))
}
request["ImportTagKey"] = v
}
if v, ok := d.GetOk("import_tag_value"); ok {
if _, ok := d.GetOk("import_tag_key"); !ok {
return WrapError(fmt.Errorf("The tag value must be passed in at the same time as the tag key (import_tag_key) or none, not just one. "))
}
request["ImportTagValue"] = v
}
request["RegionId"] = client.RegionId
request["ClientToken"] = buildClientToken("CreateApplicationGroup")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_oos_application_group", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["ApplicationName"], ":", request["Name"]))
return resourceAlicloudOosApplicationGroupRead(d, meta)
}
func resourceAlicloudOosApplicationGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
oosService := OosService{client}
object, err := oosService.DescribeOosApplicationGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_oos_application_group oosService.DescribeOosApplicationGroup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("application_group_name", parts[1])
d.Set("application_name", parts[0])
d.Set("deploy_region_id", object["DeployRegionId"])
d.Set("description", object["Description"])
d.Set("import_tag_key", object["ImportTagKey"])
d.Set("import_tag_value", object["ImportTagValue"])
return nil
}
func resourceAlicloudOosApplicationGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteApplicationGroup"
var response map[string]interface{}
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"Name": parts[1],
"ApplicationName": parts[0],
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudOosExecution() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudOosExecutionCreate,
Read: resourceAlicloudOosExecutionRead,
Delete: resourceAlicloudOosExecutionDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(11 * time.Minute),
},
Schema: map[string]*schema.Schema{
"counters": {
Type: schema.TypeString,
Computed: true,
},
"create_date": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"end_date": {
Type: schema.TypeString,
Computed: true,
},
"executed_by": {
Type: schema.TypeString,
Computed: true,
},
"is_parent": {
Type: schema.TypeBool,
Computed: true,
},
"loop_mode": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"mode": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Automatic", "Debug"}, false),
Default: "Automatic",
},
"outputs": {
Type: schema.TypeString,
Computed: true,
},
"parameters": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "{}",
ValidateFunc: validation.ValidateJsonString,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
equal, _ := compareJsonTemplateAreEquivalent(old, new)
return equal
},
},
"parent_execution_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"ram_role": {
Type: schema.TypeString,
Computed: true,
},
"safety_check": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"start_date": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"status_message": {
Type: schema.TypeString,
Computed: true,
},
"template_content": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"template_id": {
Type: schema.TypeString,
Computed: true,
},
"template_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"template_version": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"update_date": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudOosExecutionCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
oosService := OosService{client}
var response map[string]interface{}
action := "StartExecution"
request := make(map[string]interface{})
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("loop_mode"); ok {
request["LoopMode"] = v
}
if v, ok := d.GetOk("mode"); ok {
request["Mode"] = v
}
if v, ok := d.GetOk("parameters"); ok {
request["Parameters"] = v
}
if v, ok := d.GetOk("parent_execution_id"); ok {
request["ParentExecutionId"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("safety_check"); ok {
request["SafetyCheck"] = v
}
if v, ok := d.GetOk("template_content"); ok {
request["TemplateContent"] = v
}
request["TemplateName"] = d.Get("template_name")
if v, ok := d.GetOk("template_version"); ok {
request["TemplateVersion"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_oos_execution", action, AlibabaCloudSdkGoERROR)
}
responseExecution := response["Execution"].(map[string]interface{})
d.SetId(fmt.Sprint(responseExecution["ExecutionId"]))
stateConf := BuildStateConf([]string{}, []string{"Success"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, oosService.OosExecutionStateRefreshFunc(d.Id(), []string{"Failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudOosExecutionRead(d, meta)
}
func resourceAlicloudOosExecutionRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
oosService := OosService{client}
object, err := oosService.DescribeOosExecution(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_oos_execution oosService.DescribeOosExecution Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("counters", object["Counters"])
d.Set("create_date", object["CreateDate"])
d.Set("end_date", object["EndDate"])
d.Set("executed_by", object["ExecutedBy"])
d.Set("is_parent", object["IsParent"])
d.Set("mode", object["Mode"])
d.Set("outputs", object["Outputs"])
d.Set("parameters", object["Parameters"])
d.Set("parent_execution_id", object["ParentExecutionId"])
d.Set("ram_role", object["RamRole"])
d.Set("start_date", object["StartDate"])
d.Set("status", object["Status"])
d.Set("status_message", object["StatusMessage"])
d.Set("template_id", object["TemplateId"])
d.Set("template_name", object["TemplateName"])
d.Set("template_version", object["TemplateVersion"])
d.Set("update_date", object["UpdateDate"])
return nil
}
func resourceAlicloudOosExecutionDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteExecutions"
var response map[string]interface{}
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ExecutionIds": convertListToJsonString(convertListStringToListInterface([]string{d.Id()})),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudOosParameter() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudOosParameterCreate,
Read: resourceAlicloudOosParameterRead,
Update: resourceAlicloudOosParameterUpdate,
Delete: resourceAlicloudOosParameterDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"constraints": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.ValidateJsonString,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
equal, _ := compareJsonTemplateAreEquivalent(old, new)
return equal
},
},
"description": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringLenBetween(1, 200),
},
"parameter_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.All(validation.StringDoesNotMatch(regexp.MustCompile(`(^ALIYUN.*)|(^ACS.*)|(^ALIBABA.*)|(^ALICLOUD.*)|(^OOS.*)`), "It cannot start with `ALIYUN`, `ACS`, `ALIBABA`, `ALICLOUD`, or `OOS`"), validation.StringMatch(regexp.MustCompile(`^[a-zA-Z0-9_/-]{2,180}`), "The name must be `2` to `180` characters in length, and can contain letters, digits, hyphens (-), forward slashes (/) and underscores (_).")),
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"tags": tagsSchema(),
"type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"String", "StringList"}, false),
},
"value": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(1, 4096),
},
},
}
}
func resourceAlicloudOosParameterCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateParameter"
request := make(map[string]interface{})
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("constraints"); ok {
request["Constraints"] = v
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("tags"); ok {
respJson, err := convertMaptoJsonString(v.(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request["Tags"] = respJson
}
request["Name"] = d.Get("parameter_name")
request["Type"] = d.Get("type")
request["Value"] = d.Get("value")
request["ClientToken"] = buildClientToken("CreateParameter")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_oos_parameter", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["Name"]))
return resourceAlicloudOosParameterRead(d, meta)
}
func resourceAlicloudOosParameterRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
oosService := OosService{client}
object, err := oosService.DescribeOosParameter(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_oos_parameter oosService.DescribeOosParameter Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("parameter_name", d.Id())
d.Set("constraints", object["Constraints"])
d.Set("description", object["Description"])
d.Set("resource_group_id", object["ResourceGroupId"])
d.Set("tags", tagsToMap(object["Tags"]))
d.Set("type", object["Type"])
d.Set("value", object["Value"])
return nil
}
func resourceAlicloudOosParameterUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"Name": d.Id(),
}
if d.HasChange("value") {
update = true
}
request["Value"] = d.Get("value")
if d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
}
if d.HasChange("resource_group_id") {
update = true
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
}
if d.HasChange("tags") {
update = true
if v, ok := d.GetOk("tags"); ok {
respJson, err := convertMaptoJsonString(v.(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request["Tags"] = respJson
}
}
if update {
action := "UpdateParameter"
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudOosParameterRead(d, meta)
}
func resourceAlicloudOosParameterDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteParameter"
var response map[string]interface{}
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"Name": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudOosPatchBaseline() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudOosPatchBaselineCreate,
Read: resourceAlicloudOosPatchBaselineRead,
Update: resourceAlicloudOosPatchBaselineUpdate,
Delete: resourceAlicloudOosPatchBaselineDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"approval_rules": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.ValidateJsonString,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
equal, _ := compareJsonTemplateAreEquivalent(old, new)
return equal
},
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"operation_system": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"AliyunLinux", "Anolis", "Centos", "Debian", "RedhatEnterpriseLinux", "Ubuntu", "Windows"}, false),
},
"patch_baseline_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudOosPatchBaselineCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreatePatchBaseline"
request := make(map[string]interface{})
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
request["ApprovalRules"] = d.Get("approval_rules")
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["OperationSystem"] = d.Get("operation_system")
request["Name"] = d.Get("patch_baseline_name")
request["ClientToken"] = buildClientToken("CreatePatchBaseline")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_oos_patch_baseline", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["Name"]))
return resourceAlicloudOosPatchBaselineRead(d, meta)
}
func resourceAlicloudOosPatchBaselineRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
oosService := OosService{client}
object, err := oosService.DescribeOosPatchBaseline(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_oos_patch_baseline oosService.DescribeOosPatchBaseline Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("patch_baseline_name", object["Name"])
approvalRules, err := convertMaptoJsonString(object["ApprovalRules"].(map[string]interface{}))
if err != nil {
return WrapError(err)
}
d.Set("approval_rules", approvalRules)
d.Set("description", object["Description"])
d.Set("operation_system", object["OperationSystem"])
return nil
}
func resourceAlicloudOosPatchBaselineUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"Name": d.Id(),
}
if d.HasChange("approval_rules") {
update = true
}
request["ApprovalRules"] = d.Get("approval_rules")
if d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
}
if update {
action := "UpdatePatchBaseline"
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("UpdatePatchBaseline")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudOosPatchBaselineRead(d, meta)
}
func resourceAlicloudOosPatchBaselineDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeletePatchBaseline"
var response map[string]interface{}
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"Name": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudOosSecretParameter() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudOosSecretParameterCreate,
Read: resourceAlicloudOosSecretParameterRead,
Update: resourceAlicloudOosSecretParameterUpdate,
Delete: resourceAlicloudOosSecretParameterDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"constraints": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.ValidateJsonString,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
equal, _ := compareJsonTemplateAreEquivalent(old, new)
return equal
},
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(1, 200),
},
"key_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"secret_parameter_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.All(validation.StringDoesNotMatch(regexp.MustCompile(`(^ALIYUN.*)|(^ACS.*)|(^ALIBABA.*)|(^ALICLOUD.*)|(^OOS.*)`), "It cannot start with `ALIYUN`, `ACS`, `ALIBABA`, `ALICLOUD`, or `OOS`"), validation.StringMatch(regexp.MustCompile(`^[a-zA-Z0-9_/-]{2,180}`), "The name must be `2` to `180` characters in length, and can contain letters, digits, hyphens (-), forward slashes (/) and underscores (_).")),
},
"tags": tagsSchema(),
"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Secret"}, false),
},
"value": {
Type: schema.TypeString,
Required: true,
Sensitive: true,
ValidateFunc: validation.StringLenBetween(1, 4096),
},
},
}
}
func resourceAlicloudOosSecretParameterCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateSecretParameter"
request := make(map[string]interface{})
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("constraints"); ok {
request["Constraints"] = v
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("key_id"); ok {
request["KeyId"] = v
}
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("tags"); ok {
respJson, err := convertMaptoJsonString(v.(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request["Tags"] = respJson
}
if v, ok := d.GetOk("type"); ok {
request["Type"] = v
}
request["RegionId"] = client.RegionId
request["Name"] = d.Get("secret_parameter_name")
request["Value"] = d.Get("value")
request["ClientToken"] = buildClientToken("CreateSecretParameter")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_oos_secret_parameter", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["Name"]))
return resourceAlicloudOosSecretParameterRead(d, meta)
}
func resourceAlicloudOosSecretParameterRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
oosService := OosService{client}
object, err := oosService.DescribeOosSecretParameter(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_oos_secret_parameter oosService.DescribeOosSecretParameter Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("secret_parameter_name", object["Name"])
d.Set("constraints", object["Constraints"])
d.Set("description", object["Description"])
d.Set("key_id", object["KeyId"])
d.Set("resource_group_id", object["ResourceGroupId"])
d.Set("tags", tagsToMap(object["Tags"]))
d.Set("type", object["Type"])
return nil
}
func resourceAlicloudOosSecretParameterUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"Name": d.Id(),
}
if d.HasChange("value") {
update = true
}
request["Value"] = d.Get("value")
if d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
}
request["RegionId"] = client.RegionId
if d.HasChange("resource_group_id") {
update = true
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
}
if d.HasChange("tags") {
update = true
if v, ok := d.GetOk("tags"); ok {
if v, err := convertMaptoJsonString(v.(map[string]interface{})); err == nil {
request["Tags"] = v
} else {
return WrapError(err)
}
}
}
if update {
action := "UpdateSecretParameter"
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudOosSecretParameterRead(d, meta)
}
func resourceAlicloudOosSecretParameterDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteSecretParameter"
var response map[string]interface{}
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"Name": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"strings"
"time"
"github.com/google/uuid"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudOosServiceSetting() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudOosServiceSettingCreate,
Read: resourceAlicloudOosServiceSettingRead,
Update: resourceAlicloudOosServiceSettingUpdate,
Delete: resourceAlicloudOosServiceSettingDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"delivery_oss_bucket_name": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOkExists("delivery_sls_enabled"); ok && v.(bool) {
return false
}
return true
},
},
"delivery_oss_enabled": {
Type: schema.TypeBool,
Optional: true,
},
"delivery_oss_key_prefix": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOkExists("delivery_sls_enabled"); ok && v.(bool) {
return false
}
return true
},
},
"delivery_sls_enabled": {
Type: schema.TypeBool,
Optional: true,
},
"delivery_sls_project_name": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOkExists("delivery_sls_enabled"); ok && v.(bool) {
return false
}
return true
},
},
},
}
}
func resourceAlicloudOosServiceSettingCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "SetServiceSettings"
request := make(map[string]interface{})
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("delivery_oss_bucket_name"); ok {
request["DeliveryOssBucketName"] = v
}
if v, ok := d.GetOkExists("delivery_oss_enabled"); ok {
request["DeliveryOssEnabled"] = v
}
if v, ok := d.GetOk("delivery_oss_key_prefix"); ok {
request["DeliveryOssKeyPrefix"] = v
}
if v, ok := d.GetOkExists("delivery_sls_enabled"); ok {
request["DeliverySlsEnabled"] = v
}
if v, ok := d.GetOk("delivery_sls_project_name"); ok {
request["DeliverySlsProjectName"] = v
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_oos_service_setting", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(strings.Trim(uuid.New().String(), "-")))
return resourceAlicloudOosServiceSettingRead(d, meta)
}
func resourceAlicloudOosServiceSettingRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
oosService := OosService{client}
object, err := oosService.DescribeOosServiceSetting(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_oos_service_setting oosService.DescribeOosServiceSetting Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("delivery_oss_bucket_name", object["DeliveryOssBucketName"])
d.Set("delivery_oss_enabled", object["DeliveryOssEnabled"])
d.Set("delivery_oss_key_prefix", object["DeliveryOssKeyPrefix"])
d.Set("delivery_sls_enabled", object["DeliverySlsEnabled"])
d.Set("delivery_sls_project_name", object["DeliverySlsProjectName"])
d.Set("rdc_enterprise_id", object["RdcEnterpriseId"])
return nil
}
func resourceAlicloudOosServiceSettingUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{}
if d.HasChange("delivery_oss_enabled") {
update = true
if v, ok := d.GetOkExists("delivery_oss_enabled"); ok {
request["DeliveryOssEnabled"] = v
}
}
if d.HasChange("delivery_oss_bucket_name") {
update = true
if v, ok := d.GetOk("delivery_oss_bucket_name"); ok {
request["DeliveryOssBucketName"] = v
}
}
if d.HasChange("delivery_oss_key_prefix") {
update = true
if v, ok := d.GetOk("delivery_oss_key_prefix"); ok {
request["DeliveryOssKeyPrefix"] = v
}
}
if d.HasChange("delivery_sls_enabled") {
update = true
if v, ok := d.GetOkExists("delivery_sls_enabled"); ok {
request["DeliverySlsEnabled"] = v
}
}
if d.HasChange("delivery_sls_project_name") {
update = true
if v, ok := d.GetOk("delivery_sls_project_name"); ok {
request["DeliverySlsProjectName"] = v
}
}
if update {
action := "SetServiceSettings"
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudOosServiceSettingRead(d, meta)
}
func resourceAlicloudOosServiceSettingDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudOosServiceSetting. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudOosStateConfiguration() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudOosStateConfigurationCreate,
Read: resourceAlicloudOosStateConfigurationRead,
Update: resourceAlicloudOosStateConfigurationUpdate,
Delete: resourceAlicloudOosStateConfigurationDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"configure_mode": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"ApplyAndAutoCorrect", "ApplyAndMonitor", "ApplyOnly"}, false),
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"parameters": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
equal, _ := compareJsonTemplateAreEquivalent(old, new)
return equal
},
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"schedule_expression": {
Type: schema.TypeString,
Required: true,
},
"schedule_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"rate"}, false),
},
"tags": tagsSchema(),
"targets": {
Type: schema.TypeString,
Required: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
equal, _ := compareJsonTemplateAreEquivalent(old, new)
return equal
},
},
"template_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ACS-ECS-InventoryDataCollection"}, false),
},
"template_version": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudOosStateConfigurationCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateStateConfiguration"
request := make(map[string]interface{})
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("configure_mode"); ok {
request["ConfigureMode"] = v
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("parameters"); ok {
request["Parameters"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
request["ScheduleExpression"] = d.Get("schedule_expression")
request["ScheduleType"] = d.Get("schedule_type")
if v, ok := d.GetOk("tags"); ok {
respJson, err := convertMaptoJsonString(v.(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request["Tags"] = respJson
}
request["Targets"] = d.Get("targets")
request["TemplateName"] = d.Get("template_name")
if v, ok := d.GetOk("template_version"); ok {
request["TemplateVersion"] = v
}
request["ClientToken"] = buildClientToken("CreateStateConfiguration")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_oos_state_configuration", action, AlibabaCloudSdkGoERROR)
}
responseStateConfiguration := response["StateConfiguration"].(map[string]interface{})
d.SetId(fmt.Sprint(responseStateConfiguration["StateConfigurationId"]))
return resourceAlicloudOosStateConfigurationRead(d, meta)
}
func resourceAlicloudOosStateConfigurationRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
oosService := OosService{client}
object, err := oosService.DescribeOosStateConfiguration(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_oos_state_configuration oosService.DescribeOosStateConfiguration Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("configure_mode", object["ConfigureMode"])
d.Set("description", object["Description"])
d.Set("parameters", object["Parameters"])
d.Set("resource_group_id", object["ResourceGroupId"])
d.Set("schedule_expression", object["ScheduleExpression"])
d.Set("schedule_type", object["ScheduleType"])
d.Set("tags", tagsToMap(object["Tags"]))
d.Set("targets", object["Targets"])
d.Set("template_name", object["TemplateName"])
d.Set("template_version", object["TemplateVersion"])
return nil
}
func resourceAlicloudOosStateConfigurationUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"StateConfigurationId": d.Id(),
}
if d.HasChange("configure_mode") {
update = true
if v, ok := d.GetOk("configure_mode"); ok {
request["ConfigureMode"] = v
}
}
if d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
}
if d.HasChange("parameters") {
update = true
if v, ok := d.GetOk("parameters"); ok {
request["Parameters"] = v
}
}
request["RegionId"] = client.RegionId
if d.HasChange("resource_group_id") {
update = true
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
}
if d.HasChange("schedule_expression") {
update = true
request["ScheduleExpression"] = d.Get("schedule_expression")
}
if d.HasChange("schedule_type") {
update = true
request["ScheduleType"] = d.Get("schedule_type")
}
if d.HasChange("tags") {
update = true
if v, ok := d.GetOk("tags"); ok {
respJson, err := convertMaptoJsonString(v.(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request["Tags"] = respJson
}
}
if d.HasChange("targets") {
update = true
request["Targets"] = d.Get("targets")
}
if update {
action := "UpdateStateConfiguration"
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("UpdateStateConfiguration")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudOosStateConfigurationRead(d, meta)
}
func resourceAlicloudOosStateConfigurationDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteStateConfigurations"
var response map[string]interface{}
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"StateConfigurationIds": convertListToJsonString([]interface{}{d.Id()}),
}
request["RegionId"] = client.RegionId
request["ClientToken"] = buildClientToken("DeleteStateConfigurations")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudOosTemplate() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudOosTemplateCreate,
Read: resourceAlicloudOosTemplateRead,
Update: resourceAlicloudOosTemplateUpdate,
Delete: resourceAlicloudOosTemplateDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"auto_delete_executions": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"content": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.ValidateJsonString,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
equal, _ := compareJsonTemplateAreEquivalent(old, new)
return equal
},
},
"created_by": {
Type: schema.TypeString,
Computed: true,
},
"created_date": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"has_trigger": {
Type: schema.TypeBool,
Computed: true,
},
"share_type": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
"template_format": {
Type: schema.TypeString,
Computed: true,
},
"template_id": {
Type: schema.TypeString,
Computed: true,
},
"template_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"template_type": {
Type: schema.TypeString,
Computed: true,
},
"template_version": {
Type: schema.TypeString,
Computed: true,
},
"updated_by": {
Type: schema.TypeString,
Computed: true,
},
"updated_date": {
Type: schema.TypeString,
Computed: true,
},
"version_name": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudOosTemplateCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateTemplate"
request := make(map[string]interface{})
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
request["Content"] = d.Get("content")
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("tags"); ok {
respJson, err := convertMaptoJsonString(v.(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request["Tags"] = respJson
}
request["TemplateName"] = d.Get("template_name")
if v, ok := d.GetOk("version_name"); ok {
request["VersionName"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_oos_template", action, AlibabaCloudSdkGoERROR)
}
responseTemplate := response["Template"].(map[string]interface{})
d.SetId(fmt.Sprint(responseTemplate["TemplateName"]))
return resourceAlicloudOosTemplateRead(d, meta)
}
func resourceAlicloudOosTemplateRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
oosService := OosService{client}
object, err := oosService.DescribeOosTemplate(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_oos_template oosService.DescribeOosTemplate Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("template_name", d.Id())
d.Set("created_by", object["CreatedBy"])
d.Set("created_date", object["CreatedDate"])
d.Set("description", object["Description"])
d.Set("has_trigger", object["HasTrigger"])
d.Set("share_type", object["ShareType"])
if v, ok := object["Tags"].(map[string]interface{}); ok {
d.Set("tags", tagsToMap(v))
}
d.Set("template_format", object["TemplateFormat"])
d.Set("template_id", object["TemplateId"])
d.Set("template_type", object["TemplateType"])
d.Set("template_version", object["TemplateVersion"])
d.Set("updated_by", object["UpdatedBy"])
d.Set("updated_date", object["UpdatedDate"])
return nil
}
func resourceAlicloudOosTemplateUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"TemplateName": d.Id(),
}
if d.HasChange("content") {
update = true
}
request["Content"] = d.Get("content")
request["RegionId"] = client.RegionId
if d.HasChange("tags") {
update = true
respJson, err := convertMaptoJsonString(d.Get("tags").(map[string]interface{}))
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_oos_template", "UpdateTemplate", AlibabaCloudSdkGoERROR)
}
request["Tags"] = respJson
}
if d.HasChange("version_name") {
update = true
request["VersionName"] = d.Get("version_name")
}
if update {
action := "UpdateTemplate"
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudOosTemplateRead(d, meta)
}
func resourceAlicloudOosTemplateDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteTemplate"
var response map[string]interface{}
conn, err := client.NewOosClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"TemplateName": d.Id(),
}
if v, ok := d.GetOkExists("auto_delete_executions"); ok {
request["AutoDeleteExecutions"] = v
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Template"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"encoding/json"
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudOpenSearchAppGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudOpenSearchAppGroupCreate,
Read: resourceAlicloudOpenSearchAppGroupRead,
Update: resourceAlicloudOpenSearchAppGroupUpdate,
Delete: resourceAlicloudOpenSearchAppGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"app_group_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"standard", "enhanced"}, false),
},
"payment_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo", "Subscription"}, false),
},
"quota": {
Type: schema.TypeSet,
Required: true,
ForceNew: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"doc_size": {
Type: schema.TypeInt,
Required: true,
},
"compute_resource": {
Type: schema.TypeInt,
Required: true,
},
"qps": {
Type: schema.TypeInt,
Optional: true,
},
"spec": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"opensearch.share.junior", "opensearch.share.common", "opensearch.share.compute", "opensearch.share.storage", "opensearch.private.common", "opensearch.private.compute", "opensearch.private.storage"}, false),
},
},
},
},
"order": {
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"duration": {
Type: schema.TypeInt,
Optional: true,
},
"pricing_cycle": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Year", "Month"}, false),
},
"auto_renew": {
Type: schema.TypeBool,
Optional: true,
},
},
},
},
"order_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"UPGRADE", "DOWNGRADE"}, false),
},
"charge_way": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"compute_resource", "qps"}, false),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"current_version": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudOpenSearchAppGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "/v4/openapi/app-groups"
body := make(map[string]interface{})
conn, err := client.NewOpensearchClient()
if err != nil {
return WrapError(err)
}
body["name"] = d.Get("app_group_name")
body["type"] = d.Get("type")
body["chargeType"] = convertOpenSearchAppGroupPaymentTypeRequest(d.Get("payment_type").(string))
quotaMaps := make(map[string]interface{}, 0)
for _, quotas := range d.Get("quota").(*schema.Set).List() {
quota := quotas.(map[string]interface{})
quotaMaps = map[string]interface{}{
"docSize": quota["doc_size"],
"computeResource": quota["compute_resource"],
"spec": quota["spec"],
"qps": quota["qps"],
}
}
body["quota"] = quotaMaps
if _, ok := d.GetOk("order"); ok {
orderMaps := make(map[string]interface{}, 0)
for _, quotas := range d.Get("order").(*schema.Set).List() {
quota := quotas.(map[string]interface{})
orderMaps = map[string]interface{}{
"duration": quota["duration"],
"pricingCycle": quota["pricing_cycle"],
"autoRenew": quota["auto_renew"],
}
}
body["order"] = orderMaps
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2017-12-25"), nil, StringPointer("POST"), StringPointer("AK"), StringPointer(action), nil, nil, body, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug("POST "+action, response, body)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_open_search_app_group", "POST "+action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return WrapError(fmt.Errorf("%s failed, response: %v", "POST "+action, response))
}
d.SetId(fmt.Sprint(response["result"].(map[string]interface{})["name"]))
return resourceAlicloudOpenSearchAppGroupUpdate(d, meta)
}
func resourceAlicloudOpenSearchAppGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
openSearchService := OpenSearchService{client}
object, err := openSearchService.DescribeOpenSearchAppGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_open_search_app_group openSearchService.DescribeOpenSearchAppGroup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("payment_type", convertOpenSearchAppGroupPaymentTypeResponse(object["chargeType"].(string)))
d.Set("app_group_name", object["name"])
d.Set("description", object["description"])
d.Set("type", object["type"])
d.Set("current_version", object["currentVersion"])
d.Set("status", object["status"])
d.Set("charge_way", convertOpenSearchchargingWayResponse(object["chargingWay"].(json.Number).String()))
quotaSli := make([]map[string]interface{}, 0)
if _, exist := object["quota"]; exist {
quotaval := object["quota"].(map[string]interface{})
quotaSli = append(quotaSli, map[string]interface{}{
"doc_size": quotaval["docSize"],
"compute_resource": quotaval["computeResource"],
"spec": quotaval["spec"],
"qps": quotaval["qps"],
})
}
d.Set("quota", quotaSli)
return nil
}
func resourceAlicloudOpenSearchAppGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
openSearchService := OpenSearchService{client}
var response map[string]interface{}
update := false
body := map[string]interface{}{
"appGroupIdentity": d.Id(),
}
if d.HasChange("description") || d.IsNewResource() {
if v, ok := d.GetOk("description"); ok {
body["description"] = v
update = true
}
}
if d.HasChange("current_version") || d.IsNewResource() {
if v, ok := d.GetOk("current_version"); ok {
body["currentVersion"] = v
update = true
}
}
if d.HasChange("charge_way") || d.IsNewResource() {
if v, ok := d.GetOk("charge_way"); ok {
body["chargingWay"] = convertOpenSearchchargingWayRequest(v.(string))
update = true
}
}
if update {
action := "/v4/openapi/app-groups/" + d.Id()
conn, err := client.NewOpensearchClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2017-12-25"), nil, StringPointer("PUT"), StringPointer("AK"), StringPointer(action), nil, nil, body, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug("PUT "+action, response, body)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return WrapError(fmt.Errorf("%s failed, response: %v", "POST "+action, response))
}
if code, exist := response["code"]; exist && code.(string) != "Success" {
return WrapError(Error("Update AppGroup failed for " + response["message"].(string)))
}
}
update = false
if d.HasChange("quota") && !d.IsNewResource() {
update = true
if val, exist := d.GetOk("order_type"); exist {
body["orderType"] = val
} else {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is updated ", "order_type", "quota"))
}
for _, quotas := range d.Get("quota").(*schema.Set).List() {
quota := quotas.(map[string]interface{})
body["docSize"] = quota["doc_size"]
body["computeResource"] = quota["compute_resource"]
body["spec"] = quota["spec"]
}
}
if update {
action := fmt.Sprintf("/v4/openapi/app-groups/%s/quota", d.Id())
conn, err := client.NewOpensearchClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2017-12-25"), nil, StringPointer("PUT"), StringPointer("AK"), StringPointer(action), nil, nil, body, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug("PUT "+action, response, body)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return WrapError(fmt.Errorf("%s failed, response: %v", "POST "+action, response))
}
if code, exist := response["code"]; exist && code.(string) != "Success" {
return WrapError(Error("Update AppGroup failed for " + response["message"].(string)))
}
}
stateConf := BuildStateConf([]string{}, []string{"config_pending", "normal"}, d.Timeout(schema.TimeoutDelete), 5*time.Second, openSearchService.OpenSearchAppStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudOpenSearchAppGroupRead(d, meta)
}
func resourceAlicloudOpenSearchAppGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
if d.Get("payment_type").(string) == "Subscription" {
log.Printf("[WARN] Cannot destroy resource: alicloud_open_search_app_group. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
action := "/v4/openapi/app-groups/" + d.Id()
var response map[string]interface{}
conn, err := client.NewOpensearchClient()
if err != nil {
return WrapError(err)
}
request := map[string]*string{
"appGroupIdentity": StringPointer(d.Id()),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2017-12-25"), nil, StringPointer("DELETE"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug("DELETE "+action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func convertOpenSearchAppGroupPaymentTypeRequest(source string) string {
switch source {
case "PayAsYouGo":
return "POSTPAY"
case "Subscription":
return "PREPAY"
}
return source
}
func convertOpenSearchAppGroupPaymentTypeResponse(source string) string {
switch source {
case "POSTPAY":
return "PayAsYouGo"
case "PREPAY":
return "Subscription"
}
return source
}
func convertOpenSearchchargingWayRequest(source string) interface{} {
switch source {
case "compute_resource":
return 1
case "qps":
return 2
}
return source
}
func convertOpenSearchchargingWayResponse(source string) interface{} {
switch source {
case "1":
return "compute_resource"
case "2":
return "qps"
}
return source
}
package alicloud
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/hashcode"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudOssBucket() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudOssBucketCreate,
Read: resourceAlicloudOssBucketRead,
Update: resourceAlicloudOssBucketUpdate,
Delete: resourceAlicloudOssBucketDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"bucket": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(3, 63),
Default: resource.PrefixedUniqueId("tf-oss-bucket-"),
},
"acl": {
Type: schema.TypeString,
Default: oss.ACLPrivate,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"private", "public-read", "public-read-write"}, false),
},
"cors_rule": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"allowed_headers": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"allowed_methods": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"allowed_origins": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"expose_headers": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"max_age_seconds": {
Type: schema.TypeInt,
Optional: true,
},
},
},
MaxItems: 10,
},
"website": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"index_document": {
Type: schema.TypeString,
Required: true,
},
"error_document": {
Type: schema.TypeString,
Optional: true,
},
},
},
MaxItems: 1,
},
"logging": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"target_bucket": {
Type: schema.TypeString,
Required: true,
},
"target_prefix": {
Type: schema.TypeString,
Optional: true,
},
},
},
MaxItems: 1,
},
"logging_isenable": {
Type: schema.TypeBool,
Optional: true,
Deprecated: "Deprecated from 1.37.0. When `logging` is set, the bucket logging will be able.",
},
"referer_config": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"allow_empty": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"referers": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
MaxItems: 1,
},
"lifecycle_rule": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringLenBetween(0, 255),
},
"prefix": {
Type: schema.TypeString,
Optional: true,
Default: "",
},
"enabled": {
Type: schema.TypeBool,
Required: true,
},
"expiration": {
Type: schema.TypeSet,
Optional: true,
Set: expirationHash,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"date": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateOssBucketDateTimestamp,
},
"created_before_date": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateOssBucketDateTimestamp,
},
"days": {
Type: schema.TypeInt,
Optional: true,
},
"expired_object_delete_marker": {
Type: schema.TypeBool,
Optional: true,
},
},
},
},
"transitions": {
Type: schema.TypeSet,
Optional: true,
Set: transitionsHash,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"created_before_date": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateOssBucketDateTimestamp,
},
"days": {
Type: schema.TypeInt,
Optional: true,
},
"storage_class": {
Type: schema.TypeString,
Default: oss.StorageStandard,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{
string(oss.StorageStandard),
string(oss.StorageIA),
string(oss.StorageArchive),
}, false),
},
},
},
},
"abort_multipart_upload": {
Type: schema.TypeSet,
Optional: true,
Set: abortMultipartUploadHash,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"created_before_date": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateOssBucketDateTimestamp,
},
"days": {
Type: schema.TypeInt,
Optional: true,
},
},
},
},
"noncurrent_version_expiration": {
Type: schema.TypeSet,
Optional: true,
Set: expirationHash,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"days": {
Type: schema.TypeInt,
Required: true,
},
},
},
},
"noncurrent_version_transition": {
Type: schema.TypeSet,
Optional: true,
Set: transitionsHash,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"days": {
Type: schema.TypeInt,
Required: true,
},
"storage_class": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
string(oss.StorageStandard),
string(oss.StorageIA),
string(oss.StorageArchive),
}, false),
},
},
},
},
},
},
MaxItems: 1000,
},
"policy": {
Type: schema.TypeString,
Optional: true,
},
"creation_date": {
Type: schema.TypeString,
Computed: true,
},
"extranet_endpoint": {
Type: schema.TypeString,
Computed: true,
},
"intranet_endpoint": {
Type: schema.TypeString,
Computed: true,
},
"location": {
Type: schema.TypeString,
Computed: true,
},
"owner": {
Type: schema.TypeString,
Computed: true,
},
"storage_class": {
Type: schema.TypeString,
Default: oss.StorageStandard,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
string(oss.StorageStandard),
string(oss.StorageIA),
string(oss.StorageArchive),
}, false),
},
"redundancy_type": {
Type: schema.TypeString,
Default: oss.RedundancyLRS,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
string(oss.RedundancyLRS),
string(oss.RedundancyZRS),
}, false),
},
"server_side_encryption_rule": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"sse_algorithm": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
ServerSideEncryptionAes256,
ServerSideEncryptionKMS,
}, false),
},
"kms_master_key_id": {
Type: schema.TypeString,
Optional: true,
},
},
},
MaxItems: 1,
},
"tags": tagsSchema(),
"force_destroy": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"versioning": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"status": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
"Enabled",
"Suspended",
}, false),
},
},
},
MaxItems: 1,
},
"transfer_acceleration": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enabled": {
Type: schema.TypeBool,
Required: true,
},
},
},
MaxItems: 1,
},
},
}
}
func resourceAlicloudOssBucketCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := map[string]string{"bucketName": d.Get("bucket").(string)}
var requestInfo *oss.Client
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return ossClient.IsBucketExist(request["bucketName"])
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_oss_bucket", "IsBucketExist", AliyunOssGoSdk)
}
addDebug("IsBucketExist", raw, requestInfo, request)
isExist, _ := raw.(bool)
if isExist {
return WrapError(Error("[ERROR] The specified bucket name: %#v is not available. The bucket namespace is shared by all users of the OSS system. Please select a different name and try again.", request["bucketName"]))
}
type Request struct {
BucketName string
StorageClassOption oss.Option
RedundancyTypeOption oss.Option
}
req := Request{
d.Get("bucket").(string),
oss.StorageClass(oss.StorageClassType(d.Get("storage_class").(string))),
oss.RedundancyType(oss.DataRedundancyType(d.Get("redundancy_type").(string))),
}
raw, err = client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
return nil, ossClient.CreateBucket(req.BucketName, req.StorageClassOption, req.RedundancyTypeOption)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_oss_bucket", "CreateBucket", AliyunOssGoSdk)
}
addDebug("CreateBucket", raw, requestInfo, req)
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err = client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
return ossClient.IsBucketExist(request["bucketName"])
})
if err != nil {
return resource.NonRetryableError(err)
}
isExist, _ := raw.(bool)
if !isExist {
return resource.RetryableError(Error("Trying to ensure new OSS bucket %#v has been created successfully.", request["bucketName"]))
}
addDebug("IsBucketExist", raw, requestInfo, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_oss_bucket", "IsBucketExist", AliyunOssGoSdk)
}
// Assign the bucket name as the resource ID
d.SetId(request["bucketName"])
return resourceAlicloudOssBucketUpdate(d, meta)
}
func resourceAlicloudOssBucketRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ossService := OssService{client}
object, err := ossService.DescribeOssBucket(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("bucket", d.Id())
d.Set("acl", object.BucketInfo.ACL)
d.Set("creation_date", object.BucketInfo.CreationDate.Format("2006-01-02"))
d.Set("extranet_endpoint", object.BucketInfo.ExtranetEndpoint)
d.Set("intranet_endpoint", object.BucketInfo.IntranetEndpoint)
d.Set("location", object.BucketInfo.Location)
d.Set("owner", object.BucketInfo.Owner.ID)
d.Set("storage_class", object.BucketInfo.StorageClass)
d.Set("redundancy_type", object.BucketInfo.RedundancyType)
if &object.BucketInfo.SseRule != nil {
if len(object.BucketInfo.SseRule.SSEAlgorithm) > 0 && object.BucketInfo.SseRule.SSEAlgorithm != "None" {
rule := make(map[string]interface{})
rule["sse_algorithm"] = object.BucketInfo.SseRule.SSEAlgorithm
if object.BucketInfo.SseRule.KMSMasterKeyID != "" {
rule["kms_master_key_id"] = object.BucketInfo.SseRule.KMSMasterKeyID
}
data := make([]map[string]interface{}, 0)
data = append(data, rule)
d.Set("server_side_encryption_rule", data)
}
}
if object.BucketInfo.Versioning != "" {
data := map[string]interface{}{
"status": object.BucketInfo.Versioning,
}
versioning := make([]map[string]interface{}, 0)
versioning = append(versioning, data)
d.Set("versioning", versioning)
}
request := map[string]string{"bucketName": d.Id()}
var requestInfo *oss.Client
// Read the CORS
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return ossClient.GetBucketCORS(request["bucketName"])
})
if err != nil && !IsExpectedErrors(err, []string{"NoSuchCORSConfiguration"}) {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "GetBucketCORS", AliyunOssGoSdk)
}
addDebug("GetBucketCORS", raw, requestInfo, request)
cors, _ := raw.(oss.GetBucketCORSResult)
rules := make([]map[string]interface{}, 0, len(cors.CORSRules))
for _, r := range cors.CORSRules {
rule := make(map[string]interface{})
rule["allowed_headers"] = r.AllowedHeader
rule["allowed_methods"] = r.AllowedMethod
rule["allowed_origins"] = r.AllowedOrigin
rule["expose_headers"] = r.ExposeHeader
rule["max_age_seconds"] = r.MaxAgeSeconds
rules = append(rules, rule)
}
if err := d.Set("cors_rule", rules); err != nil {
return WrapError(err)
}
// Read the website configuration
raw, err = client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
return ossClient.GetBucketWebsite(d.Id())
})
if err != nil && !IsExpectedErrors(err, []string{"NoSuchWebsiteConfiguration"}) {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "GetBucketWebsite", AliyunOssGoSdk)
}
addDebug("GetBucketWebsite", raw, requestInfo, request)
ws, _ := raw.(oss.GetBucketWebsiteResult)
websites := make([]map[string]interface{}, 0)
if err == nil && &ws != nil {
w := make(map[string]interface{})
if v := &ws.IndexDocument; v != nil {
w["index_document"] = v.Suffix
}
if v := &ws.ErrorDocument; v != nil {
w["error_document"] = v.Key
}
websites = append(websites, w)
}
if err := d.Set("website", websites); err != nil {
return WrapError(err)
}
// Read the logging configuration
raw, err = client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
return ossClient.GetBucketLogging(d.Id())
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "GetBucketLogging", AliyunOssGoSdk)
}
addDebug("GetBucketLogging", raw, requestInfo, request)
logging, _ := raw.(oss.GetBucketLoggingResult)
if &logging != nil {
enable := logging.LoggingEnabled
if &enable != nil {
lgs := make([]map[string]interface{}, 0)
tb := logging.LoggingEnabled.TargetBucket
tp := logging.LoggingEnabled.TargetPrefix
if tb != "" || tp != "" {
lgs = append(lgs, map[string]interface{}{
"target_bucket": tb,
"target_prefix": tp,
})
}
if err := d.Set("logging", lgs); err != nil {
return WrapError(err)
}
}
}
// Read the bucket referer
raw, err = client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
return ossClient.GetBucketReferer(d.Id())
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "GetBucketReferer", AliyunOssGoSdk)
}
addDebug("GetBucketReferer", raw, requestInfo, request)
referers := make([]map[string]interface{}, 0)
referer, _ := raw.(oss.GetBucketRefererResult)
if len(referer.RefererList) > 0 {
referers = append(referers, map[string]interface{}{
"allow_empty": referer.AllowEmptyReferer,
"referers": referer.RefererList,
})
if err := d.Set("referer_config", referers); err != nil {
return WrapError(err)
}
}
// Read the lifecycle rule configuration
raw, err = client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
return ossClient.GetBucketLifecycle(d.Id())
})
if err != nil && !ossNotFoundError(err) {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "GetBucketLifecycle", AliyunOssGoSdk)
}
addDebug("GetBucketLifecycle", raw, requestInfo, request)
lrules := make([]map[string]interface{}, 0)
lifecycle, _ := raw.(oss.GetBucketLifecycleResult)
for _, lifecycleRule := range lifecycle.Rules {
rule := make(map[string]interface{})
rule["id"] = lifecycleRule.ID
rule["prefix"] = lifecycleRule.Prefix
if LifecycleRuleStatus(lifecycleRule.Status) == ExpirationStatusEnabled {
rule["enabled"] = true
} else {
rule["enabled"] = false
}
// expiration
if lifecycleRule.Expiration != nil {
e := make(map[string]interface{})
if lifecycleRule.Expiration.Date != "" {
t, err := time.Parse("2006-01-02T15:04:05.000Z", lifecycleRule.Expiration.Date)
if err != nil {
return WrapError(err)
}
e["date"] = t.Format("2006-01-02")
}
if lifecycleRule.Expiration.CreatedBeforeDate != "" {
t, err := time.Parse("2006-01-02T15:04:05.000Z", lifecycleRule.Expiration.CreatedBeforeDate)
if err != nil {
return WrapError(err)
}
e["created_before_date"] = t.Format("2006-01-02")
}
if lifecycleRule.Expiration.ExpiredObjectDeleteMarker != nil {
e["expired_object_delete_marker"] = *lifecycleRule.Expiration.ExpiredObjectDeleteMarker
}
e["days"] = int(lifecycleRule.Expiration.Days)
rule["expiration"] = schema.NewSet(expirationHash, []interface{}{e})
}
// transitions
if len(lifecycleRule.Transitions) != 0 {
var eSli []interface{}
for _, transition := range lifecycleRule.Transitions {
e := make(map[string]interface{})
if transition.CreatedBeforeDate != "" {
t, err := time.Parse("2006-01-02T15:04:05.000Z", transition.CreatedBeforeDate)
if err != nil {
return WrapError(err)
}
e["created_before_date"] = t.Format("2006-01-02")
}
e["days"] = transition.Days
e["storage_class"] = string(transition.StorageClass)
eSli = append(eSli, e)
}
rule["transitions"] = schema.NewSet(transitionsHash, eSli)
}
// abort_multipart_upload
if lifecycleRule.AbortMultipartUpload != nil {
e := make(map[string]interface{})
if lifecycleRule.AbortMultipartUpload.CreatedBeforeDate != "" {
t, err := time.Parse("2006-01-02T15:04:05.000Z", lifecycleRule.AbortMultipartUpload.CreatedBeforeDate)
if err != nil {
return WrapError(err)
}
e["created_before_date"] = t.Format("2006-01-02")
}
valDays := int(lifecycleRule.AbortMultipartUpload.Days)
if valDays > 0 {
e["days"] = int(lifecycleRule.AbortMultipartUpload.Days)
}
rule["abort_multipart_upload"] = schema.NewSet(abortMultipartUploadHash, []interface{}{e})
}
// NoncurrentVersionExpiration
if lifecycleRule.NonVersionExpiration != nil {
e := make(map[string]interface{})
e["days"] = int(lifecycleRule.NonVersionExpiration.NoncurrentDays)
rule["noncurrent_version_expiration"] = schema.NewSet(expirationHash, []interface{}{e})
}
// NoncurrentVersionTransitions
if len(lifecycleRule.NonVersionTransitions) != 0 {
var eSli []interface{}
for _, transition := range lifecycleRule.NonVersionTransitions {
e := make(map[string]interface{})
e["days"] = transition.NoncurrentDays
e["storage_class"] = string(transition.StorageClass)
eSli = append(eSli, e)
}
rule["noncurrent_version_transition"] = schema.NewSet(transitionsHash, eSli)
}
lrules = append(lrules, rule)
}
if err := d.Set("lifecycle_rule", lrules); err != nil {
return WrapError(err)
}
// Read Policy
raw, err = client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
params := map[string]interface{}{}
params["policy"] = nil
return ossClient.Conn.Do("GET", d.Id(), "", params, nil, nil, 0, nil)
})
if err != nil && !ossNotFoundError(err) {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "GetPolicyByConn", AliyunOssGoSdk)
}
addDebug("GetPolicyByConn", raw, requestInfo, request)
policy := ""
if err == nil {
rawResp := raw.(*oss.Response)
defer rawResp.Body.Close()
rawData, err := ioutil.ReadAll(rawResp.Body)
if err != nil {
return WrapError(err)
}
policy = string(rawData)
}
if err := d.Set("policy", policy); err != nil {
return WrapError(err)
}
// Read tags
raw, err = client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
return ossClient.GetBucketTagging(d.Id())
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "GetBucketTagging", AliyunOssGoSdk)
}
addDebug("GetBucketTagging", raw, requestInfo, request)
tagging, _ := raw.(oss.GetBucketTaggingResult)
tagsMap := make(map[string]string)
if len(tagging.Tags) > 0 {
for _, t := range tagging.Tags {
tagsMap[t.Key] = t.Value
}
}
if err := d.Set("tags", tagsMap); err != nil {
return WrapError(err)
}
// Read the bucket transfer acceleration status
raw, err = client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
return ossClient.GetBucketTransferAcc(d.Id())
})
if err != nil && !ossNotFoundError(err) && !IsExpectedErrors(err, []string{"TransferAccelerationDisabled"}) {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "GetBucketTransferAcc", AliyunOssGoSdk)
}
acc, _ := raw.(oss.TransferAccConfiguration)
accMap := make([]map[string]interface{}, 0)
if err == nil && &acc != nil {
data := map[string]interface{}{
"enabled": acc.Enabled,
}
accMap = append(accMap, data)
}
if err := d.Set("transfer_acceleration", accMap); err != nil {
return WrapError(err)
}
return nil
}
func resourceAlicloudOssBucketUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
d.Partial(true)
if d.HasChange("acl") {
request := map[string]string{"bucketName": d.Id(), "bucketACL": d.Get("acl").(string)}
var requestInfo *oss.Client
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return nil, ossClient.SetBucketACL(d.Id(), oss.ACLType(d.Get("acl").(string)))
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "SetBucketACL", AliyunOssGoSdk)
}
addDebug("SetBucketACL", raw, requestInfo, request)
d.SetPartial("acl")
}
if d.HasChange("cors_rule") {
if err := resourceAlicloudOssBucketCorsUpdate(client, d); err != nil {
return WrapError(err)
}
d.SetPartial("cors_rule")
}
if d.HasChange("website") {
if err := resourceAlicloudOssBucketWebsiteUpdate(client, d); err != nil {
return WrapError(err)
}
d.SetPartial("website")
}
if d.HasChange("logging") {
if err := resourceAlicloudOssBucketLoggingUpdate(client, d); err != nil {
return WrapError(err)
}
d.SetPartial("logging")
}
if d.HasChange("referer_config") {
if err := resourceAlicloudOssBucketRefererUpdate(client, d); err != nil {
return WrapError(err)
}
d.SetPartial("referer_config")
}
if d.HasChange("lifecycle_rule") {
if err := resourceAlicloudOssBucketLifecycleRuleUpdate(client, d); err != nil {
return WrapError(err)
}
d.SetPartial("lifecycle_rule")
}
if d.HasChange("policy") {
if err := resourceAlicloudOssBucketPolicyUpdate(client, d); err != nil {
return WrapError(err)
}
d.SetPartial("policy")
}
if d.HasChange("server_side_encryption_rule") {
if err := resourceAlicloudOssBucketEncryptionUpdate(client, d); err != nil {
return WrapError(err)
}
d.SetPartial("server_side_encryption_rule")
}
if d.HasChange("tags") {
if err := resourceAlicloudOssBucketTaggingUpdate(client, d); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
if d.HasChange("versioning") {
if err := resourceAlicloudOssBucketVersioningUpdate(client, d); err != nil {
return WrapError(err)
}
d.SetPartial("versioning")
}
if d.HasChange("transfer_acceleration") {
if err := resourceAlicloudOssBucketTransferAccUpdate(client, d); err != nil {
return WrapError(err)
}
d.SetPartial("transfer_acceleration")
}
d.Partial(false)
return resourceAlicloudOssBucketRead(d, meta)
}
func resourceAlicloudOssBucketCorsUpdate(client *connectivity.AliyunClient, d *schema.ResourceData) error {
cors := d.Get("cors_rule").([]interface{})
var requestInfo *oss.Client
if cors == nil || len(cors) == 0 {
err := resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return nil, ossClient.DeleteBucketCORS(d.Id())
})
if err != nil {
return resource.NonRetryableError(err)
}
addDebug("DeleteBucketCORS", raw, requestInfo, map[string]string{"bucketName": d.Id()})
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DeleteBucketCORS", AliyunOssGoSdk)
}
return nil
}
// Put CORS
rules := make([]oss.CORSRule, 0, len(cors))
for _, c := range cors {
corsMap := c.(map[string]interface{})
rule := oss.CORSRule{}
for k, v := range corsMap {
log.Printf("[DEBUG] OSS bucket: %s, put CORS: %#v, %#v", d.Id(), k, v)
if k == "max_age_seconds" {
rule.MaxAgeSeconds = v.(int)
} else {
rMap := make([]string, len(v.([]interface{})))
for i, vv := range v.([]interface{}) {
rMap[i] = vv.(string)
}
switch k {
case "allowed_headers":
rule.AllowedHeader = rMap
case "allowed_methods":
rule.AllowedMethod = rMap
case "allowed_origins":
rule.AllowedOrigin = rMap
case "expose_headers":
rule.ExposeHeader = rMap
}
}
}
rules = append(rules, rule)
}
log.Printf("[DEBUG] Oss bucket: %s, put CORS: %#v", d.Id(), cors)
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return nil, ossClient.SetBucketCORS(d.Id(), rules)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "SetBucketCORS", AliyunOssGoSdk)
}
addDebug("SetBucketCORS", raw, requestInfo, map[string]interface{}{
"bucketName": d.Id(),
"corsRules": rules,
})
return nil
}
func resourceAlicloudOssBucketWebsiteUpdate(client *connectivity.AliyunClient, d *schema.ResourceData) error {
ws := d.Get("website").([]interface{})
var requestInfo *oss.Client
if ws == nil || len(ws) == 0 {
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return nil, ossClient.DeleteBucketWebsite(d.Id())
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DeleteBucketWebsite", AliyunOssGoSdk)
}
addDebug("DeleteBucketWebsite", raw, requestInfo, map[string]string{"bucketName": d.Id()})
return nil
}
var index_document, error_document string
w := ws[0].(map[string]interface{})
if v, ok := w["index_document"]; ok {
index_document = v.(string)
}
if v, ok := w["error_document"]; ok {
error_document = v.(string)
}
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return nil, ossClient.SetBucketWebsite(d.Id(), index_document, error_document)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "SetBucketWebsite", AliyunOssGoSdk)
}
addDebug("SetBucketWebsite", raw, requestInfo, map[string]interface{}{
"bucketName": d.Id(),
"indexDocument": index_document,
"errorDocument": error_document,
})
return nil
}
func resourceAlicloudOssBucketLoggingUpdate(client *connectivity.AliyunClient, d *schema.ResourceData) error {
logging := d.Get("logging").([]interface{})
var requestInfo *oss.Client
if logging == nil || len(logging) == 0 {
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return nil, ossClient.DeleteBucketLogging(d.Id())
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DeleteBucketLogging", AliyunOssGoSdk)
}
addDebug("DeleteBucketLogging", raw, requestInfo, map[string]string{"bucketName": d.Id()})
return nil
}
c := logging[0].(map[string]interface{})
var target_bucket, target_prefix string
if v, ok := c["target_bucket"]; ok {
target_bucket = v.(string)
}
if v, ok := c["target_prefix"]; ok {
target_prefix = v.(string)
}
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return nil, ossClient.SetBucketLogging(d.Id(), target_bucket, target_prefix, target_bucket != "" || target_prefix != "")
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "SetBucketLogging", AliyunOssGoSdk)
}
addDebug("SetBucketLogging", raw, requestInfo, map[string]interface{}{
"bucketName": d.Id(),
"targetBucket": target_bucket,
"targetPrefix": target_prefix,
"isEnable": target_bucket != "",
})
return nil
}
func resourceAlicloudOssBucketRefererUpdate(client *connectivity.AliyunClient, d *schema.ResourceData) error {
config := d.Get("referer_config").([]interface{})
var requestInfo *oss.Client
if config == nil || len(config) < 1 {
log.Printf("[DEBUG] OSS set bucket referer as nil")
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return nil, ossClient.SetBucketReferer(d.Id(), nil, true)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "SetBucketReferer", AliyunOssGoSdk)
}
addDebug("SetBucketReferer", raw, requestInfo, map[string]interface{}{
"allowEmptyReferer": true,
"bucketName": d.Id(),
})
return nil
}
c := config[0].(map[string]interface{})
var allow bool
var referers []string
if v, ok := c["allow_empty"]; ok {
allow = v.(bool)
}
if v, ok := c["referers"]; ok {
for _, referer := range v.([]interface{}) {
referers = append(referers, referer.(string))
}
}
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return nil, ossClient.SetBucketReferer(d.Id(), referers, allow)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "SetBucketReferer", AliyunOssGoSdk)
}
addDebug("SetBucketReferer", raw, requestInfo, map[string]interface{}{
"bucketName": d.Id(),
"referers": referers,
"allowEmptyReferer": allow,
})
return nil
}
func resourceAlicloudOssBucketLifecycleRuleUpdate(client *connectivity.AliyunClient, d *schema.ResourceData) error {
bucket := d.Id()
lifecycleRules := d.Get("lifecycle_rule").([]interface{})
var requestInfo *oss.Client
if lifecycleRules == nil || len(lifecycleRules) == 0 {
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return nil, ossClient.DeleteBucketLifecycle(bucket)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DeleteBucketLifecycle", AliyunOssGoSdk)
}
addDebug("DeleteBucketLifecycle", raw, requestInfo, map[string]interface{}{
"bucketName": bucket,
})
return nil
}
rules := make([]oss.LifecycleRule, 0, len(lifecycleRules))
for i, lifecycleRule := range lifecycleRules {
r := lifecycleRule.(map[string]interface{})
rule := oss.LifecycleRule{
Prefix: r["prefix"].(string),
}
// ID
if val, ok := r["id"].(string); ok && val != "" {
rule.ID = val
}
// Enabled
if val, ok := r["enabled"].(bool); ok && val {
rule.Status = string(ExpirationStatusEnabled)
} else {
rule.Status = string(ExpirationStatusDisabled)
}
// Expiration
expiration := d.Get(fmt.Sprintf("lifecycle_rule.%d.expiration", i)).(*schema.Set).List()
if len(expiration) > 0 {
e := expiration[0].(map[string]interface{})
i := oss.LifecycleExpiration{}
valDate, _ := e["date"].(string)
valCreatedBeforeDate, _ := e["created_before_date"].(string)
valDays, _ := e["days"].(int)
if val, ok := e["expired_object_delete_marker"].(bool); ok && val {
if valDays > 0 || valDate != "" || valCreatedBeforeDate != "" {
return WrapError(Error("'date/created_before_date/days' conflicts with 'expired_object_delete_marker'. One and only one of them can be specified in one expiration configuration."))
}
i.ExpiredObjectDeleteMarker = &val
} else {
cnt := 0
if valDate != "" {
i.Date = fmt.Sprintf("%sT00:00:00.000Z", valDate)
cnt++
}
if valCreatedBeforeDate != "" {
i.CreatedBeforeDate = fmt.Sprintf("%sT00:00:00.000Z", valCreatedBeforeDate)
cnt++
}
if valDays > 0 {
i.Days = valDays
cnt++
}
if cnt != 1 {
return WrapError(Error("One and only one of 'date', 'created_before_date' and 'days' can be specified in one expiration configuration."))
}
}
rule.Expiration = &i
}
// Transitions
transitions := d.Get(fmt.Sprintf("lifecycle_rule.%d.transitions", i)).(*schema.Set).List()
if len(transitions) > 0 {
for _, transition := range transitions {
i := oss.LifecycleTransition{}
valCreatedBeforeDate := transition.(map[string]interface{})["created_before_date"].(string)
valDays := transition.(map[string]interface{})["days"].(int)
valStorageClass := transition.(map[string]interface{})["storage_class"].(string)
if (valCreatedBeforeDate != "" && valDays > 0) || (valCreatedBeforeDate == "" && valDays <= 0) || (valStorageClass == "") {
return WrapError(Error("'CreatedBeforeDate' conflicts with 'Days'. One and only one of them can be specified in one transition configuration. 'storage_class' must be set."))
}
if valCreatedBeforeDate != "" {
i.CreatedBeforeDate = fmt.Sprintf("%sT00:00:00.000Z", valCreatedBeforeDate)
}
if valDays > 0 {
i.Days = valDays
}
if valStorageClass != "" {
i.StorageClass = oss.StorageClassType(valStorageClass)
}
rule.Transitions = append(rule.Transitions, i)
}
}
// AbortMultipartUpload
abortMultipartUpload := d.Get(fmt.Sprintf("lifecycle_rule.%d.abort_multipart_upload", i)).(*schema.Set).List()
if len(abortMultipartUpload) > 0 {
e := abortMultipartUpload[0].(map[string]interface{})
i := oss.LifecycleAbortMultipartUpload{}
valCreatedBeforeDate, _ := e["created_before_date"].(string)
valDays, _ := e["days"].(int)
if (valCreatedBeforeDate != "" && valDays > 0) || (valCreatedBeforeDate == "" && valDays <= 0) {
return WrapError(Error("'CreatedBeforeDate' conflicts with 'days'. One and only one of them can be specified in one abort_multipart_upload configuration."))
}
if valCreatedBeforeDate != "" {
i.CreatedBeforeDate = fmt.Sprintf("%sT00:00:00.000Z", valCreatedBeforeDate)
}
if valDays > 0 {
i.Days = valDays
}
rule.AbortMultipartUpload = &i
}
// Noncurrent Version Expiration
noncurrentVersionExpiration := d.Get(fmt.Sprintf("lifecycle_rule.%d.noncurrent_version_expiration", i)).(*schema.Set).List()
if len(noncurrentVersionExpiration) > 0 {
e := noncurrentVersionExpiration[0].(map[string]interface{})
i := oss.LifecycleVersionExpiration{}
valDays, _ := e["days"].(int)
i.NoncurrentDays = valDays
rule.NonVersionExpiration = &i
}
// Noncurrent Version Transitions
noncurrentVersionTransitions := d.Get(fmt.Sprintf("lifecycle_rule.%d.noncurrent_version_transition", i)).(*schema.Set).List()
if len(noncurrentVersionTransitions) > 0 {
for _, transition := range noncurrentVersionTransitions {
i := oss.LifecycleVersionTransition{}
valDays := transition.(map[string]interface{})["days"].(int)
valStorageClass := transition.(map[string]interface{})["storage_class"].(string)
i.NoncurrentDays = valDays
i.StorageClass = oss.StorageClassType(valStorageClass)
rule.NonVersionTransitions = append(rule.NonVersionTransitions, i)
}
}
rules = append(rules, rule)
}
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return nil, ossClient.SetBucketLifecycle(bucket, rules)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "SetBucketLifecycle", AliyunOssGoSdk)
}
addDebug("SetBucketLifecycle", raw, requestInfo, map[string]interface{}{
"bucketName": bucket,
"rules": rules,
})
return nil
}
func resourceAlicloudOssBucketPolicyUpdate(client *connectivity.AliyunClient, d *schema.ResourceData) error {
bucket := d.Id()
policy := d.Get("policy").(string)
var requestInfo *oss.Client
if len(policy) == 0 {
params := map[string]interface{}{}
params["policy"] = nil
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return ossClient.Conn.Do("DELETE", bucket, "", params, nil, nil, 0, nil)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DeletePolicyByConn", AliyunOssGoSdk)
}
addDebug("DeletePolicyByConn", raw, requestInfo, params)
return nil
}
params := map[string]interface{}{}
params["policy"] = nil
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
buffer := new(bytes.Buffer)
buffer.Write([]byte(policy))
return ossClient.Conn.Do("PUT", bucket, "", params, nil, buffer, 0, nil)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "PutPolicyByConn", AliyunOssGoSdk)
}
addDebug("PutPolicyByConn", raw, requestInfo, params)
return nil
}
func resourceAlicloudOssBucketEncryptionUpdate(client *connectivity.AliyunClient, d *schema.ResourceData) error {
encryption_rule := d.Get("server_side_encryption_rule").([]interface{})
var requestInfo *oss.Client
if encryption_rule == nil || len(encryption_rule) == 0 {
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return nil, ossClient.DeleteBucketEncryption(d.Id())
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DeleteBucketEncryption", AliyunOssGoSdk)
}
addDebug("DeleteBucketEncryption", raw, requestInfo, map[string]string{"bucketName": d.Id()})
return nil
}
var sseRule oss.ServerEncryptionRule
c := encryption_rule[0].(map[string]interface{})
if v, ok := c["sse_algorithm"]; ok {
sseRule.SSEDefault.SSEAlgorithm = v.(string)
}
if v, ok := c["kms_master_key_id"]; ok {
sseRule.SSEDefault.KMSMasterKeyID = v.(string)
}
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return nil, ossClient.SetBucketEncryption(d.Id(), sseRule)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "SetBucketEncryption", AliyunOssGoSdk)
}
addDebug("SetBucketEncryption", raw, requestInfo, map[string]interface{}{
"bucketName": d.Id(),
"encryptionRule": sseRule,
})
return nil
}
func resourceAlicloudOssBucketTaggingUpdate(client *connectivity.AliyunClient, d *schema.ResourceData) error {
tagsMap := d.Get("tags").(map[string]interface{})
var requestInfo *oss.Client
if tagsMap == nil || len(tagsMap) == 0 {
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return nil, ossClient.DeleteBucketTagging(d.Id())
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DeleteBucketTagging", AliyunOssGoSdk)
}
addDebug("DeleteBucketTagging", raw, requestInfo, map[string]string{"bucketName": d.Id()})
return nil
}
// Put tagging
var bTagging oss.Tagging
for k, v := range tagsMap {
bTagging.Tags = append(bTagging.Tags, oss.Tag{
Key: k,
Value: v.(string),
})
}
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return nil, ossClient.SetBucketTagging(d.Id(), bTagging)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "SetBucketTagging", AliyunOssGoSdk)
}
addDebug("SetBucketTagging", raw, requestInfo, map[string]interface{}{
"bucketName": d.Id(),
"tagging": bTagging,
})
return nil
}
func resourceAlicloudOssBucketVersioningUpdate(client *connectivity.AliyunClient, d *schema.ResourceData) error {
versioning := d.Get("versioning").([]interface{})
if len(versioning) == 1 {
var status string
c := versioning[0].(map[string]interface{})
if v, ok := c["status"]; ok {
status = v.(string)
}
versioningCfg := oss.VersioningConfig{}
versioningCfg.Status = status
var requestInfo *oss.Client
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return nil, ossClient.SetBucketVersioning(d.Id(), versioningCfg)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "SetBucketVersioning", AliyunOssGoSdk)
}
addDebug("SetBucketVersioning", raw, requestInfo, map[string]interface{}{
"bucketName": d.Id(),
"versioningConfig": versioningCfg,
})
}
return nil
}
func resourceAlicloudOssBucketTransferAccUpdate(client *connectivity.AliyunClient, d *schema.ResourceData) error {
acc := d.Get("transfer_acceleration").([]interface{})
if len(acc) == 1 {
var requestInfo *oss.Client
var aacCfg oss.TransferAccConfiguration
c := acc[0].(map[string]interface{})
if v, ok := c["enabled"]; ok {
aacCfg.Enabled = v.(bool)
}
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return nil, ossClient.SetBucketTransferAcc(d.Id(), aacCfg)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "SetBucketTransferAcc", AliyunOssGoSdk)
}
addDebug("SetBucketTransferAcc", raw, requestInfo, map[string]interface{}{
"bucketName": d.Id(),
"TransferAccConfiguration": aacCfg,
})
}
return nil
}
func resourceAlicloudOssBucketDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ossService := OssService{client}
var requestInfo *oss.Client
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return ossClient.IsBucketExist(d.Id())
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "IsBucketExist", AliyunOssGoSdk)
}
addDebug("IsBucketExist", raw, requestInfo, map[string]string{"bucketName": d.Id()})
exist, _ := raw.(bool)
if !exist {
return nil
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
return nil, ossClient.DeleteBucket(d.Id())
})
if err != nil {
if IsExpectedErrors(err, []string{"BucketNotEmpty"}) {
if d.Get("force_destroy").(bool) {
raw, er := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
bucket, _ := ossClient.Bucket(d.Get("bucket").(string))
lor, err := bucket.ListObjectVersions()
if err != nil {
return nil, WrapErrorf(err, DefaultErrorMsg, d.Id(), "ListObjectVersions", AliyunOssGoSdk)
}
addDebug("ListObjectVersions", lor, requestInfo)
objectsToDelete := make([]oss.DeleteObject, 0)
for _, object := range lor.ObjectDeleteMarkers {
objectsToDelete = append(objectsToDelete, oss.DeleteObject{
Key: object.Key,
VersionId: object.VersionId,
})
}
for _, object := range lor.ObjectVersions {
objectsToDelete = append(objectsToDelete, oss.DeleteObject{
Key: object.Key,
VersionId: object.VersionId,
})
}
return bucket.DeleteObjectVersions(objectsToDelete)
})
if er != nil {
return resource.NonRetryableError(er)
}
addDebug("DeleteObjectVersions", raw, requestInfo, map[string]string{"bucketName": d.Id()})
return resource.RetryableError(err)
}
}
return resource.NonRetryableError(err)
}
addDebug("DeleteBucket", raw, requestInfo, map[string]string{"bucketName": d.Id()})
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DeleteBucket", AliyunOssGoSdk)
}
return WrapError(ossService.WaitForOssBucket(d.Id(), Deleted, DefaultTimeoutMedium))
}
func expirationHash(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
if v, ok := m["date"]; ok {
buf.WriteString(fmt.Sprintf("%s-", v.(string)))
}
if v, ok := m["created_before_date"]; ok {
buf.WriteString(fmt.Sprintf("%s-", v.(string)))
}
if v, ok := m["days"]; ok {
buf.WriteString(fmt.Sprintf("%d-", v.(int)))
}
if v, ok := m["expired_object_delete_marker"]; ok {
buf.WriteString(fmt.Sprintf("%v-", v.(bool)))
}
return hashcode.String(buf.String())
}
func transitionsHash(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
if v, ok := m["created_before_date"]; ok {
buf.WriteString(fmt.Sprintf("%s-", v.(string)))
}
if v, ok := m["storage_class"]; ok {
buf.WriteString(fmt.Sprintf("%s-", v.(string)))
}
if v, ok := m["days"]; ok {
buf.WriteString(fmt.Sprintf("%d-", v.(int)))
}
return hashcode.String(buf.String())
}
func abortMultipartUploadHash(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
if v, ok := m["created_before_date"]; ok {
buf.WriteString(fmt.Sprintf("%s-", v.(string)))
}
if v, ok := m["days"]; ok {
buf.WriteString(fmt.Sprintf("%d-", v.(int)))
}
return hashcode.String(buf.String())
}
package alicloud
import (
"bytes"
"fmt"
"io"
"log"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/mitchellh/go-homedir"
)
func resourceAlicloudOssBucketObject() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudOssBucketObjectPut,
Read: resourceAlicloudOssBucketObjectRead,
Update: resourceAlicloudOssBucketObjectPut,
Delete: resourceAlicloudOssBucketObjectDelete,
Schema: map[string]*schema.Schema{
"bucket": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"key": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"source": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"content"},
},
"content": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"source"},
},
"acl": {
Type: schema.TypeString,
Default: oss.ACLPrivate,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"private", "public-read", "public-read-write"}, false),
},
"content_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"content_length": {
Type: schema.TypeString,
Computed: true,
},
"cache_control": {
Type: schema.TypeString,
Optional: true,
},
"content_disposition": {
Type: schema.TypeString,
Optional: true,
},
"content_encoding": {
Type: schema.TypeString,
Optional: true,
},
"content_md5": {
Type: schema.TypeString,
Optional: true,
},
"expires": {
Type: schema.TypeString,
Optional: true,
},
"server_side_encryption": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{
string(ServerSideEncryptionKMS), string(ServerSideEncryptionAes256),
}, false),
Default: ServerSideEncryptionAes256,
},
"kms_key_id": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return ServerSideEncryptionKMS != d.Get("server_side_encryption").(string)
},
},
"etag": {
Type: schema.TypeString,
Computed: true,
},
"version_id": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudOssBucketObjectPut(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var requestInfo *oss.Client
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return ossClient.Bucket(d.Get("bucket").(string))
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_oss_bucket_object", "Bucket", AliyunOssGoSdk)
}
addDebug("Bucket", raw, requestInfo, map[string]string{"bucketName": d.Get("bucket").(string)})
bucket, _ := raw.(*oss.Bucket)
var filePath string
var body io.Reader
if v, ok := d.GetOk("source"); ok {
source := v.(string)
path, err := homedir.Expand(source)
if err != nil {
return WrapError(err)
}
filePath = path
} else if v, ok := d.GetOk("content"); ok {
content := v.(string)
body = bytes.NewReader([]byte(content))
} else {
return WrapError(Error("[ERROR] Must specify \"source\" or \"content\" field"))
}
key := d.Get("key").(string)
options, err := buildObjectHeaderOptions(d)
if v, ok := d.GetOk("server_side_encryption"); ok {
options = append(options, oss.ServerSideEncryption(v.(string)))
}
if v, ok := d.GetOk("kms_key_id"); ok {
options = append(options, oss.ServerSideEncryptionKeyID(v.(string)))
}
if err != nil {
return WrapError(err)
}
if filePath != "" {
err = bucket.PutObjectFromFile(key, filePath, options...)
}
if body != nil {
err = bucket.PutObject(key, body, options...)
}
if err != nil {
return WrapError(Error("Error putting object in Oss bucket (%#v): %s", bucket, err))
}
d.SetId(key)
return resourceAlicloudOssBucketObjectRead(d, meta)
}
func resourceAlicloudOssBucketObjectRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var requestInfo *oss.Client
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return ossClient.Bucket(d.Get("bucket").(string))
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "Bucket", AliyunOssGoSdk)
}
addDebug("Bucket", raw, requestInfo, map[string]string{"bucketName": d.Get("bucket").(string)})
bucket, _ := raw.(*oss.Bucket)
options, err := buildObjectHeaderOptions(d)
if err != nil {
return WrapError(err)
}
object, err := bucket.GetObjectDetailedMeta(d.Get("key").(string), options...)
if err != nil {
if IsExpectedErrors(err, []string{"404 Not Found"}) {
d.SetId("")
return WrapError(Error("To get the Object: %#v but it is not exist in the specified bucket %s.", d.Get("key").(string), d.Get("bucket").(string)))
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "GetObjectDetailedMeta", AliyunOssGoSdk)
}
addDebug("GetObjectDetailedMeta", object, requestInfo, map[string]interface{}{
"objectKey": d.Get("key").(string),
"options": options,
})
d.Set("content_type", object.Get("Content-Type"))
d.Set("content_length", object.Get("Content-Length"))
d.Set("cache_control", object.Get("Cache-Control"))
d.Set("content_disposition", object.Get("Content-Disposition"))
d.Set("content_encoding", object.Get("Content-Encoding"))
d.Set("expires", object.Get("Expires"))
d.Set("etag", strings.Trim(object.Get("ETag"), `"`))
d.Set("version_id", object.Get("x-oss-version-id"))
return nil
}
func resourceAlicloudOssBucketObjectDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ossService := OssService{client}
var requestInfo *oss.Client
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return ossClient.Bucket(d.Get("bucket").(string))
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "Bucket", AliyunOssGoSdk)
}
addDebug("Bucket", raw, requestInfo, map[string]string{"bucketName": d.Get("bucket").(string)})
bucket, _ := raw.(*oss.Bucket)
err = bucket.DeleteObject(d.Id())
if err != nil {
if IsExpectedErrors(err, []string{"No Content", "Not Found"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DeleteObject", AliyunOssGoSdk)
}
return WrapError(ossService.WaitForOssBucketObject(bucket, d.Id(), Deleted, DefaultTimeoutMedium))
}
func buildObjectHeaderOptions(d *schema.ResourceData) (options []oss.Option, err error) {
if v, ok := d.GetOk("acl"); ok {
options = append(options, oss.ObjectACL(oss.ACLType(v.(string))))
}
if v, ok := d.GetOk("content_type"); ok {
options = append(options, oss.ContentType(v.(string)))
}
if v, ok := d.GetOk("cache_control"); ok {
options = append(options, oss.CacheControl(v.(string)))
}
if v, ok := d.GetOk("content_disposition"); ok {
options = append(options, oss.ContentDisposition(v.(string)))
}
if v, ok := d.GetOk("content_encoding"); ok {
options = append(options, oss.ContentEncoding(v.(string)))
}
if v, ok := d.GetOk("content_md5"); ok {
options = append(options, oss.ContentMD5(v.(string)))
}
if v, ok := d.GetOk("expires"); ok {
expires := v.(string)
expiresTime, err := time.Parse(time.RFC1123, expires)
if err != nil {
return nil, fmt.Errorf("expires format must respect the RFC1123 standard (current value: %s)", expires)
}
options = append(options, oss.Expires(expiresTime))
}
if options == nil || len(options) == 0 {
log.Printf("[WARN] Object header options is nil.")
}
return options, nil
}
package alicloud
import (
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ots"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudOtsInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunOtsInstanceCreate,
Read: resourceAliyunOtsInstanceRead,
Update: resourceAliyunOtsInstanceUpdate,
Delete: resourceAliyunOtsInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(3, 16),
},
"accessed_by": {
Type: schema.TypeString,
Optional: true,
Default: AnyNetwork,
ValidateFunc: validation.StringInSlice([]string{
string(AnyNetwork), string(VpcOnly), string(VpcOrConsole),
}, false),
},
"instance_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: OtsHighPerformance,
ValidateFunc: validation.StringInSlice([]string{
string(OtsCapacity), string(OtsHighPerformance),
}, false),
},
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Id() != ""
},
},
"tags": tagsSchema(),
},
}
}
func resourceAliyunOtsInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
otsService := OtsService{client}
instanceType := d.Get("instance_type").(string)
request := ots.CreateInsertInstanceRequest()
request.RegionId = client.RegionId
request.ClusterType = convertInstanceType(OtsInstanceType(instanceType))
types, err := otsService.DescribeOtsInstanceTypes()
if err != nil {
return WrapError(err)
}
valid := false
for _, t := range types {
if request.ClusterType == t {
valid = true
break
}
}
if !valid {
return WrapError(Error("The instance type %s is not available in the region %s.", instanceType, client.RegionId))
}
request.InstanceName = d.Get("name").(string)
request.Description = d.Get("description").(string)
request.Network = convertInstanceAccessedBy(InstanceAccessedByType(d.Get("accessed_by").(string)))
raw, err := client.WithOtsClient(func(otsClient *ots.Client) (interface{}, error) {
return otsClient.InsertInstance(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetId(request.InstanceName)
if err := otsService.WaitForOtsInstance(request.InstanceName, Running, DefaultTimeout); err != nil {
return WrapError(err)
}
return resourceAliyunOtsInstanceUpdate(d, meta)
}
func resourceAliyunOtsInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
otsService := OtsService{client}
object, err := otsService.DescribeOtsInstance(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", object.InstanceName)
d.Set("accessed_by", convertInstanceAccessedByRevert(object.Network))
d.Set("instance_type", convertInstanceTypeRevert(object.ClusterType))
d.Set("description", object.Description)
d.Set("tags", otsTagsToMap(object.TagInfos.TagInfo))
return nil
}
func resourceAliyunOtsInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
otsService := OtsService{client}
d.Partial(true)
if !d.IsNewResource() && d.HasChange("accessed_by") {
request := ots.CreateUpdateInstanceRequest()
request.RegionId = client.RegionId
request.InstanceName = d.Id()
request.Network = convertInstanceAccessedBy(InstanceAccessedByType(d.Get("accessed_by").(string)))
raw, err := client.WithOtsClient(func(otsClient *ots.Client) (interface{}, error) {
return otsClient.UpdateInstance(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("accessed_by")
}
if d.HasChange("tags") {
oraw, nraw := d.GetChange("tags")
o := oraw.(map[string]interface{})
n := nraw.(map[string]interface{})
create, remove := diffTags(tagsFromMap(o), tagsFromMap(n))
if len(remove) > 0 {
request := ots.CreateDeleteTagsRequest()
request.RegionId = client.RegionId
request.InstanceName = d.Id()
var tags []ots.DeleteTagsTagInfo
for _, t := range remove {
tags = append(tags, ots.DeleteTagsTagInfo{
TagKey: t.Key,
TagValue: t.Value,
})
}
request.TagInfo = &tags
raw, err := client.WithOtsClient(func(otsClient *ots.Client) (interface{}, error) {
return otsClient.DeleteTags(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
if len(create) > 0 {
request := ots.CreateInsertTagsRequest()
request.RegionId = client.RegionId
request.InstanceName = d.Id()
var tags []ots.InsertTagsTagInfo
for _, t := range create {
tags = append(tags, ots.InsertTagsTagInfo{
TagKey: t.Key,
TagValue: t.Value,
})
}
request.TagInfo = &tags
raw, err := client.WithOtsClient(func(otsClient *ots.Client) (interface{}, error) {
return otsClient.InsertTags(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
d.SetPartial("tags")
}
if err := otsService.WaitForOtsInstance(d.Id(), Running, DefaultTimeout); err != nil {
return WrapError(err)
}
d.Partial(false)
return resourceAliyunOtsInstanceRead(d, meta)
}
func resourceAliyunOtsInstanceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
otsService := OtsService{client}
request := ots.CreateDeleteInstanceRequest()
request.RegionId = client.RegionId
request.InstanceName = d.Id()
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
raw, err := client.WithOtsClient(func(otsClient *ots.Client) (interface{}, error) {
return otsClient.DeleteInstance(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"AuthFailed", "InvalidStatus", "ValidationFailed"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(otsService.WaitForOtsInstance(d.Id(), Deleted, DefaultLongTimeout))
}
package alicloud
import (
"github.com/aliyun/alibaba-cloud-sdk-go/services/ots"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudOtsInstanceAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunOtsInstanceAttachmentCreate,
Read: resourceAliyunOtsInstanceAttachmentRead,
Delete: resourceAliyunOtsInstanceAttachmentDelete,
Schema: map[string]*schema.Schema{
"instance_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"vpc_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"vswitch_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"vpc_id": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAliyunOtsInstanceAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
request := ots.CreateBindInstance2VpcRequest()
request.RegionId = client.RegionId
request.InstanceName = d.Get("instance_name").(string)
request.InstanceVpcName = d.Get("vpc_name").(string)
request.VirtualSwitchId = d.Get("vswitch_id").(string)
if vsw, err := vpcService.DescribeVSwitch(d.Get("vswitch_id").(string)); err != nil {
return WrapError(err)
} else {
request.VpcId = vsw.VpcId
}
raw, err := client.WithOtsClient(func(otsClient *ots.Client) (interface{}, error) {
return otsClient.BindInstance2Vpc(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ots_instance_attachment", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetId(request.InstanceName)
return resourceAliyunOtsInstanceAttachmentRead(d, meta)
}
func resourceAliyunOtsInstanceAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
otsService := OtsService{client}
object, err := otsService.DescribeOtsInstanceAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
// There is a bug that inst does not contain instance name and vswitch ID, so this resource does not support import function.
//d.Set("instance_name", inst.InstanceName)
d.Set("vpc_name", object.InstanceVpcName)
d.Set("vpc_id", object.VpcId)
return nil
}
func resourceAliyunOtsInstanceAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
otsService := OtsService{client}
object, err := otsService.DescribeOtsInstanceAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
request := ots.CreateUnbindInstance2VpcRequest()
request.RegionId = client.RegionId
request.InstanceName = d.Id()
request.InstanceVpcName = object.InstanceVpcName
raw, err := client.WithOtsClient(func(otsClient *ots.Client) (interface{}, error) {
return otsClient.UnbindInstance2Vpc(request)
})
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(otsService.WaitForOtsInstanceVpc(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"fmt"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"strconv"
"github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudOtsTable() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunOtsTableCreate,
Read: resourceAliyunOtsTableRead,
Update: resourceAliyunOtsTableUpdate,
Delete: resourceAliyunOtsTableDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"instance_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"table_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"primary_key": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
string(IntegerType), string(BinaryType), string(StringType)}, false),
},
},
},
MaxItems: 4,
ForceNew: true,
},
"time_to_live": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(-1, INT_MAX),
},
"max_version": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(1, INT_MAX),
},
"deviation_cell_version_in_sec": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateStringConvertInt64(),
Default: "86400",
},
},
}
}
func resourceAliyunOtsTableCreate(d *schema.ResourceData, meta interface{}) error {
tableMeta := new(tablestore.TableMeta)
instanceName := d.Get("instance_name").(string)
tableName := d.Get("table_name").(string)
tableMeta.TableName = tableName
client := meta.(*connectivity.AliyunClient)
otsService := OtsService{client}
if err := resource.Retry(1*time.Minute, func() *resource.RetryError {
_, e := otsService.DescribeOtsInstance(instanceName)
if e != nil {
if NotFoundError(e) {
return resource.RetryableError(e)
}
return resource.NonRetryableError(e)
}
return nil
}); err != nil {
return WrapError(err)
}
for _, primaryKey := range d.Get("primary_key").([]interface{}) {
pk := primaryKey.(map[string]interface{})
pkValue := otsService.getPrimaryKeyType(pk["type"].(string))
tableMeta.AddPrimaryKeyColumn(pk["name"].(string), pkValue)
}
tableOption := new(tablestore.TableOption)
tableOption.TimeToAlive = d.Get("time_to_live").(int)
tableOption.MaxVersion = d.Get("max_version").(int)
if deviation, ok := d.GetOk("deviation_cell_version_in_sec"); ok {
tableOption.DeviationCellVersionInSec, _ = strconv.ParseInt(deviation.(string), 10, 64)
}
reservedThroughput := new(tablestore.ReservedThroughput)
request := new(tablestore.CreateTableRequest)
request.TableMeta = tableMeta
request.TableOption = tableOption
request.ReservedThroughput = reservedThroughput
var requestinfo *tablestore.TableStoreClient
if err := resource.Retry(6*time.Minute, func() *resource.RetryError {
raw, err := client.WithTableStoreClient(instanceName, func(tableStoreClient *tablestore.TableStoreClient) (interface{}, error) {
requestinfo = tableStoreClient
return tableStoreClient.CreateTable(request)
})
if err != nil {
if IsExpectedErrors(err, OtsTableIsTemporarilyUnavailable) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug("CreateTable", raw, requestinfo, request)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ots_table", "CreateTable", AliyunTablestoreGoSdk)
}
d.SetId(fmt.Sprintf("%s%s%s", instanceName, COLON_SEPARATED, tableName))
return resourceAliyunOtsTableRead(d, meta)
}
func resourceAliyunOtsTableRead(d *schema.ResourceData, meta interface{}) error {
instanceName, _, err := parseId(d, meta)
if err != nil {
return WrapError(err)
}
client := meta.(*connectivity.AliyunClient)
otsService := OtsService{client}
object, err := otsService.DescribeOtsTable(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("instance_name", instanceName)
d.Set("table_name", object.TableMeta.TableName)
var pks []map[string]interface{}
keys := object.TableMeta.SchemaEntry
for _, v := range keys {
item := make(map[string]interface{})
item["name"] = *v.Name
item["type"] = otsService.convertPrimaryKeyType(*v.Type)
pks = append(pks, item)
}
d.Set("primary_key", pks)
d.Set("time_to_live", object.TableOption.TimeToAlive)
d.Set("max_version", object.TableOption.MaxVersion)
d.Set("deviation_cell_version_in_sec", strconv.FormatInt(object.TableOption.DeviationCellVersionInSec, 10))
return nil
}
func resourceAliyunOtsTableUpdate(d *schema.ResourceData, meta interface{}) error {
// As the issue of ots sdk, time_to_live and max_version need to be updated together at present.
// For the issue, please refer to https://github.com/aliyun/aliyun-tablestore-go-sdk/issues/18
if d.HasChange("time_to_live") || d.HasChange("max_version") || d.HasChange("deviation_cell_version_in_sec") {
instanceName, tableName, err := parseId(d, meta)
if err != nil {
return err
}
client := meta.(*connectivity.AliyunClient)
request := new(tablestore.UpdateTableRequest)
request.TableName = tableName
tableOption := new(tablestore.TableOption)
tableOption.TimeToAlive = d.Get("time_to_live").(int)
tableOption.MaxVersion = d.Get("max_version").(int)
if deviation, ok := d.GetOk("deviation_cell_version_in_sec"); ok {
tableOption.DeviationCellVersionInSec, _ = strconv.ParseInt(deviation.(string), 10, 64)
}
request.TableOption = tableOption
var requestinfo *tablestore.TableStoreClient
if err := resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := client.WithTableStoreClient(instanceName, func(tableStoreClient *tablestore.TableStoreClient) (interface{}, error) {
requestinfo = tableStoreClient
return tableStoreClient.UpdateTable(request)
})
if err != nil {
if IsExpectedErrors(err, OtsTableIsTemporarilyUnavailable) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug("UpdateTable", raw, requestinfo, request)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "UpdateTable", AliyunTablestoreGoSdk)
}
}
return resourceAliyunOtsTableRead(d, meta)
}
func resourceAliyunOtsTableDelete(d *schema.ResourceData, meta interface{}) error {
instanceName, tableName, err := parseId(d, meta)
if err != nil {
return WrapError(err)
}
client := meta.(*connectivity.AliyunClient)
otsService := OtsService{client}
req := new(tablestore.DeleteTableRequest)
req.TableName = tableName
var requestinfo *tablestore.TableStoreClient
err = resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := client.WithTableStoreClient(instanceName, func(tableStoreClient *tablestore.TableStoreClient) (interface{}, error) {
requestinfo = tableStoreClient
return tableStoreClient.DeleteTable(req)
})
if err != nil {
if IsExpectedErrors(err, OtsTableIsTemporarilyUnavailable) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug("DeleteTable", raw, requestinfo, req)
return nil
})
if err != nil {
if strings.HasPrefix(err.Error(), "OTSObjectNotExist") {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DeleteTable", AliyunTablestoreGoSdk)
}
return WrapError(otsService.WaitForOtsTable(instanceName, tableName, Deleted, DefaultTimeout))
}
func parseId(d *schema.ResourceData, meta interface{}) (instanceName, tableName string, err error) {
split := strings.Split(d.Id(), COLON_SEPARATED)
if len(split) == 1 {
// For compatibility
if meta.(*connectivity.AliyunClient).OtsInstanceName != "" {
tableName = split[0]
instanceName = meta.(*connectivity.AliyunClient).OtsInstanceName
d.SetId(fmt.Sprintf("%s%s%s", instanceName, COLON_SEPARATED, tableName))
} else {
err = WrapError(Error("From Provider version 1.10.0, the provider field 'ots_instance_name' has been deprecated and " +
"you should use resource alicloud_ots_table's new field 'instance_name' and 'table_name' to re-import this resource."))
return
}
} else {
instanceName = split[0]
tableName = split[1]
}
return
}
package alicloud
import (
"fmt"
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/polardb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudPolarDBAccount() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudPolarDBAccountCreate,
Read: resourceAlicloudPolarDBAccountRead,
Update: resourceAlicloudPolarDBAccountUpdate,
Delete: resourceAlicloudPolarDBAccountDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"db_cluster_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"account_name": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"account_password": {
Type: schema.TypeString,
Required: true,
Sensitive: true,
},
"kms_encrypted_password": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: kmsDiffSuppressFunc,
},
"kms_encryption_context": {
Type: schema.TypeMap,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("kms_encrypted_password").(string) == ""
},
Elem: schema.TypeString,
},
"account_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{string("Normal"), string("Super")}, false),
Default: "Normal",
ForceNew: true,
},
"account_description": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudPolarDBAccountCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
polarDBService := PolarDBService{client}
request := polardb.CreateCreateAccountRequest()
request.RegionId = client.RegionId
request.DBClusterId = d.Get("db_cluster_id").(string)
request.AccountName = d.Get("account_name").(string)
password := d.Get("account_password").(string)
kmsPassword := d.Get("kms_encrypted_password").(string)
if password == "" && kmsPassword == "" {
return WrapError(Error("One of the 'password' and 'kms_encrypted_password' should be set."))
}
if password != "" {
request.AccountPassword = password
} else {
kmsService := KmsService{client}
decryptResp, err := kmsService.Decrypt(kmsPassword, d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request.AccountPassword = decryptResp
}
request.AccountType = d.Get("account_type").(string)
// Description will not be set when account type is normal and it is a API bug
if v, ok := d.GetOk("account_description"); ok && v.(string) != "" {
request.AccountDescription = v.(string)
}
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.CreateAccount(request)
})
if err != nil {
if IsExpectedErrors(err, OperationDeniedDBStatus) {
time.Sleep(5 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_polardb_account", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprintf("%s%s%s", request.DBClusterId, COLON_SEPARATED, request.AccountName))
if err := polarDBService.WaitForPolarDBAccount(d.Id(), Available, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
return resourceAlicloudPolarDBAccountRead(d, meta)
}
func resourceAlicloudPolarDBAccountRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
polarDBService := PolarDBService{client}
object, err := polarDBService.DescribePolarDBAccount(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("db_cluster_id", parts[0])
d.Set("account_name", object.AccountName)
d.Set("account_type", object.AccountType)
d.Set("account_description", object.AccountDescription)
return nil
}
func resourceAlicloudPolarDBAccountUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
polarDBService := PolarDBService{client}
d.Partial(true)
parts := strings.Split(d.Id(), COLON_SEPARATED)
instanceId := parts[0]
accountName := parts[1]
if d.HasChange("account_description") {
if err := polarDBService.WaitForPolarDBAccount(d.Id(), Available, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
request := polardb.CreateModifyAccountDescriptionRequest()
request.RegionId = client.RegionId
request.DBClusterId = instanceId
request.AccountName = accountName
request.AccountDescription = d.Get("account_description").(string)
if err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.ModifyAccountDescription(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ConcurrentTaskExceeded"}) {
time.Sleep(DefaultIntervalShort * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("account_description")
}
if d.HasChange("account_password") || d.HasChange("kms_encrypted_password") {
if err := polarDBService.WaitForPolarDBAccount(d.Id(), Available, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
request := polardb.CreateModifyAccountPasswordRequest()
request.RegionId = client.RegionId
request.DBClusterId = instanceId
request.AccountName = accountName
password := d.Get("account_password").(string)
kmsPassword := d.Get("kms_encrypted_password").(string)
if password == "" && kmsPassword == "" {
return WrapError(Error("One of the 'password' and 'kms_encrypted_password' should be set."))
}
if password != "" {
d.SetPartial("account_password")
request.NewAccountPassword = password
} else {
kmsService := KmsService{meta.(*connectivity.AliyunClient)}
decryptResp, err := kmsService.Decrypt(kmsPassword, d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request.NewAccountPassword = decryptResp
d.SetPartial("kms_encrypted_password")
d.SetPartial("kms_encryption_context")
}
if err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.ModifyAccountPassword(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ConcurrentTaskExceeded"}) {
time.Sleep(DefaultIntervalShort * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("account_password")
}
d.Partial(false)
return resourceAlicloudPolarDBAccountRead(d, meta)
}
func resourceAlicloudPolarDBAccountDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
polarDBService := PolarDBService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request := polardb.CreateDeleteAccountRequest()
request.RegionId = client.RegionId
request.DBClusterId = parts[0]
request.AccountName = parts[1]
if err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.DeleteAccount(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ConcurrentTaskExceeded"}) {
time.Sleep(DefaultIntervalShort * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}); err != nil {
if IsExpectedErrors(err, []string{"InvalidAccountName.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return polarDBService.WaitForPolarDBAccount(d.Id(), Deleted, DefaultTimeoutMedium)
}
package alicloud
import (
"fmt"
"strings"
"time"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudPolarDBAccountPrivilege() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudPolarDBAccountPrivilegeCreate,
Read: resourceAlicloudPolarDBAccountPrivilegeRead,
Update: resourceAlicloudPolarDBAccountPrivilegeUpdate,
Delete: resourceAlicloudPolarDBAccountPrivilegeDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"db_cluster_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"account_name": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"account_privilege": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"ReadOnly", "ReadWrite", "DMLOnly", "DDLOnly"}, false),
Default: "ReadOnly",
ForceNew: true,
},
"db_names": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
MinItems: 1,
},
},
}
}
func resourceAlicloudPolarDBAccountPrivilegeCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
polarDBService := PolarDBService{client}
clusterId := d.Get("db_cluster_id").(string)
account := d.Get("account_name").(string)
privilege := d.Get("account_privilege").(string)
dbList := d.Get("db_names").(*schema.Set).List()
// wait instance running before granting
if err := polarDBService.WaitForPolarDBInstance(clusterId, Running, DefaultLongTimeout); err != nil {
return WrapError(err)
}
d.SetId(fmt.Sprintf("%s%s%s%s%s", clusterId, COLON_SEPARATED, account, COLON_SEPARATED, privilege))
if len(dbList) > 0 {
for _, db := range dbList {
if err := resource.Retry(10*time.Minute, func() *resource.RetryError {
if err := polarDBService.GrantPolarDBAccountPrivilege(d.Id(), db.(string)); err != nil {
if IsExpectedErrors(err, OperationDeniedDBStatus) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
}); err != nil {
return WrapError(err)
}
}
}
return resourceAlicloudPolarDBAccountPrivilegeRead(d, meta)
}
func resourceAlicloudPolarDBAccountPrivilegeRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
polarDBService := PolarDBService{client}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
object, err := polarDBService.DescribePolarDBAccountPrivilege(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("db_cluster_id", parts[0])
d.Set("account_name", object.AccountName)
d.Set("account_privilege", parts[2])
var names []string
for _, pri := range object.DatabasePrivileges {
if pri.AccountPrivilege == parts[2] {
names = append(names, pri.DBName)
}
}
d.Set("db_names", names)
return nil
}
func resourceAlicloudPolarDBAccountPrivilegeUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
PolarDBService := PolarDBService{client}
d.Partial(true)
if d.HasChange("db_names") {
parts := strings.Split(d.Id(), COLON_SEPARATED)
o, n := d.GetChange("db_names")
os := o.(*schema.Set)
ns := n.(*schema.Set)
remove := os.Difference(ns).List()
add := ns.Difference(os).List()
if len(remove) > 0 {
// wait instance running before revoking
if err := PolarDBService.WaitForPolarDBInstance(parts[0], Running, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
for _, db := range remove {
if err := PolarDBService.RevokePolarDBAccountPrivilege(d.Id(), db.(string)); err != nil {
return WrapError(err)
}
}
}
if len(add) > 0 {
// wait instance running before granting
if err := PolarDBService.WaitForPolarDBInstance(parts[0], Running, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
for _, db := range add {
if err := PolarDBService.GrantPolarDBAccountPrivilege(d.Id(), db.(string)); err != nil {
return WrapError(err)
}
}
}
d.SetPartial("db_names")
}
d.Partial(false)
return resourceAlicloudPolarDBAccountPrivilegeRead(d, meta)
}
func resourceAlicloudPolarDBAccountPrivilegeDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
PolarDBService := PolarDBService{client}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
object, err := PolarDBService.DescribePolarDBAccountPrivilege(d.Id())
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
var dbName string
if len(object.DatabasePrivileges) > 0 {
for _, pri := range object.DatabasePrivileges {
if pri.AccountPrivilege == parts[2] {
dbName = pri.DBName
if err := PolarDBService.RevokePolarDBAccountPrivilege(d.Id(), pri.DBName); err != nil {
return WrapError(err)
}
}
}
}
return PolarDBService.WaitForPolarDBAccountPrivilege(d.Id(), dbName, Deleted, DefaultTimeoutMedium)
}
package alicloud
import (
"fmt"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudPolarDBBackupPolicy() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudPolarDBBackupPolicyCreate,
Read: resourceAlicloudPolarDBBackupPolicyRead,
Update: resourceAlicloudPolarDBBackupPolicyUpdate,
Delete: resourceAlicloudPolarDBBackupPolicyDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"db_cluster_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"preferred_backup_period": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
// terraform does not support ValidateFunc of TypeList attr
// ValidateFunc: validateAllowedStringValue([]string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}),
Optional: true,
Computed: true,
},
"preferred_backup_time": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice(BACKUP_TIME, false),
Optional: true,
Default: "02:00Z-03:00Z",
},
"backup_retention_period": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudPolarDBBackupPolicyCreate(d *schema.ResourceData, meta interface{}) error {
d.SetId(d.Get("db_cluster_id").(string))
return resourceAlicloudPolarDBBackupPolicyUpdate(d, meta)
}
func resourceAlicloudPolarDBBackupPolicyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
polardbService := PolarDBService{client}
object, err := polardbService.DescribeBackupPolicy(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("db_cluster_id", d.Id())
d.Set("backup_retention_period", object.BackupRetentionPeriod)
d.Set("preferred_backup_period", strings.Split(object.PreferredBackupPeriod, ","))
d.Set("preferred_backup_time", object.PreferredBackupTime)
return nil
}
func resourceAlicloudPolarDBBackupPolicyUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
polardbService := PolarDBService{client}
if d.HasChange("preferred_backup_period") || d.HasChange("preferred_backup_time") {
periodList := expandStringList(d.Get("preferred_backup_period").(*schema.Set).List())
preferredBackupPeriod := fmt.Sprintf("%s", strings.Join(periodList[:], COMMA_SEPARATED))
preferredBackupTime := d.Get("preferred_backup_time").(string)
// wait instance running before modifying
if err := polardbService.WaitForCluster(d.Id(), Running, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
if err := resource.Retry(5*time.Minute, func() *resource.RetryError {
if err := polardbService.ModifyDBBackupPolicy(d.Id(), preferredBackupTime, preferredBackupPeriod); err != nil {
if IsExpectedErrors(err, OperationDeniedDBStatus) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
}); err != nil {
return WrapError(err)
}
}
return resourceAlicloudPolarDBBackupPolicyRead(d, meta)
}
func resourceAlicloudPolarDBBackupPolicyDelete(d *schema.ResourceData, meta interface{}) error {
// Terraform can not destroy it..
return nil
}
package alicloud
import (
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"strconv"
"github.com/aliyun/alibaba-cloud-sdk-go/services/polardb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudPolarDBCluster() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudPolarDBClusterCreate,
Read: resourceAlicloudPolarDBClusterRead,
Update: resourceAlicloudPolarDBClusterUpdate,
Delete: resourceAlicloudPolarDBClusterDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(50 * time.Minute),
Update: schema.DefaultTimeout(50 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"db_type": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"db_version": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"db_node_class": {
Type: schema.TypeString,
Required: true,
},
"modify_type": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"Upgrade", "Downgrade"}, false),
Optional: true,
Default: "Upgrade",
},
"db_node_count": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(2, 16),
Default: 2,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"pay_type": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{string(PostPaid), string(PrePaid)}, false),
Optional: true,
Default: PostPaid,
},
"renewal_status": {
Type: schema.TypeString,
Optional: true,
Default: RenewNotRenewal,
ValidateFunc: validation.StringInSlice([]string{
string(RenewAutoRenewal),
string(RenewNormal),
string(RenewNotRenewal)}, false),
DiffSuppressFunc: polardbPostPaidDiffSuppressFunc,
},
"auto_renew_period": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 6, 12, 24, 36}),
DiffSuppressFunc: polardbPostPaidAndRenewDiffSuppressFunc,
},
"period": {
Type: schema.TypeInt,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 24, 36}),
Optional: true,
DiffSuppressFunc: polardbPostPaidDiffSuppressFunc,
},
"db_cluster_ip_array": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"db_cluster_ip_array_name": {
Type: schema.TypeString,
Optional: true,
Default: "default",
},
"security_ips": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
},
"modify_mode": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Cover", "Append", "Delete"}, false),
},
},
},
},
"security_ips": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
Optional: true,
},
"connection_string": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"maintain_time": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"collector_status": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"Enable", "Disabled"}, false),
Optional: true,
Computed: true,
},
"parameters": {
Type: schema.TypeSet,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"value": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
},
},
Set: parameterToHash,
Optional: true,
Computed: true,
},
"tde_status": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"Enabled", "Disabled"}, false),
Optional: true,
Default: "Disabled",
},
"encrypt_new_tables": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"ON", "OFF"}, false),
Optional: true,
},
"security_group_ids": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
Optional: true,
},
"tags": tagsSchema(),
},
}
}
func resourceAlicloudPolarDBClusterCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
polarDBService := PolarDBService{client}
request, err := buildPolarDBCreateRequest(d, meta)
if err != nil {
return WrapError(err)
}
raw, err := client.WithPolarDBClient(func(polarClient *polardb.Client) (interface{}, error) {
return polarClient.CreateDBCluster(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_polardb_cluster", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*polardb.CreateDBClusterResponse)
d.SetId(response.DBClusterId)
// wait cluster status change from Creating to running
stateConf := BuildStateConf([]string{"Creating"}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 5*time.Minute, polarDBService.PolarDBClusterStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudPolarDBClusterUpdate(d, meta)
}
func resourceAlicloudPolarDBClusterUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
polarDBService := PolarDBService{client}
d.Partial(true)
if d.HasChange("parameters") {
if err := polarDBService.ModifyParameters(d); err != nil {
return WrapError(err)
}
d.SetPartial("parameters")
}
if err := polarDBService.setClusterTags(d); err != nil {
return WrapError(err)
}
conn, err := client.NewPolarDBClient()
if err != nil {
return WrapError(err)
}
payType := d.Get("pay_type").(string)
if !d.IsNewResource() && d.HasChange("pay_type") {
action := "TransformDBClusterPayType"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBClusterId": d.Id(),
"PayType": convertPolarDBPayTypeUpdateRequest(payType),
}
if payType == string(PrePaid) {
period := d.Get("period").(int)
request["UsedTime"] = strconv.Itoa(period)
request["Period"] = Month
if period > 9 {
request["UsedTime"] = strconv.Itoa(period / 12)
request["Period"] = Year
}
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-08-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if payType == string(PrePaid) {
d.SetPartial("period")
}
d.SetPartial("pay_type")
}
if (d.Get("pay_type").(string) == string(PrePaid)) &&
(d.HasChange("renewal_status") || d.HasChange("auto_renew_period")) {
status := d.Get("renewal_status").(string)
request := polardb.CreateModifyAutoRenewAttributeRequest()
request.DBClusterIds = d.Id()
request.RenewalStatus = status
if status == string(RenewAutoRenewal) {
period := d.Get("auto_renew_period").(int)
request.Duration = strconv.Itoa(period)
request.PeriodUnit = string(Month)
if period > 9 {
request.Duration = strconv.Itoa(period / 12)
request.PeriodUnit = string(Year)
}
}
//wait asynchronously cluster payType
if err := polarDBService.WaitForPolarDBPayType(d.Id(), "Prepaid", DefaultLongTimeout); err != nil {
return WrapError(err)
}
raw, err := client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.ModifyAutoRenewAttribute(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("renewal_status")
d.SetPartial("auto_renew_period")
}
if d.HasChange("maintain_time") {
request := polardb.CreateModifyDBClusterMaintainTimeRequest()
request.RegionId = client.RegionId
request.DBClusterId = d.Id()
request.MaintainTime = d.Get("maintain_time").(string)
raw, err := client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.ModifyDBClusterMaintainTime(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("maintain_time")
}
if d.HasChange("db_cluster_ip_array") {
if err := polarDBService.ModifyDBAccessWhitelistSecurityIps(d); err != nil {
return WrapError(err)
}
d.SetPartial("db_cluster_ip_array")
}
if d.HasChange("security_ips") {
ipList := expandStringList(d.Get("security_ips").(*schema.Set).List())
ipstr := strings.Join(ipList[:], COMMA_SEPARATED)
// default disable connect from outside
if ipstr == "" {
ipstr = LOCAL_HOST_IP
}
if err := polarDBService.ModifyDBSecurityIps(d.Id(), ipstr); err != nil {
return WrapError(err)
}
d.SetPartial("security_ips")
}
if d.HasChange("db_node_count") {
cluster, err := polarDBService.DescribePolarDBCluster(d.Id())
if err != nil {
return WrapError(err)
}
currentDbNodeCount := len(cluster.DBNodes.DBNode)
expectDbNodeCount := d.Get("db_node_count").(int)
if expectDbNodeCount > currentDbNodeCount {
//create node
expandDbNodes := &[]polardb.CreateDBNodesDBNode{
{
TargetClass: cluster.DBNodeClass,
},
}
request := polardb.CreateCreateDBNodesRequest()
request.RegionId = client.RegionId
request.DBClusterId = d.Id()
request.DBNode = expandDbNodes
raw, err := client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.CreateDBNodes(request)
})
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
if err != nil {
return WrapErrorf(
err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*polardb.CreateDBNodesResponse)
// wait cluster status change from DBNodeCreating to running
stateConf := BuildStateConf([]string{"DBNodeCreating"}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Minute, polarDBService.PolarDBClusterStateRefreshFunc(response.DBClusterId, []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, response.DBClusterId)
}
} else {
//delete node
deleteDbNodeId := ""
for _, dbNode := range cluster.DBNodes.DBNode {
if dbNode.DBNodeRole == "Reader" {
deleteDbNodeId = dbNode.DBNodeId
}
}
request := polardb.CreateDeleteDBNodesRequest()
request.RegionId = client.RegionId
request.DBClusterId = d.Id()
request.DBNodeId = &[]string{
deleteDbNodeId,
}
raw, err := client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.DeleteDBNodes(request)
})
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
stateConf := BuildStateConf([]string{"DBNodeDeleting"}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Minute, polarDBService.PolarDBClusterStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err = stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
}
if d.HasChange("collector_status") {
request := polardb.CreateModifyDBClusterAuditLogCollectorRequest()
request.RegionId = client.RegionId
request.DBClusterId = d.Id()
request.CollectorStatus = d.Get("collector_status").(string)
raw, err := client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.ModifyDBClusterAuditLogCollector(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("collector_status")
}
if v, ok := d.GetOk("db_type"); ok && v.(string) == "MySQL" {
if d.HasChange("tde_status") {
if v, ok := d.GetOk("tde_status"); ok && v.(string) != "Disabled" {
action := "ModifyDBClusterTDE"
request := map[string]interface{}{
"DBClusterId": d.Id(),
"TDEStatus": convertPolarDBTdeStatusUpdateRequest(v.(string)),
}
if s, ok := d.GetOk("encrypt_new_tables"); ok && s.(string) != "" {
request["EncryptNewTables"] = s.(string)
}
//retry
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-08-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
//wait tde status 'Enabled'
stateConf := BuildStateConf([]string{}, []string{"Enabled"}, d.Timeout(schema.TimeoutUpdate), 3*time.Minute, polarDBService.PolarDBClusterTDEStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("tde_status")
d.SetPartial("encrypt_new_tables")
}
}
}
if d.HasChange("security_group_ids") {
securityGroupsList := expandStringList(d.Get("security_group_ids").(*schema.Set).List())
securityGroupsStr := strings.Join(securityGroupsList[:], COMMA_SEPARATED)
request := polardb.CreateModifyDBClusterAccessWhitelistRequest()
request.RegionId = client.RegionId
request.DBClusterId = d.Id()
request.WhiteListType = "SecurityGroup"
request.SecurityGroupIds = securityGroupsStr
raw, err := client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.ModifyDBClusterAccessWhitelist(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("security_group_ids")
}
if d.IsNewResource() {
d.Partial(false)
return resourceAlicloudPolarDBClusterRead(d, meta)
}
if d.HasChange("db_node_class") {
request := polardb.CreateModifyDBNodeClassRequest()
request.RegionId = client.RegionId
request.DBClusterId = d.Id()
request.ModifyType = d.Get("modify_type").(string)
request.DBNodeTargetClass = d.Get("db_node_class").(string)
//wait asynchronously cluster nodes num the same
if err := polarDBService.WaitForPolarDBNodeClass(d.Id(), DefaultLongTimeout); err != nil {
return WrapError(err)
}
raw, err := client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.ModifyDBNodeClass(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
// wait cluster status change from Creating to running
stateConf := BuildStateConf([]string{"ClassChanging"}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 5*time.Minute, polarDBService.PolarDBClusterStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("db_node_class")
}
if d.HasChange("description") {
request := polardb.CreateModifyDBClusterDescriptionRequest()
request.RegionId = client.RegionId
request.DBClusterId = d.Id()
request.DBClusterDescription = d.Get("description").(string)
raw, err := client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.ModifyDBClusterDescription(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("description")
}
d.Partial(false)
return resourceAlicloudPolarDBClusterRead(d, meta)
}
func resourceAlicloudPolarDBClusterRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
polarDBService := PolarDBService{client}
clusterAttribute, err := polarDBService.DescribePolarDBClusterAttribute(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
cluster, err := polarDBService.DescribePolarDBCluster(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
dbClusterIPArrayName := "default"
if v, ok := d.GetOk("db_cluster_ip_array_name"); ok {
dbClusterIPArrayName = v.(string)
}
if err = polarDBService.DBClusterIPArrays(d, "db_cluster_ip_array", dbClusterIPArrayName); err != nil {
return WrapError(err)
}
ips, err := polarDBService.DescribeDBSecurityIps(d.Id(), dbClusterIPArrayName)
if err != nil {
return WrapError(err)
}
d.Set("security_ips", ips)
//describe endpoints
if len(ips) == 1 && strings.HasPrefix(ips[0], LOCAL_HOST_IP) {
d.Set("connection_string", "")
} else {
endpoints, err := polarDBService.DescribePolarDBInstanceNetInfo(d.Id())
if err != nil {
return WrapError(err)
}
for _, endpoint := range endpoints {
if endpoint.EndpointType == "Cluster" {
d.Set("connection_string", endpoint.AddressItems[0].ConnectionString)
}
}
}
d.Set("vswitch_id", clusterAttribute.VSwitchId)
d.Set("pay_type", getChargeType(clusterAttribute.PayType))
d.Set("id", clusterAttribute.DBClusterId)
d.Set("description", clusterAttribute.DBClusterDescription)
d.Set("db_type", clusterAttribute.DBType)
d.Set("db_version", clusterAttribute.DBVersion)
d.Set("maintain_time", clusterAttribute.MaintainTime)
d.Set("zone_ids", clusterAttribute.ZoneIds)
d.Set("db_node_class", cluster.DBNodeClass)
d.Set("db_node_count", len(clusterAttribute.DBNodes))
d.Set("resource_group_id", clusterAttribute.ResourceGroupId)
tags, err := polarDBService.DescribeTags(d.Id(), "cluster")
if err != nil {
return WrapError(err)
}
d.Set("tags", polarDBService.tagsToMap(tags))
if clusterAttribute.PayType == string(Prepaid) {
clusterAutoRenew, err := polarDBService.DescribePolarDBAutoRenewAttribute(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
renewPeriod := 1
if clusterAutoRenew != nil {
renewPeriod = clusterAutoRenew.Duration
}
if clusterAutoRenew != nil && clusterAutoRenew.PeriodUnit == string(Year) {
renewPeriod = renewPeriod * 12
}
d.Set("auto_renew_period", renewPeriod)
//period, err := computePeriodByUnit(clusterAttribute.CreationTime, clusterAttribute.ExpireTime, d.Get("period").(int), "Month")
//if err != nil {
// return WrapError(err)
//}
//d.Set("period", period)
d.Set("renewal_status", clusterAutoRenew.RenewalStatus)
}
if err = polarDBService.RefreshParameters(d); err != nil {
return WrapError(err)
}
clusterCollectStatus, err := polarDBService.DescribeDBAuditLogCollectorStatus(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("collector_status", clusterCollectStatus)
clusterTDEStatus, err := polarDBService.DescribeDBClusterTDE(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("tde_status", clusterTDEStatus["TDEStatus"])
d.Set("encrypt_new_tables", clusterTDEStatus["EncryptNewTables"])
securityGroups, err := polarDBService.DescribeDBSecurityGroups(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("security_group_ids", securityGroups)
return nil
}
func resourceAlicloudPolarDBClusterDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
polarDBService := PolarDBService{client}
cluster, err := polarDBService.DescribePolarDBClusterAttribute(d.Id())
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
// Pre paid cluster can not be release.
if PayType(cluster.PayType) == Prepaid {
return WrapError(Error("At present, 'Prepaid' instance cannot be deleted and must wait it to be expired and release it automatically."))
}
request := polardb.CreateDeleteDBClusterRequest()
request.RegionId = client.RegionId
request.DBClusterId = d.Id()
err = resource.Retry(10*time.Minute, func() *resource.RetryError {
raw, err := client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.DeleteDBCluster(request)
})
if err != nil && !NotFoundError(err) {
if IsExpectedErrors(err, []string{"OperationDenied.DBClusterStatus", "OperationDenied.PolarDBClusterStatus", "OperationDenied.ReadPolarDBClusterStatus"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"Creating", "Running", "Deleting"}, []string{}, d.Timeout(schema.TimeoutDelete), 1*time.Minute, polarDBService.PolarDBClusterStateRefreshFunc(d.Id(), []string{}))
if _, err = stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
func buildPolarDBCreateRequest(d *schema.ResourceData, meta interface{}) (*polardb.CreateDBClusterRequest, error) {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
request := polardb.CreateCreateDBClusterRequest()
request.RegionId = string(client.Region)
request.DBType = Trim(d.Get("db_type").(string))
request.DBVersion = Trim(d.Get("db_version").(string))
request.DBNodeClass = d.Get("db_node_class").(string)
request.DBClusterDescription = d.Get("description").(string)
request.ClientToken = buildClientToken(request.GetActionName())
if v, ok := d.GetOk("resource_group_id"); ok && v.(string) != "" {
request.ResourceGroupId = v.(string)
}
if zone, ok := d.GetOk("zone_id"); ok && Trim(zone.(string)) != "" {
request.ZoneId = Trim(zone.(string))
}
vswitchId := Trim(d.Get("vswitch_id").(string))
if vswitchId != "" {
request.VSwitchId = vswitchId
request.ClusterNetworkType = strings.ToUpper(string(Vpc))
// check vswitchId in zone
vsw, err := vpcService.DescribeVSwitch(vswitchId)
if err != nil {
return nil, WrapError(err)
}
if request.ZoneId == "" {
request.ZoneId = vsw.ZoneId
} else if request.ZoneId != vsw.ZoneId {
return nil, WrapError(Error("The specified vswitch %s isn't in the zone %s.", vsw.VSwitchId, request.ZoneId))
}
request.VPCId = vsw.VpcId
}
payType := Trim(d.Get("pay_type").(string))
request.PayType = string(Postpaid)
if payType == string(PrePaid) {
request.PayType = string(Prepaid)
}
if PayType(request.PayType) == Prepaid {
period := d.Get("period").(int)
request.UsedTime = strconv.Itoa(period)
request.Period = string(Month)
if period > 9 {
request.UsedTime = strconv.Itoa(period / 12)
request.Period = string(Year)
}
if d.Get("renewal_status").(string) != string(RenewNotRenewal) {
request.AutoRenew = requests.Boolean(strconv.FormatBool(true))
} else {
request.AutoRenew = requests.Boolean(strconv.FormatBool(false))
}
}
request.TDEStatus = requests.NewBoolean(convertPolarDBTdeStatusCreateRequest(d.Get("tde_status").(string)))
return request, nil
}
func convertPolarDBTdeStatusCreateRequest(source string) bool {
switch source {
case "Enabled":
return true
}
return false
}
func convertPolarDBTdeStatusUpdateRequest(source string) string {
switch source {
case "Enabled":
return "Enable"
}
return "Disable"
}
func convertPolarDBPayTypeUpdateRequest(source string) string {
switch source {
case "PrePaid":
return "Prepaid"
}
return "Postpaid"
}
package alicloud
import (
"fmt"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/polardb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudPolarDBDatabase() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudPolarDBDatabaseCreate,
Read: resourceAlicloudPolarDBDatabaseRead,
Update: resourceAlicloudPolarDBDatabaseUpdate,
Delete: resourceAlicloudPolarDBDatabaseDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"db_cluster_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"db_name": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"character_set_name": {
Type: schema.TypeString,
Optional: true,
Default: "utf8",
ForceNew: true,
},
"db_description": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudPolarDBDatabaseCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := polardb.CreateCreateDatabaseRequest()
request.RegionId = client.RegionId
request.DBClusterId = d.Get("db_cluster_id").(string)
request.DBName = d.Get("db_name").(string)
request.CharacterSetName = d.Get("character_set_name").(string)
if v, ok := d.GetOk("db_description"); ok && v.(string) != "" {
request.DBDescription = v.(string)
}
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.CreateDatabase(request)
})
if err != nil {
if IsExpectedErrors(err, OperationDeniedDBStatus) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprintf("%s%s%s", request.DBClusterId, COLON_SEPARATED, request.DBName))
return resourceAlicloudPolarDBDatabaseRead(d, meta)
}
func resourceAlicloudPolarDBDatabaseRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
polarDBService := PolarDBService{client}
object, err := polarDBService.DescribePolarDBDatabase(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
d.SetId("")
return nil
}
d.Set("db_cluster_id", parts[0])
d.Set("db_name", object.DBName)
d.Set("character_set_name", object.CharacterSetName)
d.Set("db_description", object.DBDescription)
return nil
}
func resourceAlicloudPolarDBDatabaseUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
if d.HasChange("db_description") {
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request := polardb.CreateModifyDBDescriptionRequest()
request.RegionId = client.RegionId
request.DBClusterId = parts[0]
request.DBName = parts[1]
request.DBDescription = d.Get("db_description").(string)
var raw interface{}
raw, err = client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.ModifyDBDescription(request)
})
if err != nil {
return WrapError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
return resourceAlicloudPolarDBDatabaseRead(d, meta)
}
func resourceAlicloudPolarDBDatabaseDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
polarDBService := PolarDBService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request := polardb.CreateDeleteDatabaseRequest()
request.RegionId = client.RegionId
request.DBClusterId = parts[0]
request.DBName = parts[1]
// wait instance status is running before deleting database
if err := polarDBService.WaitForPolarDBInstance(parts[0], Running, 1800); err != nil {
return WrapError(err)
}
raw, err := client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.DeleteDatabase(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(polarDBService.WaitForPolarDBDatabase(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"encoding/json"
"fmt"
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/polardb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudPolarDBEndpoint() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudPolarDBEndpointCreate,
Read: resourceAlicloudPolarDBEndpointRead,
Update: resourceAlicloudPolarDBEndpointUpdate,
Delete: resourceAlicloudPolarDBEndpointDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"db_cluster_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"endpoint_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Custom", "Primary", "Cluster"}, false),
Default: "Custom",
},
"nodes": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"read_write_mode": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"ReadWrite", "ReadOnly"}, false),
Optional: true,
Computed: true,
},
"auto_add_new_nodes": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"Enable", "Disable"}, false),
Optional: true,
Computed: true,
},
"endpoint_config": {
Type: schema.TypeMap,
Optional: true,
Computed: true,
},
"ssl_enabled": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"Enable", "Disable", "Update"}, false),
Optional: true,
},
"ssl_connection_string": {
Type: schema.TypeString,
Computed: true,
},
"net_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Public", "Private", "Inner"}, false),
},
"ssl_expire_time": {
Type: schema.TypeString,
Computed: true,
},
"ssl_auto_rotate": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Enable", "Disable"}, false),
},
"ssl_certificate_url": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudPolarDBEndpointCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
polarDBService := PolarDBService{client}
clusterId := d.Get("db_cluster_id").(string)
endpointType := d.Get("endpoint_type").(string)
request := polardb.CreateCreateDBClusterEndpointRequest()
request.RegionId = client.RegionId
request.DBClusterId = clusterId
request.EndpointType = endpointType
if nodes, ok := d.GetOk("nodes"); ok {
nodes := expandStringList(nodes.(*schema.Set).List())
dbNodes := strings.Join(nodes, ",")
request.Nodes = dbNodes
}
if readWriteMode, ok := d.GetOk("read_write_mode"); ok {
request.ReadWriteMode = readWriteMode.(string)
}
if autoAddNewNodes, ok := d.GetOk("auto_add_new_nodes"); ok {
request.AutoAddNewNodes = autoAddNewNodes.(string)
}
if endpointConfig, ok := d.GetOk("endpoint_config"); ok {
endpointConfig, err := json.Marshal(endpointConfig)
if err != nil {
return WrapError(err)
}
request.EndpointConfig = string(endpointConfig)
}
enpoints, err := polarDBService.DescribePolarDBInstanceNetInfo(clusterId)
if err != nil {
return WrapError(err)
}
oldEndpoints := make([]interface{}, 0)
for _, value := range enpoints {
oldEndpoints = append(oldEndpoints, value.DBEndpointId)
}
oldEndpointIds := schema.NewSet(schema.HashString, oldEndpoints)
var raw interface{}
err = resource.Retry(8*time.Minute, func() *resource.RetryError {
raw, err = client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.CreateDBClusterEndpoint(request)
})
if err != nil {
OperationDeniedDBStatus = append(OperationDeniedDBStatus, "ClusterEndpoint.StatusNotValid")
if IsExpectedErrors(err, OperationDeniedDBStatus) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_polardb_endpoint", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
dbEndpointId, err := polarDBService.WaitForPolarDBEndpoints(d, Active, oldEndpointIds, DefaultTimeoutMedium)
if err != nil {
return WrapError(err)
}
d.SetId(fmt.Sprintf("%s%s%s", clusterId, COLON_SEPARATED, dbEndpointId))
return resourceAlicloudPolarDBEndpointUpdate(d, meta)
}
func resourceAlicloudPolarDBEndpointRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
polarDBService := PolarDBService{client}
parts, errParse := ParseResourceId(d.Id(), 2)
if errParse != nil {
return WrapError(errParse)
}
dbClusterId := parts[0]
dbEndpointId := parts[1]
object, err := polarDBService.DescribePolarDBClusterEndpoint(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("db_cluster_id", dbClusterId)
d.Set("endpoint_type", object.EndpointType)
nodes := strings.Split(object.Nodes, ",")
d.Set("nodes", nodes)
var autoAddNewNodes string
var readWriteMode string
if object.EndpointType == "Primary" {
autoAddNewNodes = "Disable"
readWriteMode = "ReadWrite"
} else {
autoAddNewNodes = object.AutoAddNewNodes
readWriteMode = object.ReadWriteMode
}
d.Set("auto_add_new_nodes", autoAddNewNodes)
d.Set("read_write_mode", readWriteMode)
if err = polarDBService.RefreshEndpointConfig(d); err != nil {
return WrapError(err)
}
dbClusterSSL, err := polarDBService.DescribePolarDBClusterSSL(d)
var sslConnectionString string
var sslExpireTime string
var sslEnabled string
if len(dbClusterSSL.Items) < 1 {
sslConnectionString = ""
sslExpireTime = ""
sslEnabled = ""
} else if len(dbClusterSSL.Items) == 1 && dbClusterSSL.Items[0].DBEndpointId == "" {
sslConnectionString = dbClusterSSL.Items[0].SSLConnectionString
sslExpireTime = dbClusterSSL.Items[0].SSLExpireTime
sslEnabled = convertPolarDBSSLEnableResponse(dbClusterSSL.Items[0].SSLEnabled)
} else {
for _, item := range dbClusterSSL.Items {
if item.DBEndpointId == dbEndpointId {
sslConnectionString = item.SSLConnectionString
sslExpireTime = item.SSLExpireTime
sslEnabled = convertPolarDBSSLEnableResponse(item.SSLEnabled)
}
}
}
sslAutoRotate := dbClusterSSL.SSLAutoRotate
if err := d.Set("ssl_connection_string", sslConnectionString); err != nil {
return WrapError(err)
}
if err := d.Set("ssl_expire_time", sslExpireTime); err != nil {
return WrapError(err)
}
if err := d.Set("ssl_auto_rotate", sslAutoRotate); err != nil {
return WrapError(err)
}
if sslEnabled == "Enable" {
d.Set("ssl_certificate_url", "https://apsaradb-public.oss-ap-southeast-1.aliyuncs.com/ApsaraDB-CA-Chain.zip?file=ApsaraDB-CA-Chain.zip®ionId="+polarDBService.client.RegionId)
} else {
d.Set("ssl_certificate_url", "")
}
return nil
}
func resourceAlicloudPolarDBEndpointUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
polarDBService := PolarDBService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
dbClusterId := parts[0]
dbEndpointId := parts[1]
if d.HasChange("nodes") || d.HasChange("read_write_mode") || d.HasChange("auto_add_new_nodes") || d.HasChange("endpoint_config") {
modifyEndpointRequest := polardb.CreateModifyDBClusterEndpointRequest()
modifyEndpointRequest.RegionId = client.RegionId
modifyEndpointRequest.DBClusterId = dbClusterId
modifyEndpointRequest.DBEndpointId = dbEndpointId
configItem := make(map[string]string)
if d.HasChange("nodes") {
nodes := expandStringList(d.Get("nodes").(*schema.Set).List())
dbNodes := strings.Join(nodes, ",")
modifyEndpointRequest.Nodes = dbNodes
configItem["Nodes"] = dbNodes
}
if d.HasChange("read_write_mode") {
modifyEndpointRequest.ReadWriteMode = d.Get("read_write_mode").(string)
configItem["ReadWriteMode"] = d.Get("read_write_mode").(string)
}
if d.HasChange("auto_add_new_nodes") {
modifyEndpointRequest.AutoAddNewNodes = d.Get("auto_add_new_nodes").(string)
configItem["AutoAddNewNodes"] = d.Get("auto_add_new_nodes").(string)
}
if d.HasChange("endpoint_config") {
endpointConfig, err := json.Marshal(d.Get("endpoint_config"))
if err != nil {
return WrapError(err)
}
modifyEndpointRequest.EndpointConfig = string(endpointConfig)
configItem["EndpointConfig"] = string(endpointConfig)
}
if err := resource.Retry(8*time.Minute, func() *resource.RetryError {
raw, err := client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.ModifyDBClusterEndpoint(modifyEndpointRequest)
})
if err != nil {
if IsExpectedErrors(err, []string{"EndpointStatus.NotSupport", "OperationDenied.DBClusterStatus"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(modifyEndpointRequest.GetActionName(), raw, modifyEndpointRequest.RpcRequest, modifyEndpointRequest)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), modifyEndpointRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
// wait cluster endpoint config modified
if err := polarDBService.WaitPolardbEndpointConfigEffect(
d.Id(), configItem, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
}
if d.HasChange("ssl_enabled") || d.HasChange("net_type") || d.HasChange("ssl_auto_rotate") {
if d.Get("ssl_enabled") == "" && d.Get("net_type") != "" {
return WrapErrorf(Error("Need to specify ssl_enabled as Enable or Disable, if you want to modify the net_type."), DefaultErrorMsg, d.Id(), "ModifyDBClusterSSL", ProviderERROR)
}
modifySSLRequest := polardb.CreateModifyDBClusterSSLRequest()
modifySSLRequest.SSLEnabled = d.Get("ssl_enabled").(string)
modifySSLRequest.NetType = d.Get("net_type").(string)
modifySSLRequest.DBClusterId = dbClusterId
modifySSLRequest.DBEndpointId = dbEndpointId
modifySSLRequest.SSLAutoRotate = d.Get("ssl_auto_rotate").(string)
if err := resource.Retry(8*time.Minute, func() *resource.RetryError {
raw, err := client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.ModifyDBClusterSSL(modifySSLRequest)
})
if err != nil {
if IsExpectedErrors(err, []string{"EndpointStatus.NotSupport", "OperationDenied.DBClusterStatus"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(modifySSLRequest.GetActionName(), raw, modifySSLRequest.RpcRequest, modifySSLRequest)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), modifySSLRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
// wait cluster status change from SSL_MODIFYING to Running
stateConf := BuildStateConf([]string{"SSL_MODIFYING"}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Minute, polarDBService.PolarDBClusterStateRefreshFunc(dbClusterId, []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, dbClusterId)
}
}
return resourceAlicloudPolarDBEndpointRead(d, meta)
}
func resourceAlicloudPolarDBEndpointDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
polarDBService := PolarDBService{client}
parts, errParse := ParseResourceId(d.Id(), 2)
if errParse != nil {
return WrapError(errParse)
}
object, err := polarDBService.DescribePolarDBClusterEndpoint(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
if object.EndpointType != "Custom" {
return WrapErrorf(Error(fmt.Sprintf("%s type endpoint can not be deleted.", object.EndpointType)), DefaultErrorMsg, d.Id(), "DeleteDBClusterEndpoint", ProviderERROR)
}
request := polardb.CreateDeleteDBClusterEndpointRequest()
request.RegionId = client.RegionId
request.DBClusterId = parts[0]
request.DBEndpointId = parts[1]
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.DeleteDBClusterEndpoint(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"OperationDenied.DBClusterStatus", "EndpointStatus.NotSupport", "ClusterEndpoint.StatusNotValid"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound", "InvalidCurrentConnectionString.NotFound", "AtLeastOneNetTypeExists"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
endpointIds := schema.NewSet(schema.HashString, make([]interface{}, 0))
dbEndpoint, err := polarDBService.WaitForPolarDBEndpoints(d, Deleted, endpointIds, DefaultTimeoutMedium)
if dbEndpoint != "" || err != nil {
return WrapErrorf(err, DeleteTimeoutMsg, d.Id(), request.GetActionName(), ProviderERROR)
}
return nil
}
func convertPolarDBSSLEnableResponse(source string) string {
switch source {
case "Enabled":
return "Enable"
}
return "Disable"
}
package alicloud
import (
"fmt"
"regexp"
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/polardb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudPolarDBEndpointAddress() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudPolarDBEndpointAddressCreate,
Read: resourceAlicloudPolarDBEndpointAddressRead,
Update: resourceAlicloudPolarDBEndpointAddressUpdate,
Delete: resourceAlicloudPolarDBEndpointAddressDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"db_cluster_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"db_endpoint_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"net_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Public"}, false),
Default: "Public",
ForceNew: true,
},
"connection_prefix": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-z][a-z0-9\\-]{4,28}[a-z0-9]$`), "The prefix must be 6 to 30 characters in length, and can contain lowercase letters, digits, and hyphens (-), must start with a letter and end with a digit or letter."),
},
"port": {
Type: schema.TypeString,
Computed: true,
},
"connection_string": {
Type: schema.TypeString,
Computed: true,
},
"ip_address": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudPolarDBEndpointAddressCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
polarDBService := PolarDBService{client}
clusterId := d.Get("db_cluster_id").(string)
dbEndpointId := d.Get("db_endpoint_id").(string)
netType := d.Get("net_type").(string)
request := polardb.CreateCreateDBEndpointAddressRequest()
request.RegionId = client.RegionId
request.DBClusterId = clusterId
request.DBEndpointId = dbEndpointId
request.NetType = netType
if v, ok := d.GetOk("connection_prefix"); ok && v.(string) != "" {
request.ConnectionStringPrefix = v.(string)
}
var raw interface{}
var err error
err = resource.Retry(8*time.Minute, func() *resource.RetryError {
raw, err = client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.CreateDBEndpointAddress(request)
})
if err != nil {
if IsExpectedErrors(err, OperationDeniedDBStatus) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_polardb_endpoint_address", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprintf("%s%s%s", clusterId, COLON_SEPARATED, dbEndpointId))
if err := polarDBService.WaitForPolarDBConnection(d.Id(), Available, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
// wait instance running after allocating
if err := polarDBService.WaitForPolarDBInstance(clusterId, Running, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
return resourceAlicloudPolarDBEndpointAddressRead(d, meta)
}
func resourceAlicloudPolarDBEndpointAddressRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
polarDBService := PolarDBService{client}
object, err := polarDBService.DescribePolarDBConnection(d.Id())
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("db_cluster_id", parts[0])
d.Set("db_endpoint_id", parts[1])
d.Set("port", object.Port)
d.Set("net_type", object.NetType)
d.Set("connection_string", object.ConnectionString)
d.Set("ip_address", object.IPAddress)
prefix := strings.Split(object.ConnectionString, ".")
d.Set("connection_prefix", prefix[0])
return nil
}
func resourceAlicloudPolarDBEndpointAddressUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
polarDBService := PolarDBService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
if d.HasChange("connection_prefix") {
request := polardb.CreateModifyDBEndpointAddressRequest()
request.RegionId = client.RegionId
request.DBClusterId = parts[0]
request.DBEndpointId = parts[1]
object, err := polarDBService.DescribePolarDBConnection(d.Id())
if err != nil {
return WrapError(err)
}
request.NetType = object.NetType
request.ConnectionStringPrefix = d.Get("connection_prefix").(string)
request.NetType = d.Get("net_type").(string)
if err := resource.Retry(8*time.Minute, func() *resource.RetryError {
raw, err := client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.ModifyDBEndpointAddress(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"EndpointStatus.NotSupport", "OperationDenied.DBClusterStatus"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
// wait instance connection_prefix modify success
if err := polarDBService.WaitForPolarDBConnectionPrefix(d.Id(), request.ConnectionStringPrefix, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
}
return resourceAlicloudPolarDBEndpointAddressRead(d, meta)
}
func resourceAlicloudPolarDBEndpointAddressDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
polarDBService := PolarDBService{client}
parts, errParse := ParseResourceId(d.Id(), 2)
if errParse != nil {
return WrapError(errParse)
}
request := polardb.CreateDeleteDBEndpointAddressRequest()
request.RegionId = client.RegionId
request.DBClusterId = parts[0]
request.DBEndpointId = parts[1]
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
object, err := polarDBService.DescribePolarDBConnection(d.Id())
if err != nil {
return resource.NonRetryableError(WrapError(err))
}
request.NetType = object.NetType
var raw interface{}
raw, err = client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.DeleteDBEndpointAddress(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"OperationDenied.DBClusterStatus", "EndpointStatus.NotSupport"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound", "InvalidCurrentConnectionString.NotFound", "AtLeastOneNetTypeExists"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return polarDBService.WaitForPolarDBConnection(d.Id(), Deleted, DefaultTimeoutMedium)
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudPrivatelinkVpcEndpoint() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudPrivatelinkVpcEndpointCreate,
Read: resourceAlicloudPrivatelinkVpcEndpointRead,
Update: resourceAlicloudPrivatelinkVpcEndpointUpdate,
Delete: resourceAlicloudPrivatelinkVpcEndpointDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(6 * time.Minute),
Delete: schema.DefaultTimeout(3 * time.Minute),
Update: schema.DefaultTimeout(6 * time.Minute),
},
Schema: map[string]*schema.Schema{
"bandwidth": {
Type: schema.TypeInt,
Computed: true,
},
"connection_status": {
Type: schema.TypeString,
Computed: true,
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"endpoint_business_status": {
Type: schema.TypeString,
Computed: true,
},
"endpoint_description": {
Type: schema.TypeString,
Optional: true,
},
"endpoint_domain": {
Type: schema.TypeString,
Computed: true,
},
"security_group_ids": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"service_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"service_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vpc_endpoint_name": {
Type: schema.TypeString,
Optional: true,
},
"vpc_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudPrivatelinkVpcEndpointCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
privatelinkService := PrivatelinkService{client}
var response map[string]interface{}
action := "CreateVpcEndpoint"
request := make(map[string]interface{})
conn, err := client.NewPrivatelinkClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
if v, ok := d.GetOk("endpoint_description"); ok {
request["EndpointDescription"] = v
}
request["RegionId"] = client.RegionId
request["SecurityGroupId"] = d.Get("security_group_ids").(*schema.Set).List()
if v, ok := d.GetOk("service_id"); ok {
request["ServiceId"] = v
}
if v, ok := d.GetOk("service_name"); ok {
request["ServiceName"] = v
}
if v, ok := d.GetOk("vpc_endpoint_name"); ok {
request["EndpointName"] = v
}
request["VpcId"] = d.Get("vpc_id")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_privatelink_vpc_endpoint", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["EndpointId"]))
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutCreate), 60*time.Second, privatelinkService.PrivatelinkVpcEndpointStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudPrivatelinkVpcEndpointRead(d, meta)
}
func resourceAlicloudPrivatelinkVpcEndpointRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
privatelinkService := PrivatelinkService{client}
object, err := privatelinkService.DescribePrivatelinkVpcEndpoint(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_privatelink_vpc_endpoint privatelinkService.DescribePrivatelinkVpcEndpoint Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("bandwidth", formatInt(object["Bandwidth"]))
d.Set("connection_status", object["ConnectionStatus"])
d.Set("endpoint_business_status", object["EndpointBusinessStatus"])
d.Set("endpoint_description", object["EndpointDescription"])
d.Set("endpoint_domain", object["EndpointDomain"])
d.Set("service_id", object["ServiceId"])
d.Set("service_name", object["ServiceName"])
d.Set("status", object["EndpointStatus"])
d.Set("vpc_endpoint_name", object["EndpointName"])
d.Set("vpc_id", object["VpcId"])
listVpcEndpointSecurityGroupsObject, err := privatelinkService.ListVpcEndpointSecurityGroups(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("security_group_ids", convertSecurityGroupIdToStringList(listVpcEndpointSecurityGroupsObject["SecurityGroups"]))
return nil
}
func resourceAlicloudPrivatelinkVpcEndpointUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
privatelinkService := PrivatelinkService{client}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"EndpointId": d.Id(),
}
request["RegionId"] = client.RegionId
if d.HasChange("security_group_ids") && !d.IsNewResource() {
if _, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = d.Get("dry_run")
}
conn, err := client.NewPrivatelinkClient()
if err != nil {
return WrapError(err)
}
o, n := d.GetChange("security_group_ids")
os := o.(*schema.Set)
ns := n.(*schema.Set)
rl := expandStringList(os.Difference(ns).List())
al := expandStringList(ns.Difference(os).List())
if len(al) > 0 {
for _, a := range al {
action := "AttachSecurityGroupToVpcEndpoint"
request["SecurityGroupId"] = a
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutUpdate), 60*time.Second, privatelinkService.PrivatelinkVpcEndpointStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
}
if len(rl) > 0 {
for _, r := range rl {
action := "DetachSecurityGroupFromVpcEndpoint"
request["SecurityGroupId"] = r
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutUpdate), 60*time.Second, privatelinkService.PrivatelinkVpcEndpointStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
}
d.SetPartial("security_group_ids")
}
update = false
updateVpcEndpointAttributeReq := map[string]interface{}{
"EndpointId": d.Id(),
}
updateVpcEndpointAttributeReq["RegionId"] = client.RegionId
if d.HasChange("endpoint_description") {
update = true
updateVpcEndpointAttributeReq["EndpointDescription"] = d.Get("endpoint_description")
}
if d.HasChange("vpc_endpoint_name") {
update = true
updateVpcEndpointAttributeReq["EndpointName"] = d.Get("vpc_endpoint_name")
}
if update {
if _, ok := d.GetOkExists("dry_run"); ok {
updateVpcEndpointAttributeReq["DryRun"] = d.Get("dry_run")
}
action := "UpdateVpcEndpointAttribute"
conn, err := client.NewPrivatelinkClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, updateVpcEndpointAttributeReq, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"EndpointConnectionOperationDenied", "EndpointLocked", "EndpointOperationDenied"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("endpoint_description")
d.SetPartial("vpc_endpoint_name")
}
d.Partial(false)
return resourceAlicloudPrivatelinkVpcEndpointRead(d, meta)
}
func resourceAlicloudPrivatelinkVpcEndpointDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteVpcEndpoint"
var response map[string]interface{}
conn, err := client.NewPrivatelinkClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"EndpointId": d.Id(),
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"EndpointOperationDenied"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EndpointNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func convertSecurityGroupIdToStringList(src interface{}) (result []interface{}) {
if err, ok := src.([]interface{}); !ok {
panic(err)
}
for _, v := range src.([]interface{}) {
vv := v.(map[string]interface{})
result = append(result, vv["SecurityGroupId"].(string))
}
return
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudPrivatelinkVpcEndpointConnection() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudPrivatelinkVpcEndpointConnectionCreate,
Read: resourceAlicloudPrivatelinkVpcEndpointConnectionRead,
Update: resourceAlicloudPrivatelinkVpcEndpointConnectionUpdate,
Delete: resourceAlicloudPrivatelinkVpcEndpointConnectionDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(11 * time.Minute),
Delete: schema.DefaultTimeout(6 * time.Minute),
Update: schema.DefaultTimeout(4 * time.Minute),
},
Schema: map[string]*schema.Schema{
"bandwidth": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"endpoint_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"service_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudPrivatelinkVpcEndpointConnectionCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
privatelinkService := PrivatelinkService{client}
var response map[string]interface{}
action := "EnableVpcEndpointConnection"
request := make(map[string]interface{})
conn, err := client.NewPrivatelinkClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("bandwidth"); ok {
request["Bandwidth"] = v
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["EndpointId"] = d.Get("endpoint_id")
request["RegionId"] = client.RegionId
request["ServiceId"] = d.Get("service_id")
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"EndpointConnectionOperationDenied"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_privatelink_vpc_endpoint_connection", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["ServiceId"], ":", request["EndpointId"]))
stateConf := BuildStateConf([]string{}, []string{"Connected"}, d.Timeout(schema.TimeoutCreate), 60*time.Second, privatelinkService.PrivatelinkVpcEndpointConnectionStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudPrivatelinkVpcEndpointConnectionRead(d, meta)
}
func resourceAlicloudPrivatelinkVpcEndpointConnectionRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
privatelinkService := PrivatelinkService{client}
object, err := privatelinkService.DescribePrivatelinkVpcEndpointConnection(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_privatelink_vpc_endpoint_connection privatelinkService.DescribePrivatelinkVpcEndpointConnection Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("endpoint_id", parts[1])
d.Set("service_id", parts[0])
d.Set("bandwidth", object["Bandwidth"])
d.Set("status", object["ConnectionStatus"])
return nil
}
func resourceAlicloudPrivatelinkVpcEndpointConnectionUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"EndpointId": parts[1],
"ServiceId": parts[0],
}
request["RegionId"] = client.RegionId
if d.HasChange("bandwidth") {
update = true
request["Bandwidth"] = d.Get("bandwidth")
}
if update {
if _, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = d.Get("dry_run")
}
action := "UpdateVpcEndpointConnectionAttribute"
conn, err := client.NewPrivatelinkClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("UpdateVpcEndpointConnectionAttribute")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"EndpointConnectionOperationDenied"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudPrivatelinkVpcEndpointConnectionRead(d, meta)
}
func resourceAlicloudPrivatelinkVpcEndpointConnectionDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
privatelinkService := PrivatelinkService{client}
action := "DisableVpcEndpointConnection"
var response map[string]interface{}
conn, err := client.NewPrivatelinkClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"EndpointId": parts[1],
"ServiceId": parts[0],
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"EndpointConnectionOperationDenied"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EndpointConnectionNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Disconnected"}, d.Timeout(schema.TimeoutDelete), 60*time.Second, privatelinkService.PrivatelinkVpcEndpointConnectionStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudPrivatelinkVpcEndpointService() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudPrivatelinkVpcEndpointServiceCreate,
Read: resourceAlicloudPrivatelinkVpcEndpointServiceRead,
Update: resourceAlicloudPrivatelinkVpcEndpointServiceUpdate,
Delete: resourceAlicloudPrivatelinkVpcEndpointServiceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(6 * time.Minute),
Delete: schema.DefaultTimeout(6 * time.Minute),
Update: schema.DefaultTimeout(4 * time.Minute),
},
Schema: map[string]*schema.Schema{
"auto_accept_connection": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"connect_bandwidth": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"payer": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "Endpoint",
ValidateFunc: validation.StringInSlice([]string{"Endpoint", "EndpointService"}, false),
},
"service_business_status": {
Type: schema.TypeString,
Computed: true,
},
"service_description": {
Type: schema.TypeString,
Optional: true,
},
"service_domain": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudPrivatelinkVpcEndpointServiceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
privatelinkService := PrivatelinkService{client}
var response map[string]interface{}
action := "CreateVpcEndpointService"
request := make(map[string]interface{})
conn, err := client.NewPrivatelinkClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("auto_accept_connection"); ok {
request["AutoAcceptEnabled"] = v
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
if v, ok := d.GetOk("payer"); ok {
request["Payer"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("service_description"); ok {
request["ServiceDescription"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_privatelink_vpc_endpoint_service", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["ServiceId"]))
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutCreate), 60*time.Second, privatelinkService.PrivatelinkVpcEndpointServiceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudPrivatelinkVpcEndpointServiceUpdate(d, meta)
}
func resourceAlicloudPrivatelinkVpcEndpointServiceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
privatelinkService := PrivatelinkService{client}
object, err := privatelinkService.DescribePrivatelinkVpcEndpointService(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_privatelink_vpc_endpoint_service privatelinkService.DescribePrivatelinkVpcEndpointService Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("auto_accept_connection", object["AutoAcceptEnabled"])
d.Set("connect_bandwidth", formatInt(object["ConnectBandwidth"]))
d.Set("service_business_status", object["ServiceBusinessStatus"])
d.Set("service_description", object["ServiceDescription"])
d.Set("service_domain", object["ServiceDomain"])
d.Set("status", object["ServiceStatus"])
return nil
}
func resourceAlicloudPrivatelinkVpcEndpointServiceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"ServiceId": d.Id(),
}
request["RegionId"] = client.RegionId
if !d.IsNewResource() && d.HasChange("auto_accept_connection") {
update = true
request["AutoAcceptEnabled"] = d.Get("auto_accept_connection")
}
if d.HasChange("connect_bandwidth") {
update = true
request["ConnectBandwidth"] = d.Get("connect_bandwidth")
}
if !d.IsNewResource() && d.HasChange("service_description") {
update = true
request["ServiceDescription"] = d.Get("service_description")
}
if update {
if _, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = d.Get("dry_run")
}
action := "UpdateVpcEndpointServiceAttribute"
conn, err := client.NewPrivatelinkClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"EndpointServiceLocked", "EndpointServiceOperationDenied"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudPrivatelinkVpcEndpointServiceRead(d, meta)
}
func resourceAlicloudPrivatelinkVpcEndpointServiceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteVpcEndpointService"
var response map[string]interface{}
conn, err := client.NewPrivatelinkClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ServiceId": d.Id(),
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"EndpointServiceConnectionDependence"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EndpointServiceNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudPrivatelinkVpcEndpointServiceResource() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudPrivatelinkVpcEndpointServiceResourceCreate,
Read: resourceAlicloudPrivatelinkVpcEndpointServiceResourceRead,
Update: resourceAlicloudPrivatelinkVpcEndpointServiceResourceUpdate,
Delete: resourceAlicloudPrivatelinkVpcEndpointServiceResourceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(4 * time.Minute),
},
Schema: map[string]*schema.Schema{
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"resource_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"resource_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"service_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudPrivatelinkVpcEndpointServiceResourceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AttachResourceToVpcEndpointService"
request := make(map[string]interface{})
conn, err := client.NewPrivatelinkClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["RegionId"] = client.RegionId
request["ResourceId"] = d.Get("resource_id")
request["ResourceType"] = d.Get("resource_type")
request["ServiceId"] = d.Get("service_id")
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"EndpointServiceOperationDenied"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_privatelink_vpc_endpoint_service_resource", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["ServiceId"], ":", request["ResourceId"]))
return resourceAlicloudPrivatelinkVpcEndpointServiceResourceRead(d, meta)
}
func resourceAlicloudPrivatelinkVpcEndpointServiceResourceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
privatelinkService := PrivatelinkService{client}
object, err := privatelinkService.DescribePrivatelinkVpcEndpointServiceResource(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_privatelink_vpc_endpoint_service_resource privatelinkService.DescribePrivatelinkVpcEndpointServiceResource Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("resource_id", parts[1])
d.Set("service_id", parts[0])
d.Set("resource_type", object["ResourceType"])
return nil
}
func resourceAlicloudPrivatelinkVpcEndpointServiceResourceUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return resourceAlicloudPrivatelinkVpcEndpointServiceResourceRead(d, meta)
}
func resourceAlicloudPrivatelinkVpcEndpointServiceResourceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DetachResourceFromVpcEndpointService"
var response map[string]interface{}
conn, err := client.NewPrivatelinkClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ResourceId": parts[1],
"ServiceId": parts[0],
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["RegionId"] = client.RegionId
request["ResourceType"] = d.Get("resource_type")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EndpointServiceNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudPrivatelinkVpcEndpointServiceUser() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudPrivatelinkVpcEndpointServiceUserCreate,
Read: resourceAlicloudPrivatelinkVpcEndpointServiceUserRead,
Update: resourceAlicloudPrivatelinkVpcEndpointServiceUserUpdate,
Delete: resourceAlicloudPrivatelinkVpcEndpointServiceUserDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"service_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"user_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudPrivatelinkVpcEndpointServiceUserCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AddUserToVpcEndpointService"
request := make(map[string]interface{})
conn, err := client.NewPrivatelinkClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["RegionId"] = client.RegionId
request["ServiceId"] = d.Get("service_id")
request["UserId"] = d.Get("user_id")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("AddUserToVpcEndpointService")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_privatelink_vpc_endpoint_service_user", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetId(fmt.Sprint(request["ServiceId"], ":", request["UserId"]))
return resourceAlicloudPrivatelinkVpcEndpointServiceUserRead(d, meta)
}
func resourceAlicloudPrivatelinkVpcEndpointServiceUserRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
privatelinkService := PrivatelinkService{client}
_, err := privatelinkService.DescribePrivatelinkVpcEndpointServiceUser(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_privatelink_vpc_endpoint_service_user privatelinkService.DescribePrivatelinkVpcEndpointServiceUser Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("service_id", parts[0])
d.Set("user_id", parts[1])
return nil
}
func resourceAlicloudPrivatelinkVpcEndpointServiceUserUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return resourceAlicloudPrivatelinkVpcEndpointServiceUserRead(d, meta)
}
func resourceAlicloudPrivatelinkVpcEndpointServiceUserDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "RemoveUserFromVpcEndpointService"
var response map[string]interface{}
conn, err := client.NewPrivatelinkClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ServiceId": parts[0],
"UserId": parts[1],
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EndpointServiceNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudPrivatelinkVpcEndpointZone() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudPrivatelinkVpcEndpointZoneCreate,
Read: resourceAlicloudPrivatelinkVpcEndpointZoneRead,
Update: resourceAlicloudPrivatelinkVpcEndpointZoneUpdate,
Delete: resourceAlicloudPrivatelinkVpcEndpointZoneDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(6 * time.Minute),
Delete: schema.DefaultTimeout(4 * time.Minute),
},
Schema: map[string]*schema.Schema{
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"endpoint_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudPrivatelinkVpcEndpointZoneCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
privatelinkService := PrivatelinkService{client}
var response map[string]interface{}
action := "AddZoneToVpcEndpoint"
request := make(map[string]interface{})
conn, err := client.NewPrivatelinkClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["EndpointId"] = d.Get("endpoint_id")
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("zone_id"); ok {
request["ZoneId"] = v
}
vswitchId := Trim(d.Get("vswitch_id").(string))
if vswitchId != "" {
vpcService := VpcService{client}
vsw, err := vpcService.DescribeVSwitch(vswitchId)
if err != nil {
return WrapError(err)
}
request["VSwitchId"] = vswitchId
if request["ZoneId"] == nil {
request["ZoneId"] = vsw.ZoneId
}
}
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"EndpointConnectionOperationDenied", "EndpointLocked", "EndpointOperationDenied"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_privatelink_vpc_endpoint_zone", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["EndpointId"], ":", request["ZoneId"]))
stateConf := BuildStateConf([]string{}, []string{"Wait", "Connected"}, d.Timeout(schema.TimeoutCreate), 60*time.Second, privatelinkService.PrivatelinkVpcEndpointZoneStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudPrivatelinkVpcEndpointZoneRead(d, meta)
}
func resourceAlicloudPrivatelinkVpcEndpointZoneRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
privatelinkService := PrivatelinkService{client}
object, err := privatelinkService.DescribePrivatelinkVpcEndpointZone(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_privatelink_vpc_endpoint_zone privatelinkService.DescribePrivatelinkVpcEndpointZone Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("endpoint_id", parts[0])
d.Set("zone_id", parts[1])
d.Set("status", object["ZoneStatus"])
d.Set("vswitch_id", object["VSwitchId"])
return nil
}
func resourceAlicloudPrivatelinkVpcEndpointZoneUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return resourceAlicloudPrivatelinkVpcEndpointZoneRead(d, meta)
}
func resourceAlicloudPrivatelinkVpcEndpointZoneDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "RemoveZoneFromVpcEndpoint"
var response map[string]interface{}
conn, err := client.NewPrivatelinkClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"EndpointId": parts[0],
"ZoneId": parts[1],
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"EndpointConnectionOperationDenied", "EndpointLocked", "EndpointOperationDenied"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EndpointZoneNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudPvtzEndpoint() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudPvtzEndpointCreate,
Read: resourceAlicloudPvtzEndpointRead,
Update: resourceAlicloudPvtzEndpointUpdate,
Delete: resourceAlicloudPvtzEndpointDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"endpoint_name": {
Type: schema.TypeString,
Required: true,
},
"ip_configs": {
Type: schema.TypeSet,
Required: true,
MaxItems: 6,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"zone_id": {
Type: schema.TypeString,
Required: true,
},
"cidr_block": {
Type: schema.TypeString,
Required: true,
},
"ip": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"security_group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"vpc_region_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudPvtzEndpointCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AddResolverEndpoint"
request := make(map[string]interface{})
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
request["Name"] = d.Get("endpoint_name")
for k, ipConfig := range d.Get("ip_configs").(*schema.Set).List() {
ipConfigArg := ipConfig.(map[string]interface{})
request[fmt.Sprintf("IpConfig.%d.VSwitchId", k+1)] = ipConfigArg["vswitch_id"]
request[fmt.Sprintf("IpConfig.%d.AzId", k+1)] = ipConfigArg["zone_id"]
request[fmt.Sprintf("IpConfig.%d.CidrBlock", k+1)] = ipConfigArg["cidr_block"]
request[fmt.Sprintf("IpConfig.%d.Ip", k+1)] = ipConfigArg["ip"]
}
request["Lang"] = "en"
request["SecurityGroupId"] = d.Get("security_group_id")
request["VpcId"] = d.Get("vpc_id")
request["VpcRegionId"] = d.Get("vpc_region_id")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_pvtz_endpoint", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["EndpointId"]))
pvtzService := PvtzService{client}
stateConf := BuildStateConf([]string{}, []string{"SUCCESS"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, pvtzService.PvtzEndpointStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudPvtzEndpointRead(d, meta)
}
func resourceAlicloudPvtzEndpointRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
pvtzService := PvtzService{client}
object, err := pvtzService.DescribePvtzEndpoint(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_pvtz_endpoint pvtzService.DescribePvtzEndpoint Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("endpoint_name", object["Name"])
ipConfigsSli := make([]map[string]interface{}, 0)
if ipConfigs, ok := object["IpConfigs"].([]interface{}); ok {
for _, ipConfigArgs := range ipConfigs {
ipConfigArg := ipConfigArgs.(map[string]interface{})
ipConfigsMap := make(map[string]interface{})
ipConfigsMap["zone_id"] = ipConfigArg["AzId"]
ipConfigsMap["cidr_block"] = ipConfigArg["CidrBlock"]
ipConfigsMap["ip"] = ipConfigArg["Ip"]
ipConfigsMap["vswitch_id"] = ipConfigArg["VSwitchId"]
ipConfigsSli = append(ipConfigsSli, ipConfigsMap)
}
}
d.Set("ip_configs", ipConfigsSli)
d.Set("security_group_id", object["SecurityGroupId"])
d.Set("status", object["Status"])
d.Set("vpc_id", object["VpcId"])
d.Set("vpc_region_id", object["VpcRegionId"])
return nil
}
func resourceAlicloudPvtzEndpointUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
request := map[string]interface{}{
"EndpointId": d.Id(),
}
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
update := false
if d.HasChange("endpoint_name") {
update = true
if v, ok := d.GetOk("endpoint_name"); ok {
request["Name"] = v
}
}
if d.HasChange("ip_configs") {
update = true
for k, ipConfig := range d.Get("ip_configs").(*schema.Set).List() {
ipConfigArg := ipConfig.(map[string]interface{})
request[fmt.Sprintf("IpConfig.%d.VSwitchId", k+1)] = ipConfigArg["vswitch_id"]
request[fmt.Sprintf("IpConfig.%d.AzId", k+1)] = ipConfigArg["zone_id"]
request[fmt.Sprintf("IpConfig.%d.CidrBlock", k+1)] = ipConfigArg["cidr_block"]
request[fmt.Sprintf("IpConfig.%d.Ip", k+1)] = ipConfigArg["ip"]
}
}
request["Lang"] = "en"
if update {
action := "UpdateResolverEndpoint"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
pvtzService := PvtzService{client}
stateConf := BuildStateConf([]string{}, []string{"SUCCESS"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, pvtzService.PvtzEndpointStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudPvtzEndpointRead(d, meta)
}
func resourceAlicloudPvtzEndpointDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteResolverEndpoint"
var response map[string]interface{}
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"EndpointId": d.Id(),
}
request["Lang"] = "en"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ResolverEndpoint.NotExists"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudPvtzRule() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudPvtzRuleCreate,
Read: resourceAlicloudPvtzRuleRead,
Update: resourceAlicloudPvtzRuleUpdate,
Delete: resourceAlicloudPvtzRuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"endpoint_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"forward_ips": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ip": {
Type: schema.TypeString,
Required: true,
},
"port": {
Type: schema.TypeInt,
Required: true,
},
},
},
},
"rule_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"OUTBOUND"}, false),
},
"zone_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudPvtzRuleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AddResolverRule"
request := make(map[string]interface{})
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
request["EndpointId"] = d.Get("endpoint_id")
request["Lang"] = "en"
request["Name"] = d.Get("rule_name")
if v, ok := d.GetOk("type"); ok {
request["Type"] = v
}
for k, forwardConfig := range d.Get("forward_ips").(*schema.Set).List() {
forwardConfigArg := forwardConfig.(map[string]interface{})
request[fmt.Sprintf("ForwardIp.%d.Port", k+1)] = forwardConfigArg["port"]
request[fmt.Sprintf("ForwardIp.%d.Ip", k+1)] = forwardConfigArg["ip"]
}
request["ZoneName"] = d.Get("zone_name")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_pvtz_rule", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["RuleId"]))
return resourceAlicloudPvtzRuleRead(d, meta)
}
func resourceAlicloudPvtzRuleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
pvtzService := PvtzService{client}
object, err := pvtzService.DescribePvtzRule(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_pvtz_rule pvtzService.DescribePvtzRule Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("endpoint_id", object["EndpointId"])
d.Set("rule_name", object["Name"])
forwardConfigsSli := make([]map[string]interface{}, 0)
if forwardConfigs, ok := object["ForwardIps"].([]interface{}); ok {
for _, forwardConfigArgs := range forwardConfigs {
forwardConfigArg := forwardConfigArgs.(map[string]interface{})
forwardConfigsMap := make(map[string]interface{})
forwardConfigsMap["ip"] = forwardConfigArg["Ip"]
forwardConfigsMap["port"] = formatInt(forwardConfigArg["Port"])
forwardConfigsSli = append(forwardConfigsSli, forwardConfigsMap)
}
}
d.Set("forward_ips", forwardConfigsSli)
d.Set("type", object["Type"])
d.Set("zone_name", object["ZoneName"])
return nil
}
func resourceAlicloudPvtzRuleUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"RuleId": d.Id(),
}
if d.HasChange("rule_name") {
update = true
request["Name"] = d.Get("rule_name")
}
if d.HasChange("forward_ips") {
update = true
for k, forwardConfig := range d.Get("forward_ips").(*schema.Set).List() {
forwardConfigArg := forwardConfig.(map[string]interface{})
request[fmt.Sprintf("ForwardIp.%d.Port", k+1)] = forwardConfigArg["port"]
request[fmt.Sprintf("ForwardIp.%d.Ip", k+1)] = forwardConfigArg["ip"]
}
}
if update {
request["Lang"] = "en"
action := "UpdateResolverRule"
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudPvtzRuleRead(d, meta)
}
func resourceAlicloudPvtzRuleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteResolverRule"
var response map[string]interface{}
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"RuleId": d.Id(),
}
request["Lang"] = "en"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ResolverRule.NotExists"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudPvtzRuleAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudPvtzRuleAttachmentCreate,
Read: resourceAlicloudPvtzRuleAttachmentRead,
Update: resourceAlicloudPvtzRuleAttachmentUpdate,
Delete: resourceAlicloudPvtzRuleAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"rule_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"vpcs": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"region_id": {
Type: schema.TypeString,
Required: true,
},
"vpc_id": {
Type: schema.TypeString,
Required: true,
},
},
},
},
},
}
}
func resourceAlicloudPvtzRuleAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "BindResolverRuleVpc"
request := make(map[string]interface{})
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
request["Lang"] = "en"
request["RuleId"] = d.Get("rule_id")
for k, vpcConfig := range d.Get("vpcs").(*schema.Set).List() {
vpcConfigArg := vpcConfig.(map[string]interface{})
request[fmt.Sprintf("Vpc.%d.VpcId", k+1)] = vpcConfigArg["vpc_id"]
request[fmt.Sprintf("Vpc.%d.RegionId", k+1)] = vpcConfigArg["region_id"]
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_pvtz_rule_attachment", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["RuleId"]))
return resourceAlicloudPvtzRuleAttachmentRead(d, meta)
}
func resourceAlicloudPvtzRuleAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
pvtzService := PvtzService{client}
object, err := pvtzService.DescribePvtzRuleAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_pvtz_rule_attachment pvtzService.DescribePvtzRuleAttachment Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
vpcsSli := make([]map[string]interface{}, 0)
if vpcs, ok := object["BindVpcs"].([]interface{}); ok {
for _, vpcConfigArgs := range vpcs {
vpcConfigArg := vpcConfigArgs.(map[string]interface{})
vpcsMap := make(map[string]interface{})
vpcsMap["region_id"] = vpcConfigArg["RegionId"]
vpcsMap["vpc_id"] = vpcConfigArg["VpcId"]
vpcsSli = append(vpcsSli, vpcsMap)
}
}
d.Set("vpcs", vpcsSli)
d.Set("rule_id", d.Id())
return nil
}
func resourceAlicloudPvtzRuleAttachmentUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"RuleId": d.Id(),
}
request["RegionId"] = client.RegionId
if d.HasChange("vpcs") {
update = true
for k, vpcConfig := range d.Get("vpcs").(*schema.Set).List() {
vpcConfigArg := vpcConfig.(map[string]interface{})
request[fmt.Sprintf("Vpc.%d.VpcId", k+1)] = vpcConfigArg["vpc_id"]
request[fmt.Sprintf("Vpc.%d.RegionId", k+1)] = vpcConfigArg["region_id"]
}
}
if update {
request["Lang"] = "en"
action := "BindResolverRuleVpc"
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudPvtzRuleAttachmentRead(d, meta)
}
func resourceAlicloudPvtzRuleAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "BindResolverRuleVpc"
var response map[string]interface{}
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"RuleId": d.Id(),
}
request["Lang"] = "en"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ResolverRule.NotExists"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudPvtzUserVpcAuthorization() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudPvtzUserVpcAuthorizationCreate,
Read: resourceAlicloudPvtzUserVpcAuthorizationRead,
Update: resourceAlicloudPvtzUserVpcAuthorizationUpdate,
Delete: resourceAlicloudPvtzUserVpcAuthorizationDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(2 * time.Minute),
Delete: schema.DefaultTimeout(2 * time.Minute),
},
Schema: map[string]*schema.Schema{
"auth_channel": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"RESOURCE_DIRECTORY"}, false),
},
"auth_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"NORMAL", "CLOUD_PRODUCT"}, false),
},
"authorized_user_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudPvtzUserVpcAuthorizationCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AddUserVpcAuthorization"
request := make(map[string]interface{})
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("auth_channel"); ok {
request["AuthChannel"] = v
}
if v, ok := d.GetOk("auth_type"); ok {
request["AuthType"] = v
}
request["AuthorizedUserId"] = d.Get("authorized_user_id")
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"System.Busy"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_pvtz_user_vpc_authorization", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["AuthorizedUserId"], ":", request["AuthType"]))
return resourceAlicloudPvtzUserVpcAuthorizationRead(d, meta)
}
func resourceAlicloudPvtzUserVpcAuthorizationRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
pvtzService := PvtzService{client}
_, err := pvtzService.DescribePvtzUserVpcAuthorization(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_pvtz_user_vpc_authorization pvtzService.DescribePvtzUserVpcAuthorization Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("auth_type", parts[1])
d.Set("authorized_user_id", parts[0])
return nil
}
func resourceAlicloudPvtzUserVpcAuthorizationUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return resourceAlicloudPvtzUserVpcAuthorizationRead(d, meta)
}
func resourceAlicloudPvtzUserVpcAuthorizationDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteUserVpcAuthorization"
var response map[string]interface{}
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AuthType": parts[1],
"AuthorizedUserId": parts[0],
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"System.Busy"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ZoneVpc.Auth.NotExists"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudPvtzZone() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudPvtzZoneCreate,
Read: resourceAlicloudPvtzZoneRead,
Update: resourceAlicloudPvtzZoneUpdate,
Delete: resourceAlicloudPvtzZoneDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
Delete: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"is_ptr": {
Type: schema.TypeBool,
Computed: true,
},
"lang": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"en", "jp", "zh"}, false),
},
"proxy_pattern": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"RECORD", "ZONE"}, false),
Default: "ZONE",
},
"record_count": {
Type: schema.TypeInt,
Computed: true,
},
"remark": {
Type: schema.TypeString,
Optional: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"user_client_ip": {
Type: schema.TypeString,
Optional: true,
},
"zone_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"name"},
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Deprecated: "Field 'name' has been deprecated from version 1.107.0. Use 'zone_name' instead.",
ConflictsWith: []string{"zone_name"},
},
"creation_time": {
Type: schema.TypeString,
Computed: true,
Removed: "Field 'creation_time' has been removed from provider version 1.107.0",
},
"update_time": {
Type: schema.TypeString,
Computed: true,
Removed: "Field 'update_time' has been removed from provider version 1.107.0",
},
"user_info": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"user_id": {
Type: schema.TypeString,
Optional: true,
},
"region_ids": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"sync_status": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"ON", "OFF"}, false),
},
},
}
}
func resourceAlicloudPvtzZoneCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AddZone"
request := make(map[string]interface{})
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
if v, ok := d.GetOk("proxy_pattern"); ok {
request["ProxyPattern"] = v
}
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("user_client_ip"); ok {
request["UserClientIp"] = v
}
if v, ok := d.GetOk("zone_name"); ok {
request["ZoneName"] = v
} else if v, ok := d.GetOk("name"); ok {
request["ZoneName"] = v
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ServiceUnavailable", "System.Busy", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_pvtz_zone", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["ZoneId"]))
return resourceAlicloudPvtzZoneUpdate(d, meta)
}
func resourceAlicloudPvtzZoneRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
pvtzService := PvtzService{client}
object, err := pvtzService.DescribePvtzZone(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_private_zone_zone pvtzService.DescribePvtzZone Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("is_ptr", object["IsPtr"])
d.Set("proxy_pattern", object["ProxyPattern"])
d.Set("record_count", formatInt(object["RecordCount"]))
d.Set("remark", object["Remark"])
d.Set("zone_name", object["ZoneName"])
d.Set("name", object["ZoneName"])
if v, ok := object["SyncHostTask"]; ok && v != nil {
syncObject := v.(map[string]interface{})
syncArray := make([]map[string]interface{}, 0)
for _, raw := range syncObject["EcsRegions"].(map[string]interface{})["EcsRegion"].([]interface{}) {
obj := raw.(map[string]interface{})
user := make(map[string]interface{}, 0)
user["user_id"] = obj["UserId"]
regions := make([]interface{}, 0)
for _, region := range obj["RegionIds"].(map[string]interface{})["RegionId"].([]interface{}) {
regions = append(regions, region)
}
user["region_ids"] = regions
syncArray = append(syncArray, user)
}
d.Set("user_info", syncArray)
d.Set("sync_status", syncObject["Status"])
}
return nil
}
func resourceAlicloudPvtzZoneUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
pvtzService := PvtzService{client}
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"ZoneId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("proxy_pattern") {
update = true
}
request["ProxyPattern"] = d.Get("proxy_pattern")
if update {
if _, ok := d.GetOk("lang"); ok {
request["Lang"] = d.Get("lang")
}
if _, ok := d.GetOk("user_client_ip"); ok {
request["UserClientIp"] = d.Get("user_client_ip")
}
action := "SetProxyPattern"
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ServiceUnavailable", "System.Busy", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("proxy_pattern")
}
update = false
updateZoneRemarkReq := map[string]interface{}{
"ZoneId": d.Id(),
}
if d.HasChange("remark") {
update = true
updateZoneRemarkReq["Remark"] = d.Get("remark")
}
if update {
if _, ok := d.GetOk("lang"); ok {
updateZoneRemarkReq["Lang"] = d.Get("lang")
}
if _, ok := d.GetOk("user_client_ip"); ok {
updateZoneRemarkReq["UserClientIp"] = d.Get("user_client_ip")
}
action := "UpdateZoneRemark"
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, updateZoneRemarkReq, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ServiceUnavailable", "System.Busy", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("remark")
}
update = false
UpdateSyncEcsHostTaskReq := map[string]interface{}{
"ZoneId": d.Id(),
}
if d.HasChange("sync_status") || d.HasChange("user_info") {
update = true
}
if v, ok := d.GetOk("sync_status"); ok {
UpdateSyncEcsHostTaskReq["Status"] = v
}
if v, ok := d.GetOk("user_info"); ok {
for _, raw := range v.(*schema.Set).List() {
obj := raw.(map[string]interface{})
for index, val := range obj["region_ids"].(*schema.Set).List() {
UpdateSyncEcsHostTaskReq[fmt.Sprintf("Region.%d.UserId", index+1)] = obj["user_id"]
UpdateSyncEcsHostTaskReq[fmt.Sprintf("Region.%d.RegionId", index+1)] = val
}
}
}
if update {
if _, ok := d.GetOk("lang"); ok {
updateZoneRemarkReq["Lang"] = d.Get("lang")
}
if _, ok := d.GetOk("user_info"); !ok {
object, err := pvtzService.DescribePvtzZone(d.Id())
if err != nil {
return WrapError(err)
}
if v, ok := object["SyncHostTask"]; ok && v != nil {
syncObject := v.(map[string]interface{})
for _, raw := range syncObject["EcsRegions"].(map[string]interface{})["EcsRegion"].([]interface{}) {
obj := raw.(map[string]interface{})
for index, region := range obj["RegionIds"].(map[string]interface{})["RegionId"].([]interface{}) {
UpdateSyncEcsHostTaskReq[fmt.Sprintf("Region.%d.UserId", index+1)] = obj["user_id"]
UpdateSyncEcsHostTaskReq[fmt.Sprintf("Region.%d.RegionId", index+1)] = region
}
}
}
}
action := "UpdateSyncEcsHostTask"
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, UpdateSyncEcsHostTaskReq, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"MissingRegion"}) {
log.Printf("[DEBUG] Resource alicloud_private_zone_zone UpdateSyncEcsHostTask Missed Region!!! %s", err)
return nil
}
if IsExpectedErrors(err, []string{"ServiceUnavailable", "System.Busy", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("sync_status")
d.SetPartial("user_info")
}
d.Partial(false)
return resourceAlicloudPvtzZoneRead(d, meta)
}
func resourceAlicloudPvtzZoneDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteZone"
var response map[string]interface{}
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ZoneId": d.Id(),
}
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
if v, ok := d.GetOk("user_client_ip"); ok {
request["UserClientIp"] = v
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"System.Busy", "Throttling.User", "Zone.VpcExists"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"Zone.Invalid.Id", "Zone.Invalid.UserId", "Zone.NotExists", "ZoneVpc.NotExists.VpcId"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudPvtzZoneAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudPvtzZoneAttachmentCreate,
Read: resourceAlicloudPvtzZoneAttachmentRead,
Update: resourceAlicloudPvtzZoneAttachmentUpdate,
Delete: resourceAlicloudPvtzZoneAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
CustomizeDiff: func(d *schema.ResourceDiff, v interface{}) error {
if d.HasChange("vpcs") {
d.SetNewComputed("vpc_ids")
} else if d.HasChange("vpc_ids") {
d.SetNewComputed("vpcs")
}
return nil
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
Update: schema.DefaultTimeout(5 * time.Minute),
Delete: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"lang": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"user_client_ip": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vpcs": {
Type: schema.TypeSet,
Computed: true,
ConflictsWith: []string{"vpc_ids"},
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"region_id": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"vpc_id": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"zone_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"vpc_ids": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
ConflictsWith: []string{"vpcs"},
Elem: &schema.Schema{Type: schema.TypeString},
},
},
}
}
func resourceAlicloudPvtzZoneAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "BindZoneVpc"
request := make(map[string]interface{})
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
if v, ok := d.GetOk("user_client_ip"); ok {
request["UserClientIp"] = v
}
vpcIdMap := make(map[string]string)
if v, ok := d.GetOk("vpcs"); ok {
vpcs := make([]map[string]interface{}, len(v.(*schema.Set).List()))
for i, j := range v.(*schema.Set).List() {
vpcs[i] = make(map[string]interface{})
regionId := j.(map[string]interface{})["region_id"]
if regionId == "" {
regionId = client.RegionId
}
vpcs[i]["RegionId"] = regionId
vpcIdMap[j.(map[string]interface{})["vpc_id"].(string)] = j.(map[string]interface{})["vpc_id"].(string)
vpcs[i]["VpcId"] = j.(map[string]interface{})["vpc_id"]
}
request["Vpcs"] = vpcs
} else {
vpcIds := d.Get("vpc_ids").(*schema.Set).List()
vpcs := make([]map[string]interface{}, len(vpcIds))
for i, j := range vpcIds {
vpcs[i] = make(map[string]interface{})
vpcs[i]["RegionId"] = client.RegionId
vpcs[i]["VpcId"] = j.(string)
vpcIdMap[j.(string)] = j.(string)
}
request["Vpcs"] = vpcs
}
request["ZoneId"] = d.Get("zone_id")
wait := incrementalWait(3*time.Second, 2*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"System.Busy", "Throttling.User", "ServiceUnavailable", "Zone.NotExists"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_pvtz_zone_attachment", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["ZoneId"]))
pvtzService := PvtzService{client}
if err := pvtzService.WaitForZoneAttachment(d.Id(), vpcIdMap, DefaultTimeout); err != nil {
return WrapError(err)
}
return resourceAlicloudPvtzZoneAttachmentRead(d, meta)
}
func resourceAlicloudPvtzZoneAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
pvtzService := PvtzService{client}
object, err := pvtzService.DescribePvtzZoneAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_private_zone_zone_attachment pvtzService.DescribePvtzZoneAttachment Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("zone_id", d.Id())
vpcIds := make([]string, 0)
vpc := make([]map[string]interface{}, 0)
if vpcList, ok := object["BindVpcs"].(map[string]interface{})["Vpc"].([]interface{}); ok {
for _, v := range vpcList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"region_id": m1["RegionId"],
"vpc_id": m1["VpcId"],
}
vpcIds = append(vpcIds, m1["VpcId"].(string))
vpc = append(vpc, temp1)
}
}
}
if err := d.Set("vpcs", vpc); err != nil {
return WrapError(err)
}
if err := d.Set("vpc_ids", vpcIds); err != nil {
return WrapError(err)
}
return nil
}
func resourceAlicloudPvtzZoneAttachmentUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
if d.HasChange("vpcs") || d.HasChange("vpc_ids") {
request := map[string]interface{}{
"ZoneId": d.Id(),
}
vpcIdMap := make(map[string]string)
vpcs := make([]map[string]interface{}, len(d.Get("vpcs").(*schema.Set).List()))
if d.HasChange("vpcs") && len(vpcs) != 0 {
for i, j := range d.Get("vpcs").(*schema.Set).List() {
vpcs[i] = make(map[string]interface{})
regionId := j.(map[string]interface{})["region_id"]
if regionId == "" {
regionId = client.RegionId
}
vpcs[i]["RegionId"] = regionId
vpcs[i]["VpcId"] = j.(map[string]interface{})["vpc_id"]
vpcIdMap[j.(map[string]interface{})["vpc_id"].(string)] = j.(map[string]interface{})["vpc_id"].(string)
}
} else {
vpcs = make([]map[string]interface{}, len(d.Get("vpc_ids").(*schema.Set).List()))
for i, j := range d.Get("vpc_ids").(*schema.Set).List() {
vpcs[i] = make(map[string]interface{})
vpcs[i]["RegionId"] = client.RegionId
vpcs[i]["VpcId"] = j.(string)
vpcIdMap[j.(string)] = j.(string)
}
}
request["Vpcs"] = vpcs
if _, ok := d.GetOk("lang"); ok {
request["Lang"] = d.Get("lang")
}
if _, ok := d.GetOk("user_client_ip"); ok {
request["UserClientIp"] = d.Get("user_client_ip")
}
action := "BindZoneVpc"
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 2*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"System.Busy", "Throttling.User", "ServiceUnavailable", "Zone.NotExists"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
pvtzService := PvtzService{client}
if err := pvtzService.WaitForZoneAttachment(d.Id(), vpcIdMap, DefaultTimeout); err != nil {
return WrapError(err)
}
}
return resourceAlicloudPvtzZoneAttachmentRead(d, meta)
}
func resourceAlicloudPvtzZoneAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "BindZoneVpc"
var response map[string]interface{}
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ZoneId": d.Id(),
}
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
if v, ok := d.GetOk("user_client_ip"); ok {
request["UserClientIp"] = v
}
vpcs := make([]map[string]interface{}, 0)
request["Vpcs"] = vpcs
wait := incrementalWait(3*time.Second, 2*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"System.Busy", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"Zone.NotExists", "ZoneVpc.NotExists.VpcId"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
pvtzService := PvtzService{client}
return WrapError(pvtzService.WaitForPvtzZoneAttachment(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"fmt"
"log"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudPvtzZoneRecord() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudPvtzZoneRecordCreate,
Read: resourceAlicloudPvtzZoneRecordRead,
Update: resourceAlicloudPvtzZoneRecordUpdate,
Delete: resourceAlicloudPvtzZoneRecordDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
Delete: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"lang": {
Type: schema.TypeString,
Optional: true,
},
"priority": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(1, 99),
Default: 1,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("type").(string) != "MX"
},
},
"record_id": {
Type: schema.TypeString,
Computed: true,
},
"remark": {
Type: schema.TypeString,
Optional: true,
},
"rr": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"resource_record"},
},
"resource_record": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Field 'resource_record' has been deprecated from version 1.109.0. Use 'rr' instead.",
ConflictsWith: []string{"rr"},
},
"status": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"DISABLE", "ENABLE"}, false),
Default: "ENABLE",
},
"ttl": {
Type: schema.TypeInt,
Optional: true,
Default: 60,
},
"type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"A", "CNAME", "MX", "PTR", "SRV", "TXT"}, false),
},
"user_client_ip": {
Type: schema.TypeString,
Optional: true,
},
"value": {
Type: schema.TypeString,
Required: true,
},
"zone_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudPvtzZoneRecordCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AddZoneRecord"
request := make(map[string]interface{})
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
if v, ok := d.GetOk("priority"); ok {
request["Priority"] = v
}
if v, ok := d.GetOk("rr"); ok {
request["Rr"] = v
} else if v, ok := d.GetOk("resource_record"); ok {
request["Rr"] = v
} else {
return WrapError(Error(`[ERROR] Argument "resource_record" or "rr" must be set one!`))
}
if v, ok := d.GetOk("ttl"); ok {
request["Ttl"] = v
}
request["Type"] = d.Get("type")
if v, ok := d.GetOk("user_client_ip"); ok {
request["UserClientIp"] = v
}
request["Value"] = d.Get("value")
request["ZoneId"] = d.Get("zone_id")
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ServiceUnavailable", "System.Busy", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_pvtz_zone_record", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["RecordId"], ":", request["ZoneId"]))
return resourceAlicloudPvtzZoneRecordUpdate(d, meta)
}
func resourceAlicloudPvtzZoneRecordRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
pvtzService := PvtzService{client}
object, err := pvtzService.DescribePvtzZoneRecord(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_private_zone_zone_record pvtzService.DescribePvtzZoneRecord Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
if strings.Split(d.Id(), ":")[0] != fmt.Sprint(object["RecordId"]) {
d.SetId(fmt.Sprintf("%v:%v", fmt.Sprint(object["RecordId"]), fmt.Sprint(object["ZoneId"])))
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("record_id", fmt.Sprint(parts[0]))
d.Set("zone_id", parts[1])
d.Set("priority", formatInt(object["Priority"]))
d.Set("remark", object["Remark"])
d.Set("rr", object["Rr"])
d.Set("resource_record", object["Rr"])
d.Set("status", object["Status"])
d.Set("ttl", formatInt(object["Ttl"]))
d.Set("type", object["Type"])
d.Set("value", object["Value"])
return nil
}
func resourceAlicloudPvtzZoneRecordUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
pvtzService := PvtzService{client}
object, err := pvtzService.DescribePvtzZoneRecord(d.Id())
if err != nil {
return WrapError(err)
}
if strings.Split(d.Id(), ":")[0] != fmt.Sprint(object["RecordId"]) {
d.SetId(fmt.Sprintf("%v:%v", fmt.Sprint(object["RecordId"]), fmt.Sprint(object["ZoneId"])))
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Partial(true)
update := false
request := map[string]interface{}{
"RecordId": parts[0],
}
if d.HasChange("remark") {
update = true
request["Remark"] = d.Get("remark")
}
if update {
if _, ok := d.GetOk("lang"); ok {
request["Lang"] = d.Get("lang")
}
action := "UpdateRecordRemark"
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ServiceUnavailable", "System.Busy", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("remark")
}
update = false
setZoneRecordStatusReq := map[string]interface{}{
"RecordId": parts[0],
}
if d.HasChange("status") {
update = true
}
setZoneRecordStatusReq["Status"] = d.Get("status")
if update {
if _, ok := d.GetOk("lang"); ok {
setZoneRecordStatusReq["Lang"] = d.Get("lang")
}
if _, ok := d.GetOk("user_client_ip"); ok {
setZoneRecordStatusReq["UserClientIp"] = d.Get("user_client_ip")
}
action := "SetZoneRecordStatus"
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, setZoneRecordStatusReq, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ServiceUnavailable", "System.Busy", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("status")
}
update = false
updateZoneRecordReq := map[string]interface{}{
"RecordId": parts[0],
}
if !d.IsNewResource() && d.HasChange("rr") {
update = true
updateZoneRecordReq["Rr"] = d.Get("rr")
}
if !d.IsNewResource() && d.HasChange("resource_record") {
update = true
updateZoneRecordReq["Rr"] = d.Get("resource_record")
}
if updateZoneRecordReq["Rr"] == nil {
updateZoneRecordReq["Rr"] = d.Get("rr")
}
if !d.IsNewResource() && d.HasChange("type") {
update = true
}
updateZoneRecordReq["Type"] = d.Get("type")
if !d.IsNewResource() && d.HasChange("value") {
update = true
}
updateZoneRecordReq["Value"] = d.Get("value")
if !d.IsNewResource() && d.HasChange("priority") {
update = true
updateZoneRecordReq["Priority"] = d.Get("priority")
}
if !d.IsNewResource() && d.HasChange("ttl") {
update = true
updateZoneRecordReq["Ttl"] = d.Get("ttl")
}
if update {
if _, ok := d.GetOk("lang"); ok {
updateZoneRecordReq["Lang"] = d.Get("lang")
}
if _, ok := d.GetOk("user_client_ip"); ok {
updateZoneRecordReq["UserClientIp"] = d.Get("user_client_ip")
}
action := "UpdateZoneRecord"
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, updateZoneRecordReq, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ServiceUnavailable", "System.Busy", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("resource_record")
d.SetPartial("rr")
d.SetPartial("type")
d.SetPartial("value")
d.SetPartial("priority")
d.SetPartial("ttl")
}
d.Partial(false)
return resourceAlicloudPvtzZoneRecordRead(d, meta)
}
func resourceAlicloudPvtzZoneRecordDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
pvtzService := PvtzService{client}
object, err := pvtzService.DescribePvtzZoneRecord(d.Id())
if err != nil {
return WrapError(err)
}
if strings.Split(d.Id(), ":")[0] != fmt.Sprint(object["RecordId"]) {
d.SetId(fmt.Sprintf("%v:%v", fmt.Sprint(object["RecordId"]), fmt.Sprint(object["ZoneId"])))
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteZoneRecord"
var response map[string]interface{}
conn, err := client.NewPvtzClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"RecordId": parts[0],
}
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
if v, ok := d.GetOk("user_client_ip"); ok {
request["UserClientIp"] = v
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"System.Busy", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Zone.Invalid.Id", "Zone.Invalid.UserId", "Zone.NotExists", "ZoneVpc.NotExists.VpcId"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudQuickBiUser() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudQuickBiUserCreate,
Read: resourceAlicloudQuickBiUserRead,
Update: resourceAlicloudQuickBiUserUpdate,
Delete: resourceAlicloudQuickBiUserDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"account_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"account_name": {
Type: schema.TypeString,
Required: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
parts := strings.Split(new, ":")
if len(parts) < 2 {
return false
}
return parts[1] == old
},
},
"admin_user": {
Type: schema.TypeBool,
Required: true,
},
"auth_admin_user": {
Type: schema.TypeBool,
Required: true,
},
"nick_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"user_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"Analyst", "Developer", "Visitor"}, false),
},
},
}
}
func resourceAlicloudQuickBiUserCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AddUser"
request := make(map[string]interface{})
conn, err := client.NewQuickbiClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("account_id"); ok {
request["AccountId"] = v
}
request["AccountName"] = d.Get("account_name")
request["AdminUser"] = d.Get("admin_user")
request["AuthAdminUser"] = d.Get("auth_admin_user")
request["NickName"] = d.Get("nick_name")
request["UserType"] = convertQuickBiUserUserTypeRequest(d.Get("user_type").(string))
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-08-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_quick_bi_user", action, AlibabaCloudSdkGoERROR)
}
responseResult := response["Result"].(map[string]interface{})
d.SetId(fmt.Sprint(responseResult["UserId"]))
return resourceAlicloudQuickBiUserRead(d, meta)
}
func resourceAlicloudQuickBiUserRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
quickbiPublicService := QuickbiPublicService{client}
object, err := quickbiPublicService.DescribeQuickBiUser(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_quick_bi_user quickbiPublicService.DescribeQuickBiUser Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("account_id", object["AccountId"])
d.Set("account_name", object["AccountName"])
d.Set("admin_user", object["AdminUser"])
d.Set("auth_admin_user", object["AuthAdminUser"])
d.Set("nick_name", object["NickName"])
d.Set("user_type", convertQuickBiUserUserTypeResponse(formatInt(object["UserType"])))
return nil
}
func resourceAlicloudQuickBiUserUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"UserId": d.Id(),
}
if d.HasChange("admin_user") || d.IsNewResource() {
update = true
}
request["AdminUser"] = d.Get("admin_user")
if d.HasChange("auth_admin_user") || d.IsNewResource() {
update = true
}
request["AuthAdminUser"] = d.Get("auth_admin_user")
request["NickName"] = d.Get("nick_name")
if d.HasChange("user_type") {
update = true
}
request["UserType"] = convertQuickBiUserUserTypeRequest(d.Get("user_type").(string))
if update {
action := "UpdateUser"
conn, err := client.NewQuickbiClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-08-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudQuickBiUserRead(d, meta)
}
func resourceAlicloudQuickBiUserDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteUser"
var response map[string]interface{}
conn, err := client.NewQuickbiClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"UserId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-08-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"User.Not.In.Organization"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func convertQuickBiUserUserTypeRequest(source interface{}) interface{} {
switch source {
case "Analyst":
return 3
case "Developer":
return 1
case "Visitor":
return 2
}
return 0
}
func convertQuickBiUserUserTypeResponse(source interface{}) interface{} {
switch source {
case 3:
return "Analyst"
case 1:
return "Developer"
case 2:
return "Visitor"
}
return ""
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudQuotasQuotaAlarm() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudQuotasQuotaAlarmCreate,
Read: resourceAlicloudQuotasQuotaAlarmRead,
Update: resourceAlicloudQuotasQuotaAlarmUpdate,
Delete: resourceAlicloudQuotasQuotaAlarmDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"product_code": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"quota_action_code": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"quota_alarm_name": {
Type: schema.TypeString,
Required: true,
},
"quota_dimensions": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"value": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
},
ForceNew: true,
},
"threshold": {
Type: schema.TypeFloat,
Optional: true,
},
"threshold_percent": {
Type: schema.TypeFloat,
Optional: true,
},
"web_hook": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudQuotasQuotaAlarmCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateQuotaAlarm"
request := make(map[string]interface{})
conn, err := client.NewQuotasClient()
if err != nil {
return WrapError(err)
}
request["SourceIp"] = client.SourceIp
request["ProductCode"] = d.Get("product_code")
request["QuotaActionCode"] = d.Get("quota_action_code")
request["AlarmName"] = d.Get("quota_alarm_name")
if v, ok := d.GetOk("quota_dimensions"); ok {
quotaDimensionsMaps := make([]map[string]interface{}, 0)
for _, quotaDimensions := range v.(*schema.Set).List() {
quotaDimensionsMap := make(map[string]interface{})
quotaDimensionsArg := quotaDimensions.(map[string]interface{})
quotaDimensionsMap["Key"] = quotaDimensionsArg["key"]
quotaDimensionsMap["Value"] = quotaDimensionsArg["value"]
quotaDimensionsMaps = append(quotaDimensionsMaps, quotaDimensionsMap)
}
request["QuotaDimensions"] = quotaDimensionsMaps
}
if v, ok := d.GetOk("threshold"); ok {
request["Threshold"] = v
}
if v, ok := d.GetOk("threshold_percent"); ok {
request["ThresholdPercent"] = v
}
if v, ok := d.GetOk("web_hook"); ok {
request["WebHook"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-05-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_quotas_quota_alarm", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["AlarmId"]))
return resourceAlicloudQuotasQuotaAlarmRead(d, meta)
}
func resourceAlicloudQuotasQuotaAlarmRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
quotasService := QuotasService{client}
object, err := quotasService.DescribeQuotasQuotaAlarm(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_quotas_quota_alarm quotasService.DescribeQuotasQuotaAlarm Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("product_code", object["ProductCode"])
d.Set("quota_action_code", object["QuotaActionCode"])
d.Set("quota_alarm_name", object["AlarmName"])
quotaDimensionList := make([]map[string]interface{}, 0)
if quotaDimension, ok := object["QuotaDimension"]; ok {
for k, v := range quotaDimension.(map[string]interface{}) {
quotaDimensionMap := make(map[string]interface{})
quotaDimensionMap["key"] = k
quotaDimensionMap["value"] = v
quotaDimensionList = append(quotaDimensionList, quotaDimensionMap)
}
}
if err := d.Set("quota_dimensions", quotaDimensionList); err != nil {
return WrapError(err)
}
d.Set("threshold", object["Threshold"])
d.Set("threshold_percent", object["ThresholdPercent"])
return nil
}
func resourceAlicloudQuotasQuotaAlarmUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"AlarmId": d.Id(),
"SourceIp": client.SourceIp,
}
if d.HasChange("quota_alarm_name") {
update = true
}
request["AlarmName"] = d.Get("quota_alarm_name")
if d.HasChange("threshold") {
update = true
request["Threshold"] = d.Get("threshold")
}
if d.HasChange("threshold_percent") {
update = true
request["ThresholdPercent"] = d.Get("threshold_percent")
}
if d.HasChange("web_hook") {
update = true
request["WebHook"] = d.Get("web_hook")
}
if update {
action := "UpdateQuotaAlarm"
conn, err := client.NewQuotasClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-05-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudQuotasQuotaAlarmRead(d, meta)
}
func resourceAlicloudQuotasQuotaAlarmDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteQuotaAlarm"
var response map[string]interface{}
conn, err := client.NewQuotasClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AlarmId": d.Id(),
"SourceIp": client.SourceIp,
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-05-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudQuotasQuotaApplication() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudQuotasQuotaApplicationCreate,
Read: resourceAlicloudQuotasQuotaApplicationRead,
Delete: resourceAlicloudQuotasQuotaApplicationDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"approve_value": {
Type: schema.TypeString,
Computed: true,
},
"audit_mode": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Async", "Sync"}, false),
Default: "Async",
},
"audit_reason": {
Type: schema.TypeString,
Computed: true,
},
"desire_value": {
Type: schema.TypeFloat,
Required: true,
ForceNew: true,
},
"dimensions": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"value": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
},
},
ForceNew: true,
},
"effective_time": {
Type: schema.TypeString,
Computed: true,
},
"expire_time": {
Type: schema.TypeString,
Computed: true,
},
"notice_type": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IntInSlice([]int{0, 1, 2, 3}),
Default: 0,
},
"product_code": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"quota_action_code": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"quota_category": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"CommonQuota", "FlowControl"}, false),
},
"quota_description": {
Type: schema.TypeString,
Computed: true,
},
"quota_name": {
Type: schema.TypeString,
Computed: true,
},
"quota_unit": {
Type: schema.TypeString,
Computed: true,
},
"reason": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudQuotasQuotaApplicationCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateQuotaApplication"
request := make(map[string]interface{})
conn, err := client.NewQuotasClient()
if err != nil {
return WrapError(err)
}
request["SourceIp"] = client.SourceIp
if v, ok := d.GetOk("audit_mode"); ok {
request["AuditMode"] = v
}
request["DesireValue"] = d.Get("desire_value")
if v, ok := d.GetOk("dimensions"); ok {
dimensionsMaps := make([]map[string]interface{}, 0)
for _, dimensions := range v.(*schema.Set).List() {
dimensionsMap := make(map[string]interface{})
dimensionsArg := dimensions.(map[string]interface{})
dimensionsMap["Key"] = dimensionsArg["key"]
dimensionsMap["Value"] = dimensionsArg["value"]
dimensionsMaps = append(dimensionsMaps, dimensionsMap)
}
request["Dimensions"] = dimensionsMaps
}
if v, ok := d.GetOk("notice_type"); ok {
request["NoticeType"] = v
}
request["ProductCode"] = d.Get("product_code")
request["QuotaActionCode"] = d.Get("quota_action_code")
if v, ok := d.GetOk("quota_category"); ok {
request["QuotaCategory"] = v
}
request["Reason"] = d.Get("reason")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-05-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_quotas_quota_application", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["ApplicationId"]))
return resourceAlicloudQuotasQuotaApplicationRead(d, meta)
}
func resourceAlicloudQuotasQuotaApplicationRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
quotasService := QuotasService{client}
object, err := quotasService.DescribeQuotasQuotaApplication(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_quotas_quota_application quotasService.DescribeQuotasQuotaApplication Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("approve_value", object["ApproveValue"])
d.Set("audit_reason", object["AuditReason"])
d.Set("desire_value", object["DesireValue"])
dimensionList := make([]map[string]interface{}, 0)
if dimension, ok := object["Dimension"]; ok {
for k, v := range dimension.(map[string]interface{}) {
dimensionMap := make(map[string]interface{})
dimensionMap["key"] = k
dimensionMap["value"] = v
dimensionList = append(dimensionList, dimensionMap)
}
}
if err := d.Set("dimensions", dimensionList); err != nil {
return WrapError(err)
}
d.Set("effective_time", object["EffectiveTime"])
d.Set("expire_time", object["ExpireTime"])
d.Set("notice_type", object["NoticeType"])
d.Set("product_code", object["ProductCode"])
d.Set("quota_action_code", object["QuotaActionCode"])
d.Set("quota_description", object["QuotaDescription"])
d.Set("quota_name", object["QuotaName"])
d.Set("quota_unit", object["QuotaUnit"])
d.Set("reason", object["Reason"])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudQuotasQuotaApplicationDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudQuotasQuotaApplication. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
package alicloud
import (
"github.com/aliyun/alibaba-cloud-sdk-go/services/ram"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/encryption"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudRamAccessKey() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRamAccessKeyCreate,
Read: resourceAlicloudRamAccessKeyRead,
Update: resourceAlicloudRamAccessKeyUpdate,
Delete: resourceAlicloudRamAccessKeyDelete,
Schema: map[string]*schema.Schema{
"user_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"secret_file": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
Default: Active,
ValidateFunc: validation.StringInSlice([]string{"Active", "Inactive"}, false),
},
"secret": {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
},
"pgp_key": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
},
"key_fingerprint": {
Type: schema.TypeString,
Computed: true,
},
"encrypted_secret": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudRamAccessKeyCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
request := ram.CreateCreateAccessKeyRequest()
if v, ok := d.GetOk("user_name"); ok && v.(string) != "" {
request.UserName = v.(string)
}
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.CreateAccessKey(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ram_access_key", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ram.CreateAccessKeyResponse)
if v, ok := d.GetOk("pgp_key"); ok {
pgpKey := v.(string)
encryptionKey, err := encryption.RetrieveGPGKey(pgpKey)
if err != nil {
return WrapError(err)
}
fingerprint, encrypted, err := encryption.EncryptValue(encryptionKey, response.AccessKey.AccessKeySecret, "Alicloud RAM Access Key Secret")
if err != nil {
return WrapError(err)
}
d.Set("key_fingerprint", fingerprint)
d.Set("encrypted_secret", encrypted)
} else {
if err := d.Set("secret", response.AccessKey.AccessKeySecret); err != nil {
return WrapError(err)
}
}
if output, ok := d.GetOk("secret_file"); ok && output != nil {
// create a secret_file and write access key to it.
writeToFile(output.(string), response.AccessKey)
}
d.SetId(response.AccessKey.AccessKeyId)
err = ramService.WaitForRamAccessKey(d.Id(), request.UserName, Active, DefaultTimeout)
if err != nil {
return WrapError(err)
}
return resourceAlicloudRamAccessKeyUpdate(d, meta)
}
func resourceAlicloudRamAccessKeyUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ram.CreateUpdateAccessKeyRequest()
request.RegionId = client.RegionId
request.UserAccessKeyId = d.Id()
request.Status = d.Get("status").(string)
if v, ok := d.GetOk("user_name"); ok && v.(string) != "" {
request.UserName = v.(string)
}
if d.HasChange("status") {
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.UpdateAccessKey(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
return resourceAlicloudRamAccessKeyRead(d, meta)
}
func resourceAlicloudRamAccessKeyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramservice := RamService{client}
userName := ""
if v, ok := d.GetOk("user_name"); ok && v.(string) != "" {
userName = v.(string)
}
object, err := ramservice.DescribeRamAccessKey(d.Id(), userName)
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("status", object.Status)
return nil
}
func resourceAlicloudRamAccessKeyDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
request := ram.CreateDeleteAccessKeyRequest()
request.RegionId = client.RegionId
request.UserAccessKeyId = d.Id()
if v, ok := d.GetOk("user_name"); ok && v.(string) != "" {
request.UserName = v.(string)
}
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.DeleteAccessKey(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, request.UserName, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(ramService.WaitForRamAccessKey(d.Id(), request.UserName, Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"github.com/aliyun/alibaba-cloud-sdk-go/services/ram"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudRamAccountAlias() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRamAccountAliasCreate,
Read: resourceAlicloudRamAccountAliasRead,
Delete: resourceAlicloudRamAccountAliasDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"account_alias": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudRamAccountAliasCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ram.CreateSetAccountAliasRequest()
request.RegionId = client.RegionId
request.AccountAlias = d.Get("account_alias").(string)
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.SetAccountAlias(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ram_account_alias", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetId(request.AccountAlias)
return resourceAlicloudRamAccountAliasRead(d, meta)
}
func resourceAlicloudRamAccountAliasRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
object, err := ramService.DescribeRamAccountAlias(d.Id())
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
d.Set("account_alias", object.AccountAlias)
return nil
}
func resourceAlicloudRamAccountAliasDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ram.CreateClearAccountAliasRequest()
request.RegionId = client.RegionId
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.ClearAccountAlias(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}
package alicloud
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ram"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
)
// defaults from API docs https://help.aliyun.com/document_detail/28739.html
// when resource is created it sets not specifies value in the resource block to defaults
// also during deletion it rollbacks changes to defaults (API has only a Set method)
var (
default_minimum_password_length = 12
default_require_lowercase_characters = true
default_require_uppercase_characters = true
default_require_numbers = true
default_require_symbols = true
default_hard_expiry = false
default_max_password_age = 0 // means disable
default_password_reuse_prevention = 0 // means disable
default_max_login_attempts = 5
)
func resourceAlicloudRamAccountPasswordPolicy() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRamAccountPasswordPolicyUpdate,
Read: resourceAlicloudRamAccountPasswordPolicyRead,
Update: resourceAlicloudRamAccountPasswordPolicyUpdate,
Delete: resourceAlicloudRamAccountPasswordPolicyDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"minimum_password_length": {
Type: schema.TypeInt,
Optional: true,
Default: default_minimum_password_length,
ValidateFunc: intBetween(8, 32),
},
"require_lowercase_characters": {
Type: schema.TypeBool,
Optional: true,
Default: default_require_lowercase_characters,
},
"require_uppercase_characters": {
Type: schema.TypeBool,
Optional: true,
Default: default_require_uppercase_characters,
},
"require_numbers": {
Type: schema.TypeBool,
Optional: true,
Default: default_require_numbers,
},
"require_symbols": {
Type: schema.TypeBool,
Optional: true,
Default: default_require_symbols,
},
"hard_expiry": {
Type: schema.TypeBool,
Optional: true,
Default: default_hard_expiry,
},
"max_password_age": {
Type: schema.TypeInt,
Optional: true,
Default: default_max_password_age,
ValidateFunc: intBetween(0, 1095),
},
"password_reuse_prevention": {
Type: schema.TypeInt,
Optional: true,
Default: default_password_reuse_prevention,
ValidateFunc: intBetween(0, 24),
},
"max_login_attempts": {
Type: schema.TypeInt,
Optional: true,
Default: default_max_login_attempts,
ValidateFunc: intBetween(0, 32),
},
},
}
}
func resourceAlicloudRamAccountPasswordPolicyUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ram.CreateSetPasswordPolicyRequest()
request.RegionId = client.RegionId
request.MinimumPasswordLength = requests.NewInteger(d.Get("minimum_password_length").(int))
request.RequireLowercaseCharacters = requests.NewBoolean(d.Get("require_lowercase_characters").(bool))
request.RequireUppercaseCharacters = requests.NewBoolean(d.Get("require_uppercase_characters").(bool))
request.RequireNumbers = requests.NewBoolean(d.Get("require_numbers").(bool))
request.RequireSymbols = requests.NewBoolean(d.Get("require_symbols").(bool))
request.MaxLoginAttemps = requests.NewInteger(d.Get("max_login_attempts").(int))
request.HardExpiry = requests.NewBoolean(d.Get("hard_expiry").(bool))
request.MaxPasswordAge = requests.NewInteger(d.Get("max_password_age").(int))
request.PasswordReusePrevention = requests.NewInteger(d.Get("password_reuse_prevention").(int))
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.SetPasswordPolicy(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ram_account_password_policy", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetId("ram-account-password-policy")
return resourceAlicloudRamAccountPasswordPolicyRead(d, meta)
}
func resourceAlicloudRamAccountPasswordPolicyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
object, err := ramService.DescribeRamAccountPasswordPolicy(d.Id())
if err != nil {
return WrapError(err)
}
passwordPolicy := object.PasswordPolicy
d.Set("minimum_password_length", passwordPolicy.MinimumPasswordLength)
d.Set("require_lowercase_characters", passwordPolicy.RequireLowercaseCharacters)
d.Set("require_uppercase_characters", passwordPolicy.RequireUppercaseCharacters)
d.Set("require_numbers", passwordPolicy.RequireNumbers)
d.Set("require_symbols", passwordPolicy.RequireSymbols)
d.Set("hard_expiry", passwordPolicy.HardExpiry)
d.Set("max_password_age", passwordPolicy.MaxPasswordAge)
d.Set("password_reuse_prevention", passwordPolicy.PasswordReusePrevention)
d.Set("max_login_attempts", passwordPolicy.MaxLoginAttemps)
return nil
}
func resourceAlicloudRamAccountPasswordPolicyDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ram.CreateSetPasswordPolicyRequest()
request.RegionId = client.RegionId
request.MinimumPasswordLength = requests.NewInteger(default_minimum_password_length)
request.RequireLowercaseCharacters = requests.NewBoolean(default_require_lowercase_characters)
request.RequireUppercaseCharacters = requests.NewBoolean(default_require_uppercase_characters)
request.RequireNumbers = requests.NewBoolean(default_require_numbers)
request.RequireSymbols = requests.NewBoolean(default_require_symbols)
request.HardExpiry = requests.NewBoolean(default_hard_expiry)
request.MaxPasswordAge = requests.NewInteger(default_max_password_age)
request.PasswordReusePrevention = requests.NewInteger(default_password_reuse_prevention)
request.MaxLoginAttemps = requests.NewInteger(default_max_login_attempts)
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.SetPasswordPolicy(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}
package alicloud
import (
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ram"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudRamGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRamGroupCreate,
Read: resourceAlicloudRamGroupRead,
Update: resourceAlicloudRamGroupUpdate,
Delete: resourceAlicloudRamGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"comments": {
Type: schema.TypeString,
Optional: true,
},
"force": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func resourceAlicloudRamGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramSercvice := RamService{client}
request := ram.CreateCreateGroupRequest()
request.RegionId = client.RegionId
request.GroupName = d.Get("name").(string)
if v, ok := d.GetOk("comments"); ok {
request.Comments = v.(string)
}
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.CreateGroup(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ram_group", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ram.CreateGroupResponse)
d.SetId(response.Group.GroupName)
err = ramSercvice.WaitForRamGroup(d.Id(), Normal, DefaultTimeout)
if err != nil {
return WrapError(err)
}
return resourceAlicloudRamGroupRead(d, meta)
}
func resourceAlicloudRamGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ram.CreateUpdateGroupRequest()
request.RegionId = client.RegionId
request.GroupName = d.Id()
if d.HasChange("comments") {
request.NewComments = d.Get("comments").(string)
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.UpdateGroup(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
return resourceAlicloudRamGroupRead(d, meta)
}
func resourceAlicloudRamGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
object, err := ramService.DescribeRamGroup(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
group := object.Group
d.Set("name", group.GroupName)
d.Set("comments", group.Comments)
return nil
}
func resourceAlicloudRamGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := &RamService{client}
request := ram.CreateListUsersForGroupRequest()
request.RegionId = client.RegionId
request.GroupName = d.Id()
if d.Get("force").(bool) {
// list and delete users which in this group
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.ListUsersForGroup(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
listUserResponse, _ := raw.(*ram.ListUsersForGroupResponse)
users := listUserResponse.Users.User
if len(users) > 0 {
for _, v := range users {
request := ram.CreateRemoveUserFromGroupRequest()
request.UserName = v.UserName
request.GroupName = d.Id()
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.RemoveUserFromGroup(request)
})
if err != nil && !IsExpectedErrors(err, []string{"EntityNotExist"}) {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
}
// list and detach policies which attach this group
request := ram.CreateListPoliciesForGroupRequest()
request.RegionId = client.RegionId
request.GroupName = d.Id()
raw, err = client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.ListPoliciesForGroup(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
listPolicyResponse, _ := raw.(*ram.ListPoliciesForGroupResponse)
policies := listPolicyResponse.Policies.Policy
if len(policies) > 0 {
for _, v := range policies {
request := ram.CreateDetachPolicyFromGroupRequest()
request.RegionId = client.RegionId
request.PolicyType = v.PolicyType
request.PolicyName = v.PolicyName
request.GroupName = d.Id()
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.DetachPolicyFromGroup(request)
})
if err != nil && !IsExpectedErrors(err, []string{"EntityNotExist"}) {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
}
}
deleteGroupRequest := ram.CreateDeleteGroupRequest()
deleteGroupRequest.RegionId = client.RegionId
deleteGroupRequest.GroupName = d.Id()
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.DeleteGroup(deleteGroupRequest)
})
if err != nil {
if IsExpectedErrors(err, []string{"DeleteConflict.Group.User", "DeleteConflict.Group.Policy"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(deleteGroupRequest.GetActionName(), raw, deleteGroupRequest.RpcRequest, deleteGroupRequest)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist.Group"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), deleteGroupRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(ramService.WaitForRamGroup(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"github.com/aliyun/alibaba-cloud-sdk-go/services/ram"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudRamGroupMembership() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRamGroupMembershipCreate,
Read: resourceAlicloudRamGroupMembershipRead,
Update: resourceAlicloudRamGroupMembershipUpdate,
Delete: resourceAlicloudRamGroupMembershipDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"group_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"user_names": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Set: schema.HashString,
},
},
}
}
func resourceAlicloudRamGroupMembershipCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
group := d.Get("group_name").(string)
users := expandStringList(d.Get("user_names").(*schema.Set).List())
err := addUsersToGroup(client, users, group)
if err != nil {
return WrapError(err)
}
d.SetId(group)
return resourceAlicloudRamGroupMembershipRead(d, meta)
}
func resourceAlicloudRamGroupMembershipUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
d.Partial(true)
if d.HasChange("user_names") {
d.SetPartial("user_names")
o, n := d.GetChange("user_names")
if o == nil {
o = new(schema.Set)
}
if n == nil {
n = new(schema.Set)
}
oldSet := o.(*schema.Set)
newSet := n.(*schema.Set)
remove := expandStringList(oldSet.Difference(newSet).List())
add := expandStringList(newSet.Difference(oldSet).List())
group := d.Id()
if err := removeUsersFromGroup(client, remove, group); err != nil {
return WrapError(err)
}
if err := addUsersToGroup(client, add, group); err != nil {
return WrapError(err)
}
}
d.Partial(false)
return resourceAlicloudRamGroupMembershipRead(d, meta)
}
func resourceAlicloudRamGroupMembershipRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
object, err := ramService.DescribeRamGroupMembership(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
var users []string
for _, v := range object.Users.User {
users = append(users, v.UserName)
}
d.Set("group_name", d.Id())
if err := d.Set("user_names", users); err != nil {
return WrapError(err)
}
return nil
}
func resourceAlicloudRamGroupMembershipDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
users := expandStringList(d.Get("user_names").(*schema.Set).List())
group := d.Id()
if err := removeUsersFromGroup(client, users, group); err != nil {
return WrapError(err)
}
return WrapError(ramService.WaitForRamGroupMembership(d.Id(), Deleted, DefaultTimeout))
}
func addUsersToGroup(client *connectivity.AliyunClient, users []string, group string) error {
for _, u := range users {
request := ram.CreateAddUserToGroupRequest()
request.RegionId = client.RegionId
request.UserName = u
request.GroupName = group
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.AddUserToGroup(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, u, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
return nil
}
func removeUsersFromGroup(client *connectivity.AliyunClient, users []string, group string) error {
for _, u := range users {
request := ram.CreateRemoveUserFromGroupRequest()
request.RegionId = client.RegionId
request.UserName = u
request.GroupName = group
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.RemoveUserFromGroup(request)
})
if err != nil && !IsExpectedErrors(err, []string{"EntityNotExist"}) {
return WrapErrorf(err, DefaultErrorMsg, u, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
return nil
}
package alicloud
import (
"strings"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ram"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudRamGroupPolicyAtatchment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRamGroupPolicyAttachmentCreate,
Read: resourceAlicloudRamGroupPolicyAttachmentRead,
Delete: resourceAlicloudRamGroupPolicyAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"group_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"policy_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"policy_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"System", "Custom"}, false),
},
},
}
}
func resourceAlicloudRamGroupPolicyAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ram.CreateAttachPolicyToGroupRequest()
request.RegionId = client.RegionId
request.PolicyType = d.Get("policy_type").(string)
request.PolicyName = d.Get("policy_name").(string)
request.GroupName = d.Get("group_name").(string)
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.AttachPolicyToGroup(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ram_group_policy_attachment", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetId(strings.Join([]string{"group", request.PolicyName, string(request.PolicyType), request.GroupName}, COLON_SEPARATED))
return resourceAlicloudRamGroupPolicyAttachmentRead(d, meta)
}
func resourceAlicloudRamGroupPolicyAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
if split := strings.Split(d.Id(), ":"); len(split) != 4 {
id := strings.Join([]string{"group", d.Get("policy_name").(string), d.Get("policy_type").(string), d.Get("group_name").(string)}, COLON_SEPARATED)
d.SetId(id)
}
object, err := ramService.DescribeRamGroupPolicyAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 4)
if err != nil {
return WrapError(err)
}
d.Set("group_name", parts[3])
d.Set("policy_name", object.PolicyName)
d.Set("policy_type", object.PolicyType)
return nil
}
func resourceAlicloudRamGroupPolicyAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
id := strings.Join([]string{"group", d.Get("policy_name").(string), d.Get("policy_type").(string), d.Get("group_name").(string)}, COLON_SEPARATED)
if d.Id() != id {
d.SetId(id)
}
parts, err := ParseResourceId(id, 4)
if err != nil {
return WrapError(err)
}
request := ram.CreateDetachPolicyFromGroupRequest()
request.RegionId = client.RegionId
request.PolicyName = parts[1]
request.PolicyType = parts[2]
request.GroupName = parts[3]
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.DetachPolicyFromGroup(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(ramService.WaitForRamGroupPolicyAttachment(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"strconv"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ram"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudRamLoginProfile() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRamLoginProfileCreate,
Read: resourceAlicloudRamLoginProfileRead,
Update: resourceAlicloudRamLoginProfileUpdate,
Delete: resourceAlicloudRamLoginProfileDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"user_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"password": {
Type: schema.TypeString,
Required: true,
Sensitive: true,
},
"password_reset_required": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"mfa_bind_required": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func resourceAlicloudRamLoginProfileCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramSercvice := RamService{client}
request := ram.CreateCreateLoginProfileRequest()
request.RegionId = client.RegionId
request.UserName = d.Get("user_name").(string)
request.Password = d.Get("password").(string)
if v, ok := d.GetOk("password_reset_required"); ok {
request.PasswordResetRequired = requests.Boolean(strconv.FormatBool(v.(bool)))
}
if v, ok := d.GetOk("mfa_bind_required"); ok {
request.MFABindRequired = requests.Boolean(strconv.FormatBool(v.(bool)))
}
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.CreateLoginProfile(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ram_login_profile", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetId(request.UserName)
err = ramSercvice.WaitForRamLoginProfile(d.Id(), Normal, DefaultTimeout)
if err != nil {
return WrapError(err)
}
return resourceAlicloudRamLoginProfileRead(d, meta)
}
func resourceAlicloudRamLoginProfileUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ram.CreateUpdateLoginProfileRequest()
request.RegionId = client.RegionId
request.Password = d.Get("password").(string)
request.UserName = d.Id()
if d.HasChange("password_reset_required") {
request.PasswordResetRequired = requests.Boolean(strconv.FormatBool(d.Get("password_reset_required").(bool)))
}
if d.HasChange("mfa_bind_required") {
request.MFABindRequired = requests.Boolean(strconv.FormatBool(d.Get("mfa_bind_required").(bool)))
}
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.UpdateLoginProfile(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return resourceAlicloudRamLoginProfileRead(d, meta)
}
func resourceAlicloudRamLoginProfileRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
object, err := ramService.DescribeRamLoginProfile(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
profile := object.LoginProfile
d.Set("user_name", profile.UserName)
d.Set("mfa_bind_required", profile.MFABindRequired)
d.Set("password_reset_required", profile.PasswordResetRequired)
return nil
}
func resourceAlicloudRamLoginProfileDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
request := ram.CreateDeleteLoginProfileRequest()
request.RegionId = client.RegionId
request.UserName = d.Id()
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.DeleteLoginProfile(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist.User", "EntityNotExist.User.LoginProfile"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(ramService.WaitForRamLoginProfile(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudRamPolicy() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRamPolicyCreate,
Read: resourceAlicloudRamPolicyRead,
Update: resourceAlicloudRamPolicyUpdate,
Delete: resourceAlicloudRamPolicyDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Delete: schema.DefaultTimeout(26 * time.Minute),
},
Schema: map[string]*schema.Schema{
"default_version": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"policy_document": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.ValidateJsonString,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
equal, _ := compareJsonTemplateAreEquivalent(old, new)
return equal
},
ConflictsWith: []string{"document", "version", "statement"},
},
"document": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.ValidateJsonString,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
equal, _ := compareJsonTemplateAreEquivalent(old, new)
return equal
},
Deprecated: "Field 'document' has been deprecated from provider version 1.114.0. New field 'policy_document' instead.",
ConflictsWith: []string{"policy_document", "version", "statement"},
},
"policy_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"name"},
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Deprecated: "Field 'name' has been deprecated from provider version 1.114.0. New field 'policy_name' instead.",
ConflictsWith: []string{"policy_name"},
},
"rotate_strategy": {
Type: schema.TypeString,
Optional: true,
Default: "None",
ValidateFunc: validation.StringInSlice([]string{"DeleteOldestNonDefaultVersionWhenLimitExceeded", "None"}, false),
},
"version_id": {
Type: schema.TypeString,
Computed: true,
},
"statement": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Deprecated: "Field 'statement' has been deprecated from version 1.49.0, and use field 'document' to replace. ",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"effect": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"Allow", "Deny"}, false),
},
"action": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"resource": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
},
ConflictsWith: []string{"document"},
},
"version": {
Type: schema.TypeString,
Optional: true,
Default: "1",
ConflictsWith: []string{"document"},
// can only be '1' so far.
ValidateFunc: validation.StringInSlice([]string{"1"}, false),
Deprecated: "Field 'version' has been deprecated from version 1.49.0, and use field 'document' to replace. ",
},
"force": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"attachment_count": {
Type: schema.TypeInt,
Computed: true,
},
},
}
}
func resourceAlicloudRamPolicyCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreatePolicy"
request := make(map[string]interface{})
conn, err := client.NewRamClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("policy_document"); ok {
request["PolicyDocument"] = v
} else if v, ok := d.GetOk("document"); ok {
request["PolicyDocument"] = v
} else if v, ok := d.GetOk("statement"); ok {
ramService := RamService{client}
doc, err := ramService.AssemblePolicyDocument(v.(*schema.Set).List(), d.Get("version").(string))
if err != nil {
return WrapError(err)
}
request["PolicyDocument"] = doc
} else {
return WrapError(Error("One of 'policy_document', 'document', 'statement' must be specified."))
}
if v, ok := d.GetOk("policy_name"); ok {
request["PolicyName"] = v
} else if v, ok := d.GetOk("name"); ok {
request["PolicyName"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-05-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ram_policy", action, AlibabaCloudSdkGoERROR)
}
responsePolicy := response["Policy"].(map[string]interface{})
d.SetId(fmt.Sprint(responsePolicy["PolicyName"]))
return resourceAlicloudRamPolicyRead(d, meta)
}
func resourceAlicloudRamPolicyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
object, err := ramService.DescribeRamPolicy(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ram_policy ramService.DescribeRamPolicy Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("policy_name", d.Id())
d.Set("name", d.Id())
d.Set("default_version", object["Policy"].(map[string]interface{})["DefaultVersion"])
d.Set("description", object["Policy"].(map[string]interface{})["Description"])
d.Set("policy_document", object["DefaultPolicyVersion"].(map[string]interface{})["PolicyDocument"])
d.Set("document", object["DefaultPolicyVersion"].(map[string]interface{})["PolicyDocument"])
d.Set("version_id", object["DefaultPolicyVersion"].(map[string]interface{})["VersionId"])
statement, version, err := ramService.ParsePolicyDocument(object["DefaultPolicyVersion"].(map[string]interface{})["PolicyDocument"].(string))
if err != nil {
return WrapError(err)
}
d.Set("version", version)
d.Set("statement", statement)
d.Set("attachment_count", object["Policy"].(map[string]interface{})["AttachmentCount"])
d.Set("type", object["Policy"].(map[string]interface{})["PolicyType"])
return nil
}
func resourceAlicloudRamPolicyUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"PolicyName": d.Id(),
}
if d.HasChange("policy_document") {
update = true
request["PolicyDocument"] = d.Get("policy_document")
}
if d.HasChange("document") {
update = true
request["PolicyDocument"] = d.Get("document")
}
request["SetAsDefault"] = true
if d.HasChange("statement") || d.HasChange("version") {
ramService := RamService{client}
document, err := ramService.AssemblePolicyDocument(d.Get("statement").(*schema.Set).List(), d.Get("version").(string))
if err != nil {
return WrapError(err)
}
request["PolicyDocument"] = document
}
if update {
if _, ok := d.GetOk("rotate_strategy"); ok {
request["RotateStrategy"] = d.Get("rotate_strategy")
}
action := "CreatePolicyVersion"
conn, err := client.NewRamClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-05-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudRamPolicyRead(d, meta)
}
func resourceAlicloudRamPolicyDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeletePolicy"
var response map[string]interface{}
conn, err := client.NewRamClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"PolicyName": d.Id(),
}
if d.Get("force").(bool) {
listRequest := map[string]interface{}{
"PolicyName": d.Id(),
"PolicyType": "Custom",
}
listAction := "ListEntitiesForPolicy"
response, err = conn.DoRequest(StringPointer(listAction), nil, StringPointer("POST"), StringPointer("2015-05-01"), StringPointer("AK"), nil, listRequest, &util.RuntimeOptions{})
userResp, err := jsonpath.Get("$.Users.User", response)
if len(userResp.([]interface{})) > 0 {
for _, v := range userResp.([]interface{}) {
userAction := "DetachPolicyFromUser"
userRequest := map[string]interface{}{
"PolicyName": d.Id(),
"UserName": v.(map[string]interface{})["UserName"],
"PolicyType": "Custom",
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(userAction), nil, StringPointer("POST"), StringPointer("2015-05-01"), StringPointer("AK"), nil, userRequest, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, userRequest)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
}
groupResp, err := jsonpath.Get("$.Groups.Group", response)
if len(groupResp.([]interface{})) > 0 {
for _, v := range groupResp.([]interface{}) {
groupAction := "DetachPolicyFromGroup"
groupRequest := map[string]interface{}{
"PolicyName": d.Id(),
"GroupName": v.(map[string]interface{})["GroupName"],
"PolicyType": "Custom",
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(groupAction), nil, StringPointer("POST"), StringPointer("2015-05-01"), StringPointer("AK"), nil, groupRequest, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, groupRequest)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
}
roleResp, err := jsonpath.Get("$.Roles.Role", response)
if len(roleResp.([]interface{})) > 0 {
for _, v := range roleResp.([]interface{}) {
roleAction := "DetachPolicyFromRole"
roleRequest := map[string]interface{}{
"PolicyName": d.Id(),
"RoleName": v.(map[string]interface{})["RoleName"],
"PolicyType": "Custom",
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(roleAction), nil, StringPointer("POST"), StringPointer("2015-05-01"), StringPointer("AK"), nil, roleRequest, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, roleRequest)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
}
listVersionsRequest := map[string]interface{}{
"PolicyName": d.Id(),
"PolicyType": "Custom",
}
listVersionsAction := "ListPolicyVersions"
response, err = conn.DoRequest(StringPointer(listVersionsAction), nil, StringPointer("POST"), StringPointer("2015-05-01"), StringPointer("AK"), nil, listVersionsRequest, &util.RuntimeOptions{})
versionsResp, err := jsonpath.Get("$.PolicyVersions.PolicyVersion", response)
// More than one means there are other versions besides the default version
if len(versionsResp.([]interface{})) > 1 {
for _, v := range versionsResp.([]interface{}) {
if !v.(map[string]interface{})["IsDefaultVersion"].(bool) {
versionAction := "DeletePolicyVersion"
versionRequest := map[string]interface{}{
"PolicyName": d.Id(),
"VersionId": v.(map[string]interface{})["VersionId"],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(versionAction), nil, StringPointer("POST"), StringPointer("2015-05-01"), StringPointer("AK"), nil, versionRequest, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(versionAction, response, versionRequest)
return nil
})
}
}
}
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-05-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"DeleteConflict.Policy.Group", "DeleteConflict.Policy.User", "DeleteConflict.Policy.Version", "DeleteConflict.Role.Policy"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ram"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudRamRole() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRamRoleCreate,
Read: resourceAlicloudRamRoleRead,
Update: resourceAlicloudRamRoleUpdate,
Delete: resourceAlicloudRamRoleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ram_users": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Set: schema.HashString,
ConflictsWith: []string{"document"},
Deprecated: "Field 'ram_users' has been deprecated from version 1.49.0, and use field 'document' to replace. ",
},
"max_session_duration": {
Type: schema.TypeInt,
Optional: true,
Default: 3600,
ValidateFunc: validation.IntBetween(3600, 43200),
},
"services": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Set: schema.HashString,
ConflictsWith: []string{"document"},
Deprecated: "Field 'services' has been deprecated from version 1.49.0, and use field 'document' to replace. ",
},
"document": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"ram_users", "services", "version"},
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
equal, _ := compareJsonTemplateAreEquivalent(old, new)
return equal
},
ValidateFunc: validation.ValidateJsonString,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"version": {
Type: schema.TypeString,
Optional: true,
Default: "1",
ConflictsWith: []string{"document"},
// can only be '1' so far.
ValidateFunc: validation.StringInSlice([]string{"1"}, false),
Deprecated: "Field 'version' has been deprecated from version 1.49.0, and use field 'document' to replace. ",
},
"force": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"arn": {
Type: schema.TypeString,
Computed: true,
},
"role_id": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudRamRoleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request, err := buildAlicloudRamRoleCreateArgs(d, meta)
if err != nil {
return WrapError(err)
}
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.CreateRole(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ram_role", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ram.CreateRoleResponse)
d.SetId(response.Role.RoleName)
return resourceAlicloudRamRoleRead(d, meta)
}
func resourceAlicloudRamRoleUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
var response map[string]interface{}
update := false
request := map[string]interface{}{
"RoleName": d.Id(),
}
if d.HasChange("document") {
update = true
request["NewAssumeRolePolicyDocument"] = d.Get("document").(string)
} else if d.HasChange("ram_users") || d.HasChange("services") || d.HasChange("version") {
update = true
document, err := ramService.AssembleRolePolicyDocument(d.Get("ram_users").(*schema.Set).List(), d.Get("services").(*schema.Set).List(), d.Get("version").(string))
if err != nil {
return WrapError(err)
}
request["NewAssumeRolePolicyDocument"] = document
}
if d.HasChange("max_session_duration") {
update = true
request["NewMaxSessionDuration"] = d.Get("max_session_duration")
}
if d.HasChange("description") {
update = true
request["NewDescription"] = d.Get("description")
}
if update {
action := "UpdateRole"
conn, err := client.NewRamClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-05-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudRamRoleRead(d, meta)
}
func resourceAlicloudRamRoleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
object, err := ramService.DescribeRamRole(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
role := object.Role
rolePolicy, err := ramService.ParseRolePolicyDocument(role.AssumeRolePolicyDocument)
if err != nil {
return WrapError(err)
}
if len(rolePolicy.Statement) > 0 {
principal := rolePolicy.Statement[0].Principal
d.Set("services", principal.Service)
d.Set("ram_users", principal.RAM)
}
d.Set("role_id", role.RoleId)
d.Set("name", role.RoleName)
d.Set("arn", role.Arn)
d.Set("description", role.Description)
d.Set("version", rolePolicy.Version)
d.Set("document", role.AssumeRolePolicyDocument)
d.Set("max_session_duration", role.MaxSessionDuration)
return nil
}
func resourceAlicloudRamRoleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
ListPoliciesForRoleRequest := ram.CreateListPoliciesForRoleRequest()
ListPoliciesForRoleRequest.RegionId = client.RegionId
ListPoliciesForRoleRequest.RoleName = d.Id()
if d.Get("force").(bool) {
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.ListPoliciesForRole(ListPoliciesForRoleRequest)
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist.Role"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), ListPoliciesForRoleRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(ListPoliciesForRoleRequest.GetActionName(), raw, ListPoliciesForRoleRequest.RpcRequest, ListPoliciesForRoleRequest)
response, _ := raw.(*ram.ListPoliciesForRoleResponse)
// Loop and remove the Policies from the Role
if len(response.Policies.Policy) > 0 {
for _, v := range response.Policies.Policy {
request := ram.CreateDetachPolicyFromRoleRequest()
request.RegionId = client.RegionId
request.RoleName = v.PolicyName
request.PolicyType = v.PolicyType
request.RoleName = d.Id()
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.DetachPolicyFromRole(request)
})
if err != nil && !IsExpectedErrors(err, []string{"EntityNotExist"}) {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
}
}
deleteRoleRequest := ram.CreateDeleteRoleRequest()
deleteRoleRequest.RegionId = client.RegionId
deleteRoleRequest.RoleName = d.Id()
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.DeleteRole(deleteRoleRequest)
})
if err != nil {
if IsExpectedErrors(err, []string{"DeleteConflict.Role.Policy"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(ListPoliciesForRoleRequest.GetActionName(), raw, ListPoliciesForRoleRequest.RpcRequest, ListPoliciesForRoleRequest)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist.Role"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), deleteRoleRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(ramService.WaitForRamRole(d.Id(), Deleted, DefaultTimeout))
}
func buildAlicloudRamRoleCreateArgs(d *schema.ResourceData, meta interface{}) (*ram.CreateRoleRequest, error) {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
request := ram.CreateCreateRoleRequest()
request.RegionId = client.RegionId
request.RoleName = d.Get("name").(string)
ramUsers, usersOk := d.GetOk("ram_users")
services, servicesOk := d.GetOk("services")
document, documentOk := d.GetOk("document")
if !usersOk && !servicesOk && !documentOk {
return &ram.CreateRoleRequest{}, WrapError(Error("At least one of 'ram_users', 'services' or 'document' must be set."))
}
if documentOk {
request.AssumeRolePolicyDocument = document.(string)
} else {
rolePolicyDocument, err := ramService.AssembleRolePolicyDocument(ramUsers.(*schema.Set).List(), services.(*schema.Set).List(), d.Get("version").(string))
if err != nil {
return &ram.CreateRoleRequest{}, WrapError(err)
}
request.AssumeRolePolicyDocument = rolePolicyDocument
}
if v, ok := d.GetOk("description"); ok && v.(string) != "" {
request.Description = v.(string)
}
if v, ok := d.GetOk("max_session_duration"); ok {
request.MaxSessionDuration = requests.NewInteger(v.(int))
}
return request, nil
}
package alicloud
import (
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudRamRoleAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudInstanceRoleAttachmentCreate,
Read: resourceAlicloudInstanceRoleAttachmentRead,
Delete: resourceAlicloudInstanceRoleAttachmentDelete,
Schema: map[string]*schema.Schema{
"role_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_ids": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudInstanceRoleAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
instanceIds := convertListToJsonString(d.Get("instance_ids").(*schema.Set).List())
request := ecs.CreateAttachInstanceRamRoleRequest()
request.RegionId = client.RegionId
request.InstanceIds = instanceIds
request.RamRoleName = d.Get("role_name").(string)
err := ramService.JudgeRolePolicyPrincipal(request.RamRoleName)
if err != nil {
return WrapError(err)
}
return resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.AttachInstanceRamRole(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"unexpected end of JSON input"}) {
return resource.RetryableError(WrapError(Error("Please trying again.")))
}
return resource.NonRetryableError(WrapErrorf(err, DefaultErrorMsg, "ram_role_attachment", request.GetActionName(), AlibabaCloudSdkGoERROR))
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetId(d.Get("role_name").(string) + COLON_SEPARATED + instanceIds)
return resource.NonRetryableError(WrapError(resourceAlicloudInstanceRoleAttachmentRead(d, meta)))
})
}
func resourceAlicloudInstanceRoleAttachmentRead(d *schema.ResourceData, meta interface{}) error {
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
roleName := parts[0]
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
object, err := ramService.DescribeRamRoleAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
instRoleSets := object.InstanceRamRoleSets.InstanceRamRoleSet
var instIds []string
for _, item := range instRoleSets {
if item.RamRoleName == roleName {
instIds = append(instIds, item.InstanceId)
}
}
d.Set("role_name", object.InstanceRamRoleSets.InstanceRamRoleSet[0].RamRoleName)
d.Set("instance_ids", instIds)
return nil
}
func resourceAlicloudInstanceRoleAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
roleName := parts[0]
instanceIds := parts[1]
request := ecs.CreateDetachInstanceRamRoleRequest()
request.RegionId = client.RegionId
request.RamRoleName = roleName
request.InstanceIds = instanceIds
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DetachInstanceRamRole(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"unexpected end of JSON input"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(WrapErrorf(err, DefaultTimeoutMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR))
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(ramService.WaitForRamRoleAttachment(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"strings"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ram"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudRamRolePolicyAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRamRolePolicyAttachmentCreate,
Read: resourceAlicloudRamRolePolicyAttachmentRead,
//Update: resourceAlicloudRamRolePolicyAttachmentUpdate,
Delete: resourceAlicloudRamRolePolicyAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"role_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"policy_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"policy_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"System", "Custom"}, false),
},
},
}
}
func resourceAlicloudRamRolePolicyAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ram.CreateAttachPolicyToRoleRequest()
request.RegionId = client.RegionId
request.RoleName = d.Get("role_name").(string)
request.PolicyType = d.Get("policy_type").(string)
request.PolicyName = d.Get("policy_name").(string)
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.AttachPolicyToRole(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ram_role_policy_attachment", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
// In order to be compatible with previous Id (before 1.9.6) which format to role:<policy_name>:<policy_type>:<role_name>
d.SetId(strings.Join([]string{"role", request.PolicyName, request.PolicyType, request.RoleName}, COLON_SEPARATED))
return resourceAlicloudRamRolePolicyAttachmentRead(d, meta)
}
func resourceAlicloudRamRolePolicyAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
if split := strings.Split(d.Id(), ":"); len(split) != 4 {
id := strings.Join([]string{"role", d.Get("policy_name").(string), d.Get("policy_type").(string), d.Get("role_name").(string)}, COLON_SEPARATED)
d.SetId(id)
}
object, err := ramService.DescribeRamRolePolicyAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 4)
if err != nil {
return WrapError(err)
}
d.Set("role_name", parts[3])
d.Set("policy_name", object.PolicyName)
d.Set("policy_type", object.PolicyType)
return nil
}
func resourceAlicloudRamRolePolicyAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
id := strings.Join([]string{"role", d.Get("policy_name").(string), d.Get("policy_type").(string), d.Get("role_name").(string)}, COLON_SEPARATED)
if d.Id() != id {
d.SetId(id)
}
parts, err := ParseResourceId(id, 4)
if err != nil {
return WrapError(err)
}
request := ram.CreateDetachPolicyFromRoleRequest()
request.RegionId = client.RegionId
request.PolicyName = parts[1]
request.PolicyType = parts[2]
request.RoleName = parts[3]
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.DetachPolicyFromRole(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(ramService.WaitForRamRolePolicyAttachment(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudRamSamlProvider() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRamSamlProviderCreate,
Read: resourceAlicloudRamSamlProviderRead,
Update: resourceAlicloudRamSamlProviderUpdate,
Delete: resourceAlicloudRamSamlProviderDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"arn": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"encodedsaml_metadata_document": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return ramSAMLProviderDiffSuppressFunc(old, new)
},
},
"saml_provider_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"update_date": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudRamSamlProviderCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateSAMLProvider"
request := make(map[string]interface{})
conn, err := client.NewImsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("encodedsaml_metadata_document"); ok {
request["EncodedSAMLMetadataDocument"] = v
}
request["SAMLProviderName"] = d.Get("saml_provider_name")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ram_saml_provider", action, AlibabaCloudSdkGoERROR)
}
responseSAMLProvider := response["SAMLProvider"].(map[string]interface{})
d.SetId(fmt.Sprint(responseSAMLProvider["SAMLProviderName"]))
return resourceAlicloudRamSamlProviderRead(d, meta)
}
func resourceAlicloudRamSamlProviderRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
imsService := ImsService{client}
object, err := imsService.DescribeRamSamlProvider(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ram_saml_provider imsService.DescribeRamSamlProvider Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("saml_provider_name", d.Id())
d.Set("arn", object["Arn"])
d.Set("description", object["Description"])
d.Set("encodedsaml_metadata_document", object["EncodedSAMLMetadataDocument"])
d.Set("update_date", object["UpdateDate"])
return nil
}
func resourceAlicloudRamSamlProviderUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewImsClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
update := false
request := map[string]interface{}{
"SAMLProviderName": d.Id(),
}
if d.HasChange("description") {
update = true
request["NewDescription"] = d.Get("description")
}
if d.HasChange("encodedsaml_metadata_document") {
update = true
request["NewEncodedSAMLMetadataDocument"] = d.Get("encodedsaml_metadata_document")
}
if update {
action := "UpdateSAMLProvider"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudRamSamlProviderRead(d, meta)
}
func resourceAlicloudRamSamlProviderDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteSAMLProvider"
var response map[string]interface{}
conn, err := client.NewImsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"SAMLProviderName": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist.SAMLProviderError"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudRamSecurityPreference() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRamSecurityPreferenceCreate,
Read: resourceAlicloudRamSecurityPreferenceRead,
Update: resourceAlicloudRamSecurityPreferenceUpdate,
Delete: resourceAlicloudRamSecurityPreferenceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"enable_save_mfa_ticket": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"allow_user_to_change_password": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"allow_user_to_manage_access_keys": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"allow_user_to_manage_mfa_devices": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"login_session_duration": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"login_network_masks": {
Type: schema.TypeString,
Optional: true,
},
"enforce_mfa_for_login": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
},
}
}
func resourceAlicloudRamSecurityPreferenceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "SetSecurityPreference"
request := make(map[string]interface{})
conn, err := client.NewImsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("allow_user_to_change_password"); ok {
request["AllowUserToChangePassword"] = v
}
if v, ok := d.GetOkExists("allow_user_to_manage_access_keys"); ok {
request["AllowUserToManageAccessKeys"] = v
}
if v, ok := d.GetOkExists("allow_user_to_manage_mfa_devices"); ok {
request["AllowUserToManageMFADevices"] = v
}
if v, ok := d.GetOkExists("enable_save_mfa_ticket"); ok {
request["EnableSaveMFATicket"] = v
}
if v, ok := d.GetOk("login_network_masks"); ok {
request["LoginNetworkMasks"] = v
}
if v, ok := d.GetOk("login_session_duration"); ok {
request["LoginSessionDuration"] = v
}
if v, ok := d.GetOk("enforce_mfa_for_login"); ok {
request["EnforceMFAForLogin"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ram_security_preference", action, AlibabaCloudSdkGoERROR)
}
d.SetId("RamSecurityPreference")
return resourceAlicloudRamSecurityPreferenceRead(d, meta)
}
func resourceAlicloudRamSecurityPreferenceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
object, err := ramService.DescribeRamSecurityPreference(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ram_security_preference ramService.DescribeRamSecurityPreference Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
if v, exist := object["AccessKeyPreference"].(map[string]interface{}); exist {
d.Set("allow_user_to_manage_access_keys", v["AllowUserToManageAccessKeys"])
}
if v, exist := object["LoginProfilePreference"].(map[string]interface{}); exist {
d.Set("allow_user_to_change_password", v["AllowUserToChangePassword"])
d.Set("enable_save_mfa_ticket", v["EnableSaveMFATicket"])
d.Set("login_network_masks", v["LoginNetworkMasks"])
d.Set("login_session_duration", v["LoginSessionDuration"])
d.Set("enforce_mfa_for_login", v["EnforceMFAForLogin"])
}
if v, exist := object["MFAPreference"].(map[string]interface{}); exist {
d.Set("allow_user_to_manage_mfa_devices", v["AllowUserToManageMFADevices"])
}
return nil
}
func resourceAlicloudRamSecurityPreferenceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewImsClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
update := false
request := map[string]interface{}{}
if d.HasChange("allow_user_to_change_password") {
update = true
}
request["AllowUserToChangePassword"] = d.Get("allow_user_to_change_password")
if d.HasChange("allow_user_to_manage_access_keys") {
update = true
}
request["AllowUserToManageAccessKeys"] = d.Get("allow_user_to_manage_access_keys")
if d.HasChange("allow_user_to_manage_mfa_devices") {
update = true
}
request["AllowUserToManageMFADevices"] = d.Get("allow_user_to_manage_mfa_devices")
if d.HasChange("enable_save_mfa_ticket") {
update = true
}
request["EnableSaveMFATicket"] = d.Get("enable_save_mfa_ticket")
if d.HasChange("login_network_masks") {
update = true
}
request["LoginNetworkMasks"] = d.Get("login_network_masks")
if d.HasChange("login_session_duration") {
update = true
}
request["LoginSessionDuration"] = d.Get("login_session_duration")
if d.HasChange("enforce_mfa_for_login") {
update = true
}
request["EnforceMFAForLogin"] = d.Get("enforce_mfa_for_login")
if update {
action := "SetSecurityPreference"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudRamSecurityPreferenceRead(d, meta)
}
func resourceAlicloudRamSecurityPreferenceDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudRamSecurityPreference. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
package alicloud
import (
"github.com/aliyun/alibaba-cloud-sdk-go/services/ram"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudRamUser() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRamUserCreate,
Read: resourceAlicloudRamUserRead,
Update: resourceAlicloudRamUserUpdate,
Delete: resourceAlicloudRamUserDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"display_name": {
Type: schema.TypeString,
Optional: true,
},
"mobile": {
Type: schema.TypeString,
Optional: true,
},
"email": {
Type: schema.TypeString,
Optional: true,
},
"force": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"comments": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(0, 128),
},
},
}
}
func resourceAlicloudRamUserCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
request := ram.CreateCreateUserRequest()
request.RegionId = client.RegionId
request.UserName = d.Get("name").(string)
if v, ok := d.GetOk("display_name"); ok {
request.DisplayName = v.(string)
}
if v, ok := d.GetOk("mobile"); ok {
request.MobilePhone = v.(string)
}
if v, ok := d.GetOk("email"); ok {
request.Email = v.(string)
}
if v, ok := d.GetOk("comments"); ok {
request.Comments = v.(string)
}
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.CreateUser(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ram_user", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ram.CreateUserResponse)
d.SetId(response.User.UserId)
err = ramService.WaitForRamUser(d.Id(), Normal, DefaultTimeout)
if err != nil {
return WrapError(err)
}
return resourceAlicloudRamUserRead(d, meta)
}
func resourceAlicloudRamUserUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ram.CreateUpdateUserRequest()
request.RegionId = client.RegionId
request.UserName = d.Get("name").(string)
request.NewUserName = d.Get("name").(string)
update := false
if d.HasChange("name") && !d.IsNewResource() {
ov, nv := d.GetChange("name")
request.UserName = ov.(string)
request.NewUserName = nv.(string)
update = true
}
if d.HasChange("display_name") {
request.NewDisplayName = d.Get("display_name").(string)
update = true
}
if d.HasChange("mobile") {
request.NewMobilePhone = d.Get("mobile").(string)
update = true
}
if d.HasChange("email") {
request.NewEmail = d.Get("email").(string)
update = true
}
if d.HasChange("comments") {
request.NewComments = d.Get("comments").(string)
update = true
}
if update {
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.UpdateUser(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
return resourceAlicloudRamUserRead(d, meta)
}
func resourceAlicloudRamUserRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := &RamService{client: client}
object, err := ramService.DescribeRamUser(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.SetId(object.UserId)
d.Set("name", object.UserName)
d.Set("display_name", object.DisplayName)
d.Set("mobile", object.MobilePhone)
d.Set("email", object.Email)
d.Set("comments", object.Comments)
return nil
}
func resourceAlicloudRamUserDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := &RamService{client: client}
object, err := ramService.DescribeRamUser(d.Id())
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
userName := object.UserName
request := ram.CreateListAccessKeysRequest()
request.RegionId = client.RegionId
request.UserName = userName
if d.Get("force").(bool) {
// list and delete access keys for this user
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.ListAccessKeys(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
listAccessKeysResponse, _ := raw.(*ram.ListAccessKeysResponse)
if len(listAccessKeysResponse.AccessKeys.AccessKey) > 0 {
for _, v := range listAccessKeysResponse.AccessKeys.AccessKey {
request := ram.CreateDeleteAccessKeyRequest()
request.RegionId = client.RegionId
request.UserAccessKeyId = v.AccessKeyId
request.UserName = userName
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.DeleteAccessKey(request)
})
if err != nil && !IsExpectedErrors(err, []string{"EntityNotExist"}) {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
}
// list and delete policies for this user
request := ram.CreateListPoliciesForUserRequest()
request.RegionId = client.RegionId
request.UserName = userName
raw, err = client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.ListPoliciesForUser(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
listPoliciesForUserResponse, _ := raw.(*ram.ListPoliciesForUserResponse)
if len(listPoliciesForUserResponse.Policies.Policy) > 0 {
for _, v := range listPoliciesForUserResponse.Policies.Policy {
request := ram.CreateDetachPolicyFromUserRequest()
request.RegionId = client.RegionId
request.PolicyName = v.PolicyName
request.PolicyType = v.PolicyType
request.UserName = userName
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.DetachPolicyFromUser(request)
})
if err != nil && !IsExpectedErrors(err, []string{"EntityNotExist"}) {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
}
// list and delete groups for this user
listGroupsForUserRequest := ram.CreateListGroupsForUserRequest()
listGroupsForUserRequest.RegionId = client.RegionId
listGroupsForUserRequest.UserName = userName
raw, err = client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.ListGroupsForUser(listGroupsForUserRequest)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), listGroupsForUserRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(listGroupsForUserRequest.GetActionName(), raw, listGroupsForUserRequest.RpcRequest, listGroupsForUserRequest)
listGroupsForUserResponse, _ := raw.(*ram.ListGroupsForUserResponse)
if len(listGroupsForUserResponse.Groups.Group) > 0 {
for _, v := range listGroupsForUserResponse.Groups.Group {
request := ram.CreateRemoveUserFromGroupRequest()
request.RegionId = client.RegionId
request.UserName = userName
request.GroupName = v.GroupName
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.RemoveUserFromGroup(request)
})
if err != nil && !IsExpectedErrors(err, []string{"EntityNotExist"}) {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
}
// delete login profile for this user
deleteLoginProfileRequest := ram.CreateDeleteLoginProfileRequest()
deleteLoginProfileRequest.RegionId = client.RegionId
deleteLoginProfileRequest.UserName = userName
raw, err = client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.DeleteLoginProfile(deleteLoginProfileRequest)
})
if err != nil && !IsExpectedErrors(err, []string{"EntityNotExist.User.LoginProfile"}) {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), deleteLoginProfileRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(deleteLoginProfileRequest.GetActionName(), raw)
// unbind MFA device for this user
unbindMFADeviceRequest := ram.CreateUnbindMFADeviceRequest()
unbindMFADeviceRequest.UserName = userName
raw, err = client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.UnbindMFADevice(unbindMFADeviceRequest)
})
if err != nil && !IsExpectedErrors(err, []string{"EntityNotExist", "EntityNotExist.User.MFADevice"}) {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), unbindMFADeviceRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(unbindMFADeviceRequest.GetActionName(), raw, deleteLoginProfileRequest.RpcRequest, deleteLoginProfileRequest)
}
deleteUserRequest := ram.CreateDeleteUserRequest()
deleteUserRequest.RegionId = client.RegionId
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
deleteUserRequest.UserName = userName
return ramClient.DeleteUser(deleteUserRequest)
})
if err != nil {
if IsExpectedErrors(err, []string{"DeleteConflict.User.AccessKey", "DeleteConflict.User.Group", "DeleteConflict.User.Policy", "DeleteConflict.User.LoginProfile", "DeleteConflict.User.MFADevice"}) {
return WrapError(Error("The user can not be deleted if he has any access keys, login profile, groups, policies, or MFA device attached. You can force the deletion of the user by setting force equals true."))
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(deleteUserRequest.GetActionName(), raw, deleteUserRequest.RpcRequest, deleteUserRequest)
return WrapError(ramService.WaitForRamUser(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"strings"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ram"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudRamUserPolicyAtatchment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRamUserPolicyAttachmentCreate,
Read: resourceAlicloudRamUserPolicyAttachmentRead,
Delete: resourceAlicloudRamUserPolicyAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"user_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"policy_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"policy_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"System", "Custom"}, false),
},
},
}
}
func resourceAlicloudRamUserPolicyAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ram.CreateAttachPolicyToUserRequest()
request.RegionId = client.RegionId
request.UserName = d.Get("user_name").(string)
request.PolicyName = d.Get("policy_name").(string)
request.PolicyType = d.Get("policy_type").(string)
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.AttachPolicyToUser(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ram_user_policy_attachment", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetId(strings.Join([]string{"user", request.PolicyName, request.PolicyType, request.UserName}, COLON_SEPARATED))
return resourceAlicloudRamUserPolicyAttachmentRead(d, meta)
}
func resourceAlicloudRamUserPolicyAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
// In order to be compatible with previous Id (before 1.9.6) which format to user:<policy_name>:<policy_type>:<user_name>
if split := strings.Split(d.Id(), ":"); len(split) != 4 {
id := strings.Join([]string{"user", d.Get("policy_name").(string), d.Get("policy_type").(string), d.Get("user_name").(string)}, COLON_SEPARATED)
d.SetId(id)
}
object, err := ramService.DescribeRamUserPolicyAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 4)
if err != nil {
return WrapError(err)
}
d.Set("user_name", parts[3])
d.Set("policy_name", object.PolicyName)
d.Set("policy_type", object.PolicyType)
return nil
}
func resourceAlicloudRamUserPolicyAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ramService := RamService{client}
// In order to be compatible with previous Id (before 1.9.6) which format to user:<policy_name>:<policy_type>:<user_name>
id := strings.Join([]string{"user", d.Get("policy_name").(string), d.Get("policy_type").(string), d.Get("user_name").(string)}, COLON_SEPARATED)
if d.Id() != id {
d.SetId(id)
}
parts, err := ParseResourceId(id, 4)
if err != nil {
return WrapError(err)
}
request := ram.CreateDetachPolicyFromUserRequest()
request.RegionId = client.RegionId
request.PolicyName = parts[1]
request.PolicyType = parts[2]
request.UserName = parts[3]
raw, err := client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.DetachPolicyFromUser(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(ramService.WaitForRamUserPolicyAttachment(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudRdcOrganization() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRdcOrganizationCreate,
Read: resourceAlicloudRdcOrganizationRead,
Update: resourceAlicloudRdcOrganizationUpdate,
Delete: resourceAlicloudRdcOrganizationDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"desired_member_count": {
Type: schema.TypeInt,
Optional: true,
},
"organization_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"real_pk": {
Type: schema.TypeString,
Optional: true,
},
"source": {
Type: schema.TypeString,
Required: true,
},
},
}
}
func resourceAlicloudRdcOrganizationCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateDevopsOrganization"
request := make(map[string]interface{})
conn, err := client.NewDevopsrdcClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("desired_member_count"); ok {
request["DesiredMemberCount"] = v
}
request["OrgName"] = d.Get("organization_name")
if v, ok := d.GetOk("real_pk"); ok {
request["RealPk"] = v
}
request["Source"] = d.Get("source")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-03"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_rdc_organization", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["Object"]))
return resourceAlicloudRdcOrganizationRead(d, meta)
}
func resourceAlicloudRdcOrganizationRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
devopsRdcService := DevopsRdcService{client}
object, err := devopsRdcService.DescribeRdcOrganization(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_rdc_organization devopsRdcService.DescribeRdcOrganization Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("organization_name", object["Name"])
return nil
}
func resourceAlicloudRdcOrganizationUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return resourceAlicloudRdcOrganizationRead(d, meta)
}
func resourceAlicloudRdcOrganizationDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteDevopsOrganization"
var response map[string]interface{}
conn, err := client.NewDevopsrdcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"OrgId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-03"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidOrganization.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudRdsAccount() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRdsAccountCreate,
Read: resourceAlicloudRdsAccountRead,
Update: resourceAlicloudRdsAccountUpdate,
Delete: resourceAlicloudRdsAccountDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(5 * time.Minute),
Update: schema.DefaultTimeout(6 * time.Minute),
},
Schema: map[string]*schema.Schema{
"account_description": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"description"},
},
"description": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Field 'description' has been deprecated from provider version 1.120.0. New field 'account_description' instead.",
ConflictsWith: []string{"account_description"},
},
"account_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-z][a-z0-9_]{0,61}[a-z0-9]$`), "The name can consist of lowercase letters, numbers, underscores, and must begin with letters and end with letters or numbers"),
ConflictsWith: []string{"name"},
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-z][a-z0-9_]{0,61}[a-z0-9]$`), "The name can consist of lowercase letters, numbers, underscores, and must begin with letters and end with letters or numbers"),
Deprecated: "Field 'name' has been deprecated from provider version 1.120.0. New field 'account_name' instead.",
ConflictsWith: []string{"account_name"},
},
"account_password": {
Type: schema.TypeString,
Sensitive: true,
Optional: true,
Computed: true,
ConflictsWith: []string{"password"},
},
"password": {
Type: schema.TypeString,
Sensitive: true,
Optional: true,
Computed: true,
Deprecated: "Field 'password' has been deprecated from provider version 1.120.0. New field 'account_password' instead.",
ConflictsWith: []string{"account_password"},
},
"account_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Normal", "Super"}, false),
ConflictsWith: []string{"type"},
},
"type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Normal", "Super"}, false),
Deprecated: "Field 'type' has been deprecated from provider version 1.120.0. New field 'account_type' instead.",
ConflictsWith: []string{"account_type"},
},
"db_instance_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"instance_id"},
},
"instance_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Deprecated: "Field 'instance_id' has been deprecated from provider version 1.120.0. New field 'db_instance_id' instead.",
ConflictsWith: []string{"db_instance_id"},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"kms_encrypted_password": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: kmsDiffSuppressFunc,
},
"kms_encryption_context": {
Type: schema.TypeMap,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("kms_encrypted_password").(string) == ""
},
Elem: schema.TypeString,
},
},
}
}
func resourceAlicloudRdsAccountCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
var response map[string]interface{}
action := "CreateAccount"
request := make(map[string]interface{})
request["SourceIp"] = client.SourceIp
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("account_description"); ok {
request["AccountDescription"] = v
} else if v, ok := d.GetOk("description"); ok {
request["AccountDescription"] = v
}
if v, ok := d.GetOk("account_name"); ok {
request["AccountName"] = v
} else if v, ok := d.GetOk("name"); ok {
request["AccountName"] = v
} else {
return WrapError(Error(`[ERROR] Argument "name" or "account_name" must be set one!`))
}
request["AccountPassword"] = d.Get("account_password")
if v, ok := d.GetOk("account_password"); ok {
request["AccountPassword"] = v
} else if v, ok := d.GetOk("password"); ok {
request["AccountPassword"] = v
} else if v, ok := d.GetOk("kms_encrypted_password"); ok {
kmsService := KmsService{client}
decryptResp, err := kmsService.Decrypt(v.(string), d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request["AccountPassword"] = decryptResp
} else {
return WrapError(Error("One of the 'account_password' and 'password' and 'kms_encrypted_password' should be set."))
}
if v, ok := d.GetOk("account_type"); ok {
request["AccountType"] = v
} else if v, ok := d.GetOk("type"); ok {
request["AccountType"] = v
}
if v, ok := d.GetOk("db_instance_id"); ok {
request["DBInstanceId"] = v
} else if v, ok := d.GetOk("instance_id"); ok {
request["DBInstanceId"] = v
} else {
return WrapError(Error(`[ERROR] Argument "instance_id" or "db_instance_id" must be set one!`))
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"InternalError", "OperationDenied.DBClusterStatus", "OperationDenied.DBInstanceStatus", "OperationDenied.DBStatus", "OperationDenied.OutofUsage"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_rds_account", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["DBInstanceId"], ":", request["AccountName"]))
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, rdsService.RdsAccountStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudRdsAccountRead(d, meta)
}
func resourceAlicloudRdsAccountRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
object, err := rdsService.DescribeRdsAccount(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_rds_account rdsService.DescribeRdsAccount Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("account_name", parts[1])
d.Set("name", parts[1])
d.Set("db_instance_id", parts[0])
d.Set("instance_id", parts[0])
d.Set("account_description", object["AccountDescription"])
d.Set("description", object["AccountDescription"])
d.Set("account_type", object["AccountType"])
d.Set("type", object["AccountType"])
d.Set("status", object["AccountStatus"])
return nil
}
func resourceAlicloudRdsAccountUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Partial(true)
update := false
request := map[string]interface{}{
"AccountName": parts[1],
"DBInstanceId": parts[0],
"SourceIp": client.SourceIp,
}
if d.HasChange("account_description") {
update = true
request["AccountDescription"] = d.Get("account_description")
} else if d.HasChange("description") {
update = true
request["AccountDescription"] = d.Get("description")
}
if update {
action := "ModifyAccountDescription"
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, rdsService.RdsAccountStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("description")
d.SetPartial("account_description")
}
update = false
resetAccountPasswordReq := map[string]interface{}{
"AccountName": parts[1],
"DBInstanceId": parts[0],
"SourceIp": client.SourceIp,
}
if d.HasChange("account_password") {
update = true
resetAccountPasswordReq["AccountPassword"] = d.Get("account_password").(string)
} else if d.HasChange("password") {
update = true
resetAccountPasswordReq["AccountPassword"] = d.Get("password").(string)
} else if d.HasChange("kms_encrypted_password") {
update = true
kmsPassword := d.Get("kms_encrypted_password").(string)
kmsService := KmsService{meta.(*connectivity.AliyunClient)}
decryptResp, err := kmsService.Decrypt(kmsPassword, d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return WrapError(err)
}
resetAccountPasswordReq["AccountPassword"] = decryptResp
}
if update {
action := "ResetAccountPassword"
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, resetAccountPasswordReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, resetAccountPasswordReq)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, rdsService.RdsAccountStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("password")
d.SetPartial("kms_encrypted_password")
d.SetPartial("kms_encryption_context")
d.SetPartial("account_password")
}
d.Partial(false)
return resourceAlicloudRdsAccountRead(d, meta)
}
func resourceAlicloudRdsAccountDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
rdsService := RdsService{client}
action := "DeleteAccount"
var response map[string]interface{}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AccountName": parts[1],
"DBInstanceId": parts[0],
"SourceIp": client.SourceIp,
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) && IsExpectedErrors(err, []string{"InternalError", "OperationDenied.DBClusterStatus", "OperationDenied.DBInstanceStatus", "OperationDenied.DBStatus"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
object, err := rdsService.DescribeRdsAccount(d.Id())
if err != nil {
if NotFoundError(err) {
return nil
}
return resource.NonRetryableError(err)
}
if fmt.Sprint(object["AccountStatus"]) == "Lock" {
action = "UnlockAccount"
wait = incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return resource.NonRetryableError(err)
}
action = "DeleteAccount"
return resource.RetryableError(fmt.Errorf("there need to delete account %s again after unlock it", d.Id()))
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, rdsService.RdsAccountStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudRdsBackup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRdsBackupCreate,
Read: resourceAlicloudRdsBackupRead,
Update: resourceAlicloudRdsBackupUpdate,
Delete: resourceAlicloudRdsBackupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(20 * time.Minute),
Delete: schema.DefaultTimeout(20 * time.Minute),
},
Schema: map[string]*schema.Schema{
"backup_method": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"backup_strategy": {
Type: schema.TypeString,
Optional: true,
},
"backup_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"db_instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"db_name": {
Type: schema.TypeString,
Optional: true,
},
"backup_id": {
Type: schema.TypeString,
Computed: true,
},
"remove_from_state": {
Type: schema.TypeBool,
Optional: true,
},
"store_status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudRdsBackupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
var response map[string]interface{}
action := "CreateBackup"
request := make(map[string]interface{})
request["SourceIp"] = client.SourceIp
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("backup_method"); ok {
request["BackupMethod"] = v
}
if v, ok := d.GetOk("backup_strategy"); ok {
request["BackupStrategy"] = v
}
if v, ok := d.GetOk("backup_type"); ok {
request["BackupType"] = v
}
request["DBInstanceId"] = d.Get("db_instance_id")
if v, ok := d.GetOk("db_name"); ok {
request["DBName"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_rds_backup", action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Finished"}, d.Timeout(schema.TimeoutCreate), 20*time.Second, rdsService.RdsBackupStateRefreshFunc(d.Get("db_instance_id").(string), response["BackupJobId"].(string), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
// Wait one minute because the query API(DescribeBackups) has not been synchronized when the backup status is Finished
time.Sleep(1 * time.Minute)
object, err := rdsService.DescribeBackupTasks(d.Get("db_instance_id").(string), response["BackupJobId"].(string))
d.SetId(fmt.Sprint(request["DBInstanceId"], ":", object["BackupId"].(string)))
return resourceAlicloudRdsBackupRead(d, meta)
}
func resourceAlicloudRdsBackupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
object, err := rdsService.DescribeRdsBackup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_rds_backup rdsService.DescribeRdsBackup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("backup_method", object["BackupMethod"])
d.Set("backup_type", object["BackupType"])
d.Set("db_instance_id", object["DBInstanceId"])
d.Set("backup_id", object["BackupId"])
d.Set("store_status", object["StoreStatus"])
return nil
}
func resourceAlicloudRdsBackupUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return resourceAlicloudRdsBackupRead(d, meta)
}
func resourceAlicloudRdsBackupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteBackup"
parts, err := ParseResourceId(d.Id(), 2)
if d.Get("store_status").(string) == "Disabled" {
if !d.Get("remove_from_state").(bool) {
return WrapError(Error("the resource can not be deleted at this time and you can set remove_from_state to true to remove it."))
} else {
return nil
}
}
var response map[string]interface{}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"BackupId": parts[1],
"DBInstanceId": parts[0],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudRdsCloneDbInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRdsCloneDbInstanceCreate,
Read: resourceAlicloudRdsCloneDbInstanceRead,
Update: resourceAlicloudRdsCloneDbInstanceUpdate,
Delete: resourceAlicloudRdsCloneDbInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(300 * time.Minute),
Update: schema.DefaultTimeout(30 * time.Minute),
Delete: schema.DefaultTimeout(20 * time.Minute),
},
Schema: map[string]*schema.Schema{
"acl": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"cert", "perfer", "verify-ca", "verify-full"}, false),
Computed: true,
},
"auto_upgrade_minor_version": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Auto", "Manual"}, false),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("engine").(string) != "MySQL"
},
},
"backup_id": {
Type: schema.TypeString,
Optional: true,
},
"backup_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"FullBackup", "IncrementalBackup"}, false),
},
"ca_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"aliyun", "custom"}, false),
Computed: true,
},
"category": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"AlwaysOn", "Basic", "Finance", "HighAvailability"}, false),
},
"certificate": {
Type: schema.TypeString,
Optional: true,
},
"client_ca_enabled": {
Type: schema.TypeInt,
Optional: true,
},
"client_ca_cert": {
Type: schema.TypeString,
Optional: true,
},
"client_cert_revocation_list": {
Type: schema.TypeString,
Optional: true,
},
"client_crl_enabled": {
Type: schema.TypeInt,
Optional: true,
},
"connection_string": {
Type: schema.TypeString,
Computed: true,
},
"connection_string_prefix": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(8, 64),
},
"db_instance_class": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"db_instance_description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"db_instance_storage": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"db_instance_storage_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"cloud_essd", "cloud_essd2", "cloud_essd3", "cloud_ssd", "local_ssd"}, false),
},
"db_name": {
Type: schema.TypeString,
Optional: true,
},
"db_names": {
Type: schema.TypeString,
Optional: true,
},
"dedicated_host_group_id": {
Type: schema.TypeString,
Optional: true,
},
"direction": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Auto", "Down", "TempUpgrade", "Up"}, false),
},
"effective_time": {
Type: schema.TypeString,
Optional: true,
},
"encryption_key": {
Type: schema.TypeString,
Optional: true,
},
"engine": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"engine_version": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"force_restart": {
Type: schema.TypeBool,
Optional: true,
},
"ha_mode": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"RPO", "RTO"}, false),
},
"instance_network_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Classic", "VPC"}, false),
Computed: true,
},
"maintain_time": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"password": {
Type: schema.TypeString,
Optional: true,
},
"payment_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo", "Subscription"}, false),
},
"period": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Month", "Year"}, false),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("payment_type").(string) != "Subscription"
},
},
"port": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"private_ip_address": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"private_key": {
Type: schema.TypeString,
Optional: true,
},
"released_keep_policy": {
Type: schema.TypeString,
Optional: true,
},
"replication_acl": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"cert", "perfer", "verify-ca", "verify-full"}, false),
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
},
"restore_table": {
Type: schema.TypeString,
Optional: true,
},
"restore_time": {
Type: schema.TypeString,
Optional: true,
},
"role_arn": {
Type: schema.TypeString,
Optional: true,
},
"security_ips": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
Optional: true,
},
"server_cert": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"server_key": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"source_biz": {
Type: schema.TypeString,
Optional: true,
},
"source_db_instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ssl_enabled": {
Type: schema.TypeInt,
ValidateFunc: validation.IntInSlice([]int{0, 1}),
Optional: true,
Computed: true,
},
"switch_time": {
Type: schema.TypeString,
Optional: true,
},
"sync_mode": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Async", "Semi-sync", "Sync"}, false),
},
"tde_status": {
Type: schema.TypeString,
Optional: true,
},
"table_meta": {
Type: schema.TypeString,
Optional: true,
},
"used_time": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 24, 36}),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("payment_type").(string) != "Subscription"
},
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"parameters": {
Type: schema.TypeSet,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"value": {
Type: schema.TypeString,
Required: true,
},
},
},
Set: parameterToHash,
Optional: true,
Computed: true,
},
},
}
}
func resourceAlicloudRdsCloneDbInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
var response map[string]interface{}
action := "CloneDBInstance"
request := make(map[string]interface{})
request["SourceIp"] = client.SourceIp
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("backup_id"); ok {
request["BackupId"] = v
}
if v, ok := d.GetOk("backup_type"); ok {
request["BackupType"] = v
}
if v, ok := d.GetOk("category"); ok {
request["Category"] = v
}
if v, ok := d.GetOk("db_instance_class"); ok {
request["DBInstanceClass"] = v
}
if v, ok := d.GetOk("db_instance_storage"); ok {
request["DBInstanceStorage"] = v
}
request["DBInstanceStorageType"] = d.Get("db_instance_storage_type")
if v, ok := d.GetOk("db_names"); ok {
request["DbNames"] = v
}
if v, ok := d.GetOk("dedicated_host_group_id"); ok {
request["DedicatedHostGroupId"] = v
}
if v, ok := d.GetOk("instance_network_type"); ok {
request["InstanceNetworkType"] = v
}
request["PayType"] = convertRdsInstancePaymentTypeRequest(d.Get("payment_type"))
if v, ok := d.GetOk("period"); ok {
request["Period"] = v
}
if v, ok := d.GetOk("private_ip_address"); ok {
request["PrivateIpAddress"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("restore_table"); ok {
request["RestoreTable"] = v
}
if v, ok := d.GetOk("restore_time"); ok {
request["RestoreTime"] = v
}
request["DBInstanceId"] = d.Get("source_db_instance_id")
if v, ok := d.GetOk("table_meta"); ok {
request["TableMeta"] = v
}
if v, ok := d.GetOk("used_time"); ok {
request["UsedTime"] = v
}
if v, ok := d.GetOk("zone_id"); ok {
request["ZoneId"] = v
}
if v, ok := d.GetOk("vpc_id"); ok {
request["VPCId"] = v
}
if v, ok := d.GetOk("vswitch_id"); ok {
request["VSwitchId"] = v
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"undefined"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_rds_clone_db_instance", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["DBInstanceId"]))
// wait instance status change from Creating to running
stateConf := BuildStateConf([]string{"Creating"}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 3*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudRdsCloneDbInstanceUpdate(d, meta)
}
func resourceAlicloudRdsCloneDbInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
object, err := rdsService.DescribeRdsCloneDbInstance(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_rds_clone_db_instance rdsService.DescribeRdsCloneDbInstance Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("auto_upgrade_minor_version", object["AutoUpgradeMinorVersion"])
d.Set("category", object["Category"])
d.Set("db_instance_class", object["DBInstanceClass"])
d.Set("db_instance_description", object["DBInstanceDescription"])
if v, ok := object["DBInstanceStorage"]; ok && fmt.Sprint(v) != "0" {
d.Set("db_instance_storage", formatInt(v))
}
d.Set("db_instance_storage_type", object["DBInstanceStorageType"])
d.Set("dedicated_host_group_id", object["DedicatedHostGroupId"])
d.Set("engine", object["Engine"])
d.Set("engine_version", object["EngineVersion"])
d.Set("instance_network_type", object["InstanceNetworkType"])
d.Set("maintain_time", object["MaintainTime"])
d.Set("vswitch_id", object["VSwitchId"])
d.Set("zone_id", object["ZoneId"])
d.Set("payment_type", convertRdsInstancePaymentTypeResponse(object["PayType"]))
d.Set("port", object["Port"])
d.Set("connection_string", object["ConnectionString"])
if err = rdsService.RefreshParameters(d, "parameters"); err != nil {
return WrapError(err)
}
describeDBInstanceHAConfigObject, err := rdsService.DescribeDBInstanceHAConfig(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("sync_mode", describeDBInstanceHAConfigObject["SyncMode"])
d.Set("ha_mode", describeDBInstanceHAConfigObject["HAMode"])
dbInstanceIpArrayName := "default"
describeDBInstanceIPArrayListObject, err := rdsService.GetSecurityIps(d.Id(), dbInstanceIpArrayName)
if err != nil {
return WrapError(err)
}
d.Set("security_ips", describeDBInstanceIPArrayListObject)
describeDBInstanceNetInfoObject, err := rdsService.DescribeDBInstanceNetInfo(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("private_ip_address", describeDBInstanceNetInfoObject[0].(map[string]interface{})["IPAddress"])
describeDBInstanceSSLObject, err := rdsService.DescribeDBInstanceSSL(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("acl", describeDBInstanceSSLObject["ACL"])
d.Set("ca_type", describeDBInstanceSSLObject["CAType"])
d.Set("client_ca_cert", describeDBInstanceSSLObject["ClientCACert"])
d.Set("client_cert_revocation_list", describeDBInstanceSSLObject["ClientCertRevocationList"])
d.Set("replication_acl", describeDBInstanceSSLObject["ReplicationACL"])
d.Set("server_cert", describeDBInstanceSSLObject["ServerCert"])
d.Set("server_key", describeDBInstanceSSLObject["ServerKey"])
if v, ok := describeDBInstanceSSLObject["SSLEnabled"]; ok && v.(string) != "" {
sslEnabled := 0
if v == "on" {
sslEnabled = 1
}
d.Set("ssl_enabled'", sslEnabled)
}
return nil
}
func resourceAlicloudRdsCloneDbInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
var response map[string]interface{}
d.Partial(true)
if d.HasChange("parameters") {
if err := rdsService.ModifyParameters(d, "parameters"); err != nil {
return WrapError(err)
}
}
update := false
request := map[string]interface{}{
"DBInstanceId": d.Id(),
}
if d.HasChange("auto_upgrade_minor_version") {
update = true
}
if v, ok := d.GetOk("auto_upgrade_minor_version"); ok {
request["AutoUpgradeMinorVersion"] = v
}
if update {
action := "ModifyDBInstanceAutoUpgradeMinorVersion"
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("ModifyDBInstanceAutoUpgradeMinorVersion")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("auto_upgrade_minor_version")
}
update = false
modifyDBInstanceDescriptionReq := map[string]interface{}{
"DBInstanceId": d.Id(),
}
if d.HasChange("db_instance_description") {
update = true
}
if v, ok := d.GetOk("db_instance_description"); ok {
modifyDBInstanceDescriptionReq["DBInstanceDescription"] = v
}
if update {
action := "ModifyDBInstanceDescription"
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, modifyDBInstanceDescriptionReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyDBInstanceDescriptionReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("db_instance_description")
}
update = false
modifyDBInstanceMaintainTimeReq := map[string]interface{}{
"DBInstanceId": d.Id(),
}
if d.HasChange("maintain_time") {
update = true
}
if v, ok := d.GetOk("maintain_time"); ok {
modifyDBInstanceMaintainTimeReq["MaintainTime"] = v
}
if update {
action := "ModifyDBInstanceMaintainTime"
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("ModifyDBInstanceMaintainTime")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, modifyDBInstanceMaintainTimeReq, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyDBInstanceMaintainTimeReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("maintain_time")
}
update = false
modifyDBInstanceHAConfigReq := map[string]interface{}{
"DbInstanceId": d.Id(),
}
if d.HasChange("sync_mode") {
update = true
}
if d.HasChange("ha_mode") {
update = true
}
if update {
if v, ok := d.GetOk("sync_mode"); ok {
modifyDBInstanceHAConfigReq["SyncMode"] = v
}
if v, ok := d.GetOk("ha_mode"); ok {
modifyDBInstanceHAConfigReq["HAMode"] = v
}
action := "ModifyDBInstanceHAConfig"
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, modifyDBInstanceHAConfigReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyDBInstanceHAConfigReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("sync_mode")
}
update = false
switchDBInstanceVpcReq := map[string]interface{}{
"DBInstanceId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("private_ip_address") {
update = true
if v, ok := d.GetOk("private_ip_address"); ok {
switchDBInstanceVpcReq["PrivateIpAddress"] = v
}
}
if !d.IsNewResource() && d.HasChange("vpc_id") {
update = true
if v, ok := d.GetOk("vpc_id"); ok {
switchDBInstanceVpcReq["VPCId"] = v
}
}
if !d.IsNewResource() && d.HasChange("vswitch_id") {
update = true
if v, ok := d.GetOk("vswitch_id"); ok {
switchDBInstanceVpcReq["VSwitchId"] = v
}
}
if update {
action := "SwitchDBInstanceVpc"
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, switchDBInstanceVpcReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, switchDBInstanceVpcReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
// wait instance status change from Creating to running
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 3*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("private_ip_address")
d.SetPartial("vpc_id")
d.SetPartial("vswitch_id")
}
update = false
modifyDBInstanceConnectionStringReq := map[string]interface{}{
"DBInstanceId": d.Id(),
}
if d.HasChange("port") {
update = true
}
if d.HasChange("connection_string_prefix") {
update = true
}
if v, ok := d.GetOk("connection_string"); ok {
modifyDBInstanceConnectionStringReq["CurrentConnectionString"] = v
}
if update {
if v, ok := d.GetOk("connection_string_prefix"); ok {
modifyDBInstanceConnectionStringReq["ConnectionStringPrefix"] = v
}
if v, ok := d.GetOk("port"); ok {
modifyDBInstanceConnectionStringReq["Port"] = v
}
action := "ModifyDBInstanceConnectionString"
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, modifyDBInstanceConnectionStringReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyDBInstanceConnectionStringReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
// wait instance status change from Creating to running
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 3*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("connection_string")
}
update = false
modifyDBInstanceTDEReq := map[string]interface{}{
"DBInstanceId": d.Id(),
}
if d.HasChange("encryption_key") {
update = true
if v, ok := d.GetOk("encryption_key"); ok {
modifyDBInstanceTDEReq["EncryptionKey"] = v
}
}
if update {
if v, ok := d.GetOk("tde_status"); ok {
modifyDBInstanceTDEReq["TDEStatus"] = v
}
if v, ok := d.GetOk("certificate"); ok {
modifyDBInstanceTDEReq["Certificate"] = v
}
if v, ok := d.GetOk("db_name"); ok {
modifyDBInstanceTDEReq["DBName"] = v
}
if v, ok := d.GetOk("password"); ok {
modifyDBInstanceTDEReq["PassWord"] = v
}
if v, ok := d.GetOk("private_key"); ok {
modifyDBInstanceTDEReq["PrivateKey"] = v
}
if v, ok := d.GetOk("role_arn"); ok {
modifyDBInstanceTDEReq["RoleArn"] = v
}
action := "ModifyDBInstanceTDE"
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, modifyDBInstanceTDEReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyDBInstanceTDEReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
// wait instance status change from Creating to running
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 3*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("encryption_key")
}
update = false
modifySecurityIpsReq := map[string]interface{}{
"DBInstanceId": d.Id(),
}
if d.HasChange("security_ips") {
update = true
ipList := expandStringList(d.Get("security_ips").(*schema.Set).List())
ipstr := strings.Join(ipList[:], COMMA_SEPARATED)
// default disable connect from outside
if ipstr == "" {
ipstr = LOCAL_HOST_IP
}
modifySecurityIpsReq["SecurityIps"] = ipstr
}
if update {
action := "ModifySecurityIps"
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, modifySecurityIpsReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifySecurityIpsReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("security_ips")
}
update = false
modifyDBInstanceSSLReq := map[string]interface{}{
"DBInstanceId": d.Id(),
}
if v, ok := d.GetOk("connection_string"); ok {
modifyDBInstanceSSLReq["ConnectionString"] = v
}
if d.HasChange("acl") {
update = true
if v, ok := d.GetOk("acl"); ok {
modifyDBInstanceSSLReq["ACL"] = v
}
}
if d.HasChange("ca_type") {
update = true
if v, ok := d.GetOk("ca_type"); ok {
modifyDBInstanceSSLReq["CAType"] = v
}
}
if d.HasChange("client_ca_cert") {
update = true
if v, ok := d.GetOk("client_ca_cert"); ok {
modifyDBInstanceSSLReq["ClientCACert"] = v
}
}
if d.HasChange("client_cert_revocation_list") {
update = true
if v, ok := d.GetOk("client_cert_revocation_list"); ok {
modifyDBInstanceSSLReq["ClientCertRevocationList"] = v
}
}
if d.HasChange("replication_acl") {
update = true
if v, ok := d.GetOk("replication_acl"); ok {
modifyDBInstanceSSLReq["ReplicationACL"] = v
}
}
if d.HasChange("server_cert") {
update = true
if v, ok := d.GetOk("server_cert"); ok {
modifyDBInstanceSSLReq["ServerCert"] = v
}
}
if d.HasChange("server_key") {
update = true
if v, ok := d.GetOk("server_key"); ok {
modifyDBInstanceSSLReq["ServerKey"] = v
}
}
if d.HasChange("client_ca_enabled") {
update = true
if v, ok := d.GetOk("client_ca_enabled"); ok {
modifyDBInstanceSSLReq["ClientCAEnabled"] = v
}
}
if d.HasChange("client_crl_enabled") {
update = true
if v, ok := d.GetOk("client_crl_enabled"); ok {
modifyDBInstanceSSLReq["ClientCrlEnabled"] = v
}
}
if d.HasChange("ssl_enabled") {
update = true
if v, ok := d.GetOk("ssl_enabled"); ok {
modifyDBInstanceSSLReq["SSLEnabled"] = v
}
}
if update {
action := "ModifyDBInstanceSSL"
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, modifyDBInstanceSSLReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyDBInstanceSSLReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
// wait instance status change from Creating to running
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 3*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("connection_string")
d.SetPartial("acl")
d.SetPartial("ca_type")
d.SetPartial("client_ca_cert")
d.SetPartial("client_cert_revocation_list")
d.SetPartial("replication_acl")
d.SetPartial("server_cert")
d.SetPartial("server_key")
d.SetPartial("ssl_enabled")
}
update = false
modifyDBInstanceSpecReq := map[string]interface{}{
"DBInstanceId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("payment_type") {
update = true
}
if v, ok := d.GetOk("payment_type"); ok {
modifyDBInstanceSpecReq["PayType"] = convertRdsInstancePaymentTypeRequest(v)
}
if !d.IsNewResource() && d.HasChange("db_instance_class") {
update = true
if v, ok := d.GetOk("db_instance_class"); ok {
modifyDBInstanceSpecReq["DBInstanceClass"] = v
}
}
if !d.IsNewResource() && d.HasChange("db_instance_storage") {
update = true
if v, ok := d.GetOk("db_instance_storage"); ok {
modifyDBInstanceSpecReq["DBInstanceStorage"] = v
}
}
if !d.IsNewResource() && d.HasChange("db_instance_storage_type") {
update = true
modifyDBInstanceSpecReq["DBInstanceStorageType"] = d.Get("db_instance_storage_type")
}
if !d.IsNewResource() && d.HasChange("dedicated_host_group_id") {
update = true
if v, ok := d.GetOk("dedicated_host_group_id"); ok {
modifyDBInstanceSpecReq["DedicatedHostGroupId"] = v
}
}
if d.HasChange("engine_version") {
update = true
if v, ok := d.GetOk("engine_version"); ok {
modifyDBInstanceSpecReq["EngineVersion"] = v
}
}
if !d.IsNewResource() && d.HasChange("zone_id") {
update = true
if v, ok := d.GetOk("zone_id"); ok {
modifyDBInstanceSpecReq["ZoneId"] = v
}
}
if update {
if v, ok := d.GetOk("direction"); ok {
modifyDBInstanceSpecReq["Direction"] = v
}
if v, ok := d.GetOk("effective_time"); ok {
modifyDBInstanceSpecReq["EffectiveTime"] = v
}
if v, ok := d.GetOk("resource_group_id"); ok {
modifyDBInstanceSpecReq["ResourceGroupId"] = v
}
if v, ok := d.GetOk("source_biz"); ok {
modifyDBInstanceSpecReq["SourceBiz"] = v
}
if v, ok := d.GetOk("switch_time"); ok {
modifyDBInstanceSpecReq["SwitchTime"] = v
}
if v, ok := d.GetOk("used_time"); ok {
modifyDBInstanceSpecReq["UsedTime"] = v
}
action := "ModifyDBInstanceSpec"
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, modifyDBInstanceSpecReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyDBInstanceSpecReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
// wait instance status change from Creating to running
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 3*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("db_instance_class")
d.SetPartial("db_instance_storage")
d.SetPartial("db_instance_storage_type")
d.SetPartial("dedicated_host_group_id")
d.SetPartial("engine_version")
d.SetPartial("zone_id")
}
d.Partial(false)
return resourceAlicloudRdsCloneDbInstanceRead(d, meta)
}
func resourceAlicloudRdsCloneDbInstanceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteDBInstance"
var response map[string]interface{}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DBInstanceId": d.Id(),
}
request[""] = client.RegionId
if v, ok := d.GetOk("released_keep_policy"); ok {
request["ReleasedKeepPolicy"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func convertRdsInstancePaymentTypeRequest(source interface{}) interface{} {
switch source {
case "PayAsYouGo":
return "Postpaid"
case "Subscription":
return "Prepaid"
}
return source
}
func convertRdsInstancePaymentTypeResponse(source interface{}) interface{} {
switch source {
case "Postpaid":
return "PayAsYouGo"
case "Prepaid":
return "Subscription"
}
return source
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudRdsParameterGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRdsParameterGroupCreate,
Read: resourceAlicloudRdsParameterGroupRead,
Update: resourceAlicloudRdsParameterGroupUpdate,
Delete: resourceAlicloudRdsParameterGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"engine": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"mariadb", "mysql"}, false),
},
"engine_version": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"10.3", "5.1", "5.5", "5.6", "5.7", "8.0"}, false),
},
"param_detail": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"param_name": {
Type: schema.TypeString,
Required: true,
},
"param_value": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"parameter_group_desc": {
Type: schema.TypeString,
Optional: true,
},
"parameter_group_name": {
Type: schema.TypeString,
Required: true,
},
},
}
}
func resourceAlicloudRdsParameterGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateParameterGroup"
request := make(map[string]interface{})
request["SourceIp"] = client.SourceIp
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
request["Engine"] = d.Get("engine")
request["EngineVersion"] = d.Get("engine_version")
list := d.Get("param_detail").(*schema.Set).List()
paramMap := map[string]interface{}{}
for _, v := range list {
v := v.(map[string]interface{})
paramMap[v["param_name"].(string)] = v["param_value"]
}
paramStr, _ := convertMaptoJsonString(paramMap)
request["Parameters"] = paramStr
if v, ok := d.GetOk("parameter_group_desc"); ok {
request["ParameterGroupDesc"] = v
}
request["ParameterGroupName"] = d.Get("parameter_group_name")
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_rds_parameter_group", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["ParameterGroupId"]))
return resourceAlicloudRdsParameterGroupRead(d, meta)
}
func resourceAlicloudRdsParameterGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
object, err := rdsService.DescribeRdsParameterGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_rds_parameter_group rdsService.DescribeRdsParameterGroup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("engine", object["Engine"])
d.Set("engine_version", object["EngineVersion"])
if v, ok := object["ParamDetail"].(map[string]interface{})["ParameterDetail"].([]interface{}); ok {
parameterDetail := make([]map[string]interface{}, 0)
for _, val := range v {
item := val.(map[string]interface{})
parameterDetail = append(parameterDetail, map[string]interface{}{
"param_name": item["ParamName"],
"param_value": item["ParamValue"],
})
}
if err := d.Set("param_detail", parameterDetail); err != nil {
return WrapError(err)
}
}
d.Set("parameter_group_desc", object["ParameterGroupDesc"])
d.Set("parameter_group_name", object["ParameterGroupName"])
return nil
}
func resourceAlicloudRdsParameterGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"ParameterGroupId": d.Id(),
"SourceIp": client.SourceIp,
}
request["RegionId"] = client.RegionId
if d.HasChange("param_detail") {
update = true
list := d.Get("param_detail").(*schema.Set).List()
paramMap := map[string]interface{}{}
for _, v := range list {
v := v.(map[string]interface{})
paramMap[v["param_name"].(string)] = v["param_value"]
}
paramStr, _ := convertMaptoJsonString(paramMap)
request["Parameters"] = paramStr
}
if d.HasChange("parameter_group_desc") {
update = true
request["ParameterGroupDesc"] = d.Get("parameter_group_desc")
}
if d.HasChange("parameter_group_name") {
update = true
request["ParameterGroupName"] = d.Get("parameter_group_name")
}
if update {
action := "ModifyParameterGroup"
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudRdsParameterGroupRead(d, meta)
}
func resourceAlicloudRdsParameterGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteParameterGroup"
var response map[string]interface{}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ParameterGroupId": d.Id(),
"SourceIp": client.SourceIp,
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudRdsUpgradeDbInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRdsUpgradeDbInstanceCreate,
Read: resourceAlicloudRdsUpgradeDbInstanceRead,
Update: resourceAlicloudRdsUpgradeDbInstanceUpdate,
Delete: resourceAlicloudRdsUpgradeDbInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(300 * time.Minute),
Update: schema.DefaultTimeout(30 * time.Minute),
Delete: schema.DefaultTimeout(20 * time.Minute),
},
Schema: map[string]*schema.Schema{
"acl": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"cert", "perfer", "verify-ca", "verify-full"}, false),
Computed: true,
},
"auto_upgrade_minor_version": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Auto", "Manual"}, false),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("engine").(string) != "MySQL"
},
},
"ca_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"aliyun", "custom"}, false),
Computed: true,
},
"certificate": {
Type: schema.TypeString,
Optional: true,
},
"client_ca_enabled": {
Type: schema.TypeInt,
Optional: true,
},
"client_ca_cert": {
Type: schema.TypeString,
Optional: true,
},
"client_cert_revocation_list": {
Type: schema.TypeString,
Optional: true,
},
"client_crl_enabled": {
Type: schema.TypeInt,
Optional: true,
},
"connection_string": {
Type: schema.TypeString,
Computed: true,
},
"connection_string_prefix": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(8, 64),
},
"db_instance_class": {
Type: schema.TypeString,
Required: true,
},
"db_instance_description": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"db_instance_storage": {
Type: schema.TypeInt,
Required: true,
},
"db_instance_storage_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"cloud_essd", "cloud_essd2", "cloud_essd3", "cloud_ssd", "local_ssd"}, false),
},
"db_name": {
Type: schema.TypeString,
Optional: true,
},
"dedicated_host_group_id": {
Type: schema.TypeString,
Optional: true,
},
"direction": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Auto", "Down", "TempUpgrade", "Up"}, false),
},
"effective_time": {
Type: schema.TypeString,
Optional: true,
},
"encryption_key": {
Type: schema.TypeString,
Optional: true,
},
"engine": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"engine_version": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"force_restart": {
Type: schema.TypeBool,
Optional: true,
},
"ha_mode": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"RPO", "RTO"}, false),
},
"instance_network_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Classic", "VPC"}, false),
},
"maintain_time": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"password": {
Type: schema.TypeString,
Optional: true,
},
"payment_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo", "Subscription"}, false),
},
"port": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"private_ip_address": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"private_key": {
Type: schema.TypeString,
Optional: true,
},
"released_keep_policy": {
Type: schema.TypeString,
Optional: true,
},
"replication_acl": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"cert", "perfer", "verify-ca", "verify-full"}, false),
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
},
"role_arn": {
Type: schema.TypeString,
Optional: true,
},
"security_ips": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
Optional: true,
},
"server_cert": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"server_key": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"source_biz": {
Type: schema.TypeString,
Optional: true,
},
"source_db_instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ssl_enabled": {
Type: schema.TypeInt,
ValidateFunc: validation.IntInSlice([]int{0, 1}),
Optional: true,
Computed: true,
},
"switch_time": {
Type: schema.TypeString,
Optional: true,
},
"sync_mode": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Async", "Semi-sync", "Sync"}, false),
},
"tde_status": {
Type: schema.TypeString,
Optional: true,
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"zone_id_slave_1": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"switch_time_mode": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Immediate", "MaintainTime"}, false),
},
"switch_over": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"true", "false"}, false),
},
"collect_stat_mode": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"Before", "After"}, false),
},
"target_major_version": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"parameters": {
Type: schema.TypeSet,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"value": {
Type: schema.TypeString,
Required: true,
},
},
},
Set: parameterToHash,
Optional: true,
Computed: true,
},
},
}
}
func resourceAlicloudRdsUpgradeDbInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
conn, err := client.NewRdsClient()
action := "UpgradeDBInstanceMajorVersionPrecheck"
request := map[string]interface{}{
"RegionId": client.RegionId,
"DBInstanceId": d.Get("source_db_instance_id"),
"SourceIp": client.SourceIp,
}
if v, ok := d.GetOk("target_major_version"); ok && v.(string) != "" {
request["TargetMajorVersion"] = v
}
var response map[string]interface{}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
stateConf := BuildStateConf([]string{}, []string{"Success"}, d.Timeout(schema.TimeoutCreate), 3*time.Second, rdsService.RdsUpgradeMajorVersionRefreshFunc(d.Get("source_db_instance_id").(string), formatInt(response["TaskId"]), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
action = "UpgradeDBInstanceMajorVersion"
request = make(map[string]interface{})
request["SourceIp"] = client.SourceIp
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("db_instance_class"); ok {
request["DBInstanceClass"] = v
}
if v, ok := d.GetOk("db_instance_storage"); ok {
request["DBInstanceStorage"] = v
}
request["PayType"] = convertRdsInstancePaymentTypeRequest(d.Get("payment_type"))
if v, ok := d.GetOk("instance_network_type"); ok {
request["InstanceNetworkType"] = v
}
if v, ok := d.GetOk("switch_time_mode"); ok {
request["SwitchTimeMode"] = v
}
if v, ok := d.GetOk("switch_over"); ok {
request["SwitchOver"] = v
}
if v, ok := d.GetOk("collect_stat_mode"); ok {
request["CollectStatMode"] = v
}
if v, ok := d.GetOk("target_major_version"); ok {
request["TargetMajorVersion"] = v
}
request["DBInstanceId"] = d.Get("source_db_instance_id")
if v, ok := d.GetOk("vpc_id"); ok {
request["VPCId"] = v
}
if v, ok := d.GetOk("vswitch_id"); ok {
request["VSwitchId"] = v
}
if v, ok := d.GetOk("private_ip_address"); ok {
request["PrivateIpAddress"] = v
}
request["DBInstanceStorageType"] = d.Get("db_instance_storage_type")
if v, ok := d.GetOk("zone_id"); ok {
request["ZoneId"] = v
}
if v, ok := d.GetOk("zone_id_slave_1"); ok {
request["ZoneIdSlave1"] = v
}
wait = incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_rds_upgrade_db_instance", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["DBInstanceId"]))
// wait instance status change from Creating to running
stateConf = BuildStateConf([]string{"Creating"}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 3*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudRdsUpgradeDbInstanceUpdate(d, meta)
}
func resourceAlicloudRdsUpgradeDbInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
object, err := rdsService.DescribeRdsCloneDbInstance(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_rds_upgrade_db_instance rdsService.DescribeRdsCloneDbInstance Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("auto_upgrade_minor_version", object["AutoUpgradeMinorVersion"])
d.Set("db_instance_class", object["DBInstanceClass"])
d.Set("db_instance_description", object["DBInstanceDescription"])
if v, ok := object["DBInstanceStorage"]; ok && fmt.Sprint(v) != "0" {
d.Set("db_instance_storage", formatInt(v))
}
d.Set("db_instance_storage_type", object["DBInstanceStorageType"])
d.Set("dedicated_host_group_id", object["DedicatedHostGroupId"])
d.Set("engine", object["Engine"])
d.Set("engine_version", object["EngineVersion"])
d.Set("instance_network_type", object["InstanceNetworkType"])
d.Set("maintain_time", object["MaintainTime"])
d.Set("vpc_id", object["VpcId"])
d.Set("vswitch_id", object["VSwitchId"])
d.Set("zone_id", object["ZoneId"])
if len(object["SlaveZones"].(map[string]interface{})["SlaveZone"].([]interface{})) > 0 {
d.Set("zone_id_slave_1", object["SlaveZones"].(map[string]interface{})["SlaveZone"].([]interface{})[0].(map[string]interface{})["ZoneId"])
}
d.Set("payment_type", convertRdsInstancePaymentTypeResponse(object["PayType"]))
d.Set("port", object["Port"])
d.Set("connection_string", object["ConnectionString"])
if err = rdsService.RefreshParameters(d, "parameters"); err != nil {
return WrapError(err)
}
describeDBInstanceHAConfigObject, err := rdsService.DescribeDBInstanceHAConfig(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("sync_mode", describeDBInstanceHAConfigObject["SyncMode"])
d.Set("ha_mode", describeDBInstanceHAConfigObject["HAMode"])
dbInstanceIpArrayName := "default"
describeDBInstanceIPArrayListObject, err := rdsService.GetSecurityIps(d.Id(), dbInstanceIpArrayName)
if err != nil {
return WrapError(err)
}
d.Set("security_ips", describeDBInstanceIPArrayListObject)
describeDBInstanceNetInfoObject, err := rdsService.DescribeDBInstanceNetInfo(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("private_ip_address", describeDBInstanceNetInfoObject[0].(map[string]interface{})["IPAddress"])
describeDBInstanceSSLObject, err := rdsService.DescribeDBInstanceSSL(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("acl", describeDBInstanceSSLObject["ACL"])
d.Set("ca_type", describeDBInstanceSSLObject["CAType"])
d.Set("client_ca_cert", describeDBInstanceSSLObject["ClientCACert"])
d.Set("client_cert_revocation_list", describeDBInstanceSSLObject["ClientCertRevocationList"])
d.Set("replication_acl", describeDBInstanceSSLObject["ReplicationACL"])
d.Set("server_cert", describeDBInstanceSSLObject["ServerCert"])
d.Set("server_key", describeDBInstanceSSLObject["ServerKey"])
if v, ok := describeDBInstanceSSLObject["SSLEnabled"]; ok && v.(string) != "" {
sslEnabled := 0
if v == "on" {
sslEnabled = 1
}
d.Set("ssl_enabled'", sslEnabled)
}
return nil
}
func resourceAlicloudRdsUpgradeDbInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
var response map[string]interface{}
d.Partial(true)
if d.HasChange("parameters") {
if err := rdsService.ModifyParameters(d, "parameters"); err != nil {
return WrapError(err)
}
}
update := false
request := map[string]interface{}{
"DBInstanceId": d.Id(),
}
if d.HasChange("auto_upgrade_minor_version") {
update = true
}
if v, ok := d.GetOk("auto_upgrade_minor_version"); ok {
request["AutoUpgradeMinorVersion"] = v
}
if update {
action := "ModifyDBInstanceAutoUpgradeMinorVersion"
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("ModifyDBInstanceAutoUpgradeMinorVersion")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("auto_upgrade_minor_version")
}
update = false
modifyDBInstanceDescriptionReq := map[string]interface{}{
"DBInstanceId": d.Id(),
}
if d.HasChange("db_instance_description") {
update = true
}
if v, ok := d.GetOk("db_instance_description"); ok {
modifyDBInstanceDescriptionReq["DBInstanceDescription"] = v
}
if update {
action := "ModifyDBInstanceDescription"
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, modifyDBInstanceDescriptionReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyDBInstanceDescriptionReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("db_instance_description")
}
update = false
modifyDBInstanceMaintainTimeReq := map[string]interface{}{
"DBInstanceId": d.Id(),
}
if d.HasChange("maintain_time") {
update = true
}
if v, ok := d.GetOk("maintain_time"); ok {
modifyDBInstanceMaintainTimeReq["MaintainTime"] = v
}
if update {
action := "ModifyDBInstanceMaintainTime"
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("ModifyDBInstanceMaintainTime")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, modifyDBInstanceMaintainTimeReq, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyDBInstanceMaintainTimeReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("maintain_time")
}
update = false
modifyDBInstanceHAConfigReq := map[string]interface{}{
"DbInstanceId": d.Id(),
}
if d.HasChange("sync_mode") {
update = true
}
if d.HasChange("ha_mode") {
update = true
}
if update {
if v, ok := d.GetOk("sync_mode"); ok {
modifyDBInstanceHAConfigReq["SyncMode"] = v
}
if v, ok := d.GetOk("ha_mode"); ok {
modifyDBInstanceHAConfigReq["HAMode"] = v
}
action := "ModifyDBInstanceHAConfig"
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, modifyDBInstanceHAConfigReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyDBInstanceHAConfigReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("sync_mode")
}
update = false
switchDBInstanceVpcReq := map[string]interface{}{
"DBInstanceId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("private_ip_address") {
update = true
if v, ok := d.GetOk("private_ip_address"); ok {
switchDBInstanceVpcReq["PrivateIpAddress"] = v
}
}
if !d.IsNewResource() && d.HasChange("vpc_id") {
update = true
if v, ok := d.GetOk("vpc_id"); ok {
switchDBInstanceVpcReq["VPCId"] = v
}
}
if !d.IsNewResource() && d.HasChange("vswitch_id") {
update = true
if v, ok := d.GetOk("vswitch_id"); ok {
switchDBInstanceVpcReq["VSwitchId"] = v
}
}
if update {
action := "SwitchDBInstanceVpc"
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, switchDBInstanceVpcReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, switchDBInstanceVpcReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
// wait instance status change from Creating to running
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 3*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("private_ip_address")
d.SetPartial("vpc_id")
d.SetPartial("vswitch_id")
}
update = false
modifyDBInstanceConnectionStringReq := map[string]interface{}{
"DBInstanceId": d.Id(),
}
if d.HasChange("port") {
update = true
}
if d.HasChange("connection_string_prefix") {
update = true
}
if v, ok := d.GetOk("connection_string"); ok {
modifyDBInstanceConnectionStringReq["CurrentConnectionString"] = v
}
if update {
if v, ok := d.GetOk("connection_string_prefix"); ok {
modifyDBInstanceConnectionStringReq["ConnectionStringPrefix"] = v
}
if v, ok := d.GetOk("port"); ok {
modifyDBInstanceConnectionStringReq["Port"] = v
}
action := "ModifyDBInstanceConnectionString"
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, modifyDBInstanceConnectionStringReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyDBInstanceConnectionStringReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
// wait instance status change from Creating to running
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 3*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("connection_string")
}
update = false
modifyDBInstanceTDEReq := map[string]interface{}{
"DBInstanceId": d.Id(),
}
if d.HasChange("encryption_key") {
update = true
if v, ok := d.GetOk("encryption_key"); ok {
modifyDBInstanceTDEReq["EncryptionKey"] = v
}
}
if update {
if v, ok := d.GetOk("tde_status"); ok {
modifyDBInstanceTDEReq["TDEStatus"] = v
}
if v, ok := d.GetOk("certificate"); ok {
modifyDBInstanceTDEReq["Certificate"] = v
}
if v, ok := d.GetOk("db_name"); ok {
modifyDBInstanceTDEReq["DBName"] = v
}
if v, ok := d.GetOk("password"); ok {
modifyDBInstanceTDEReq["PassWord"] = v
}
if v, ok := d.GetOk("private_key"); ok {
modifyDBInstanceTDEReq["PrivateKey"] = v
}
if v, ok := d.GetOk("role_arn"); ok {
modifyDBInstanceTDEReq["RoleArn"] = v
}
action := "ModifyDBInstanceTDE"
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, modifyDBInstanceTDEReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyDBInstanceTDEReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
// wait instance status change from Creating to running
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 3*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("encryption_key")
}
update = false
modifySecurityIpsReq := map[string]interface{}{
"DBInstanceId": d.Id(),
}
if d.HasChange("security_ips") {
update = true
ipList := expandStringList(d.Get("security_ips").(*schema.Set).List())
ipstr := strings.Join(ipList[:], COMMA_SEPARATED)
if ipstr == "" {
ipstr = LOCAL_HOST_IP
}
modifySecurityIpsReq["SecurityIps"] = ipstr
}
if update {
action := "ModifySecurityIps"
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, modifySecurityIpsReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifySecurityIpsReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("security_ips")
}
update = false
modifyDBInstanceSSLReq := map[string]interface{}{
"DBInstanceId": d.Id(),
}
if v, ok := d.GetOk("connection_string"); ok {
modifyDBInstanceSSLReq["ConnectionString"] = v
}
if d.HasChange("acl") {
update = true
if v, ok := d.GetOk("acl"); ok {
modifyDBInstanceSSLReq["ACL"] = v
}
}
if d.HasChange("ca_type") {
update = true
if v, ok := d.GetOk("ca_type"); ok {
modifyDBInstanceSSLReq["CAType"] = v
}
}
if d.HasChange("client_ca_cert") {
update = true
if v, ok := d.GetOk("client_ca_cert"); ok {
modifyDBInstanceSSLReq["ClientCACert"] = v
}
}
if d.HasChange("client_cert_revocation_list") {
update = true
if v, ok := d.GetOk("client_cert_revocation_list"); ok {
modifyDBInstanceSSLReq["ClientCertRevocationList"] = v
}
}
if d.HasChange("replication_acl") {
update = true
if v, ok := d.GetOk("replication_acl"); ok {
modifyDBInstanceSSLReq["ReplicationACL"] = v
}
}
if d.HasChange("server_cert") {
update = true
if v, ok := d.GetOk("server_cert"); ok {
modifyDBInstanceSSLReq["ServerCert"] = v
}
}
if d.HasChange("server_key") {
update = true
if v, ok := d.GetOk("server_key"); ok {
modifyDBInstanceSSLReq["ServerKey"] = v
}
}
if d.HasChange("client_ca_enabled") {
update = true
if v, ok := d.GetOk("client_ca_enabled"); ok {
modifyDBInstanceSSLReq["ClientCAEnabled"] = v
}
}
if d.HasChange("client_crl_enabled") {
update = true
if v, ok := d.GetOk("client_crl_enabled"); ok {
modifyDBInstanceSSLReq["ClientCrlEnabled"] = v
}
}
if d.HasChange("ssl_enabled") {
update = true
if v, ok := d.GetOk("ssl_enabled"); ok {
modifyDBInstanceSSLReq["SSLEnabled"] = v
}
}
if update {
action := "ModifyDBInstanceSSL"
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, modifyDBInstanceSSLReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyDBInstanceSSLReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
// wait instance status change from Creating to running
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 3*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("connection_string")
d.SetPartial("acl")
d.SetPartial("ca_type")
d.SetPartial("client_ca_cert")
d.SetPartial("client_cert_revocation_list")
d.SetPartial("replication_acl")
d.SetPartial("server_cert")
d.SetPartial("server_key")
d.SetPartial("ssl_enabled")
}
update = false
modifyDBInstanceSpecReq := map[string]interface{}{
"DBInstanceId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("payment_type") {
update = true
}
if v, ok := d.GetOk("payment_type"); ok {
modifyDBInstanceSpecReq["PayType"] = convertRdsInstancePaymentTypeRequest(v)
}
if !d.IsNewResource() && d.HasChange("db_instance_class") {
update = true
if v, ok := d.GetOk("db_instance_class"); ok {
modifyDBInstanceSpecReq["DBInstanceClass"] = v
}
}
if !d.IsNewResource() && d.HasChange("db_instance_storage") {
update = true
if v, ok := d.GetOk("db_instance_storage"); ok {
modifyDBInstanceSpecReq["DBInstanceStorage"] = v
}
}
if !d.IsNewResource() && d.HasChange("db_instance_storage_type") {
update = true
modifyDBInstanceSpecReq["DBInstanceStorageType"] = d.Get("db_instance_storage_type")
}
if !d.IsNewResource() && d.HasChange("dedicated_host_group_id") {
update = true
if v, ok := d.GetOk("dedicated_host_group_id"); ok {
modifyDBInstanceSpecReq["DedicatedHostGroupId"] = v
}
}
if d.HasChange("engine_version") {
update = true
if v, ok := d.GetOk("engine_version"); ok {
modifyDBInstanceSpecReq["EngineVersion"] = v
}
}
if !d.IsNewResource() && d.HasChange("zone_id") {
update = true
if v, ok := d.GetOk("zone_id"); ok {
modifyDBInstanceSpecReq["ZoneId"] = v
}
}
if update {
if v, ok := d.GetOk("direction"); ok {
modifyDBInstanceSpecReq["Direction"] = v
}
if v, ok := d.GetOk("effective_time"); ok {
modifyDBInstanceSpecReq["EffectiveTime"] = v
}
if v, ok := d.GetOk("resource_group_id"); ok {
modifyDBInstanceSpecReq["ResourceGroupId"] = v
}
if v, ok := d.GetOk("source_biz"); ok {
modifyDBInstanceSpecReq["SourceBiz"] = v
}
if v, ok := d.GetOk("switch_time"); ok {
modifyDBInstanceSpecReq["SwitchTime"] = v
}
action := "ModifyDBInstanceSpec"
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, modifyDBInstanceSpecReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyDBInstanceSpecReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
// wait instance status change from Creating to running
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 3*time.Minute, rdsService.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("db_instance_class")
d.SetPartial("db_instance_storage")
d.SetPartial("db_instance_storage_type")
d.SetPartial("dedicated_host_group_id")
d.SetPartial("engine_version")
d.SetPartial("zone_id")
}
d.Partial(false)
return resourceAlicloudRdsUpgradeDbInstanceRead(d, meta)
}
func resourceAlicloudRdsUpgradeDbInstanceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteDBInstance"
var response map[string]interface{}
conn, err := client.NewRdsClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DBInstanceId": d.Id(),
"RegionId": client.RegionId,
"SourceIp": client.SourceIp,
}
if v, ok := d.GetOk("released_keep_policy"); ok {
request["ReleasedKeepPolicy"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"strings"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliCloudReservedInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAliCloudReservedInstanceCreate,
Read: resourceAliCloudReservedInstanceRead,
Update: resourceAliCloudReservedInstanceUpdate,
Delete: resourceAliCloudReservedInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"instance_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"scope": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "Region",
ValidateFunc: validation.StringInSlice([]string{"Region", "Zone"}, false),
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"instance_amount": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ForceNew: true,
},
"platform": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Windows", "Linux"}, false),
},
"period_unit": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "Year",
ValidateFunc: validation.StringInSlice([]string{"Year"}, false),
},
"period": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Default: 1,
ValidateFunc: validation.IntInSlice([]int{1, 3}),
},
"offering_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"No Upfront", "Partial Upfront", "All Upfront"}, false),
},
"name": {
Type: schema.TypeString,
Optional: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
}
}
func resourceAliCloudReservedInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
request := ecs.CreatePurchaseReservedInstancesOfferingRequest()
if v, ok := d.GetOk("instance_type"); ok {
request.InstanceType = v.(string)
}
request.RegionId = client.RegionId
if scope, ok := d.GetOk("scope"); ok {
request.Scope = scope.(string)
if v, ok := d.GetOk("zone_id"); ok {
if scope == "Zone" && v == "" {
return WrapError(Error("Required when Scope is Zone."))
}
request.ZoneId = v.(string)
}
}
if v, ok := d.GetOk("instance_amount"); ok {
request.InstanceAmount = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("platform"); ok {
request.Platform = v.(string)
}
if v, ok := d.GetOk("period_unit"); ok {
request.PeriodUnit = v.(string)
}
if v, ok := d.GetOk("period"); ok {
request.Period = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("offering_type"); ok {
request.OfferingType = v.(string)
}
if v, ok := d.GetOk("name"); ok {
request.ReservedInstanceName = v.(string)
}
if v, ok := d.GetOk("description"); ok {
request.Description = v.(string)
}
if v, ok := d.GetOk("resource_group_id"); ok {
request.ResourceGroupId = v.(string)
}
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.PurchaseReservedInstancesOffering(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_reserved_instance", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response := raw.(*ecs.PurchaseReservedInstancesOfferingResponse)
if len(response.ReservedInstanceIdSets.ReservedInstanceId) != 1 {
return WrapError(Error("API returned wrong number of collections"))
}
d.SetId(response.ReservedInstanceIdSets.ReservedInstanceId[0])
if err := ecsService.WaitForReservedInstance(d.Id(), Active, DefaultTimeout); err != nil {
return WrapError(err)
}
return resourceAliCloudReservedInstanceRead(d, meta)
}
func resourceAliCloudReservedInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ecs.CreateModifyReservedInstanceAttributeRequest()
request.ReservedInstanceId = d.Id()
request.RegionId = client.RegionId
if d.HasChange("name") || d.HasChange("description") {
if v, ok := d.GetOk("name"); ok {
request.ReservedInstanceName = v.(string)
}
if v, ok := d.GetOk("description"); ok {
request.Description = v.(string)
}
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ModifyReservedInstanceAttribute(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
return resourceAliCloudReservedInstanceRead(d, meta)
}
func resourceAliCloudReservedInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
reservedInstances, err := ecsService.DescribeReservedInstance(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("instance_type", reservedInstances.InstanceType)
d.Set("scope", reservedInstances.Scope)
d.Set("zone_id", reservedInstances.ZoneId)
d.Set("instance_amount", reservedInstances.InstanceAmount)
d.Set("platform", strings.Title(reservedInstances.Platform))
d.Set("offering_type", reservedInstances.OfferingType)
d.Set("name", reservedInstances.ReservedInstanceName)
d.Set("description", reservedInstances.Description)
d.Set("resource_group_id", reservedInstances.ReservedInstanceId)
return WrapError(err)
}
func resourceAliCloudReservedInstanceDelete(d *schema.ResourceData, meta interface{}) error {
// PurchaseReservedInstancesOffering can not be release.
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudResourceManagerAccount() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudResourceManagerAccountCreate,
Read: resourceAlicloudResourceManagerAccountRead,
Update: resourceAlicloudResourceManagerAccountUpdate,
Delete: resourceAlicloudResourceManagerAccountDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"account_name_prefix": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"display_name": {
Type: schema.TypeString,
Required: true,
},
"folder_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"join_method": {
Type: schema.TypeString,
Computed: true,
},
"join_time": {
Type: schema.TypeString,
Computed: true,
},
"modify_time": {
Type: schema.TypeString,
Computed: true,
},
"payer_account_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"resource_directory_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudResourceManagerAccountCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateResourceAccount"
request := make(map[string]interface{})
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("account_name_prefix"); ok {
request["AccountNamePrefix"] = v
}
request["DisplayName"] = d.Get("display_name")
if v, ok := d.GetOk("folder_id"); ok {
request["ParentFolderId"] = v
}
if v, ok := d.GetOk("payer_account_id"); ok {
request["PayerAccountId"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_resource_manager_account", action, AlibabaCloudSdkGoERROR)
}
responseAccount := response["Account"].(map[string]interface{})
d.SetId(fmt.Sprint(responseAccount["AccountId"]))
return resourceAlicloudResourceManagerAccountRead(d, meta)
}
func resourceAlicloudResourceManagerAccountRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
resourcemanagerService := ResourcemanagerService{client}
object, err := resourcemanagerService.DescribeResourceManagerAccount(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_resource_manager_account resourcemanagerService.DescribeResourceManagerAccount Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("display_name", object["DisplayName"])
d.Set("folder_id", object["FolderId"])
d.Set("join_method", object["JoinMethod"])
d.Set("join_time", object["JoinTime"])
d.Set("modify_time", object["ModifyTime"])
d.Set("resource_directory_id", object["ResourceDirectoryId"])
d.Set("status", object["Status"])
d.Set("type", object["Type"])
getPayerForAccountObject, err := resourcemanagerService.GetPayerForAccount(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("payer_account_id", getPayerForAccountObject["PayerAccountId"])
return nil
}
func resourceAlicloudResourceManagerAccountUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
d.Partial(true)
if d.HasChange("folder_id") {
request := map[string]interface{}{
"AccountId": d.Id(),
}
request["DestinationFolderId"] = d.Get("folder_id")
action := "MoveAccount"
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("folder_id")
}
update := false
request := map[string]interface{}{
"AccountId": d.Id(),
}
if d.HasChange("display_name") {
update = true
}
request["NewDisplayName"] = d.Get("display_name")
if update {
action := "UpdateAccount"
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("display_name")
}
d.Partial(false)
return resourceAlicloudResourceManagerAccountRead(d, meta)
}
func resourceAlicloudResourceManagerAccountDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudResourceManagerAccount. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudResourceManagerControlPolicy() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudResourceManagerControlPolicyCreate,
Read: resourceAlicloudResourceManagerControlPolicyRead,
Update: resourceAlicloudResourceManagerControlPolicyUpdate,
Delete: resourceAlicloudResourceManagerControlPolicyDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"control_policy_name": {
Type: schema.TypeString,
Required: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"effect_scope": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"RAM"}, false),
},
"policy_document": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.ValidateJsonString,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
equal, _ := compareJsonTemplateAreEquivalent(old, new)
return equal
},
},
},
}
}
func resourceAlicloudResourceManagerControlPolicyCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateControlPolicy"
request := make(map[string]interface{})
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
request["PolicyName"] = d.Get("control_policy_name")
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["EffectScope"] = d.Get("effect_scope")
request["PolicyDocument"] = d.Get("policy_document")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("CreateControlPolicy")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_resource_manager_control_policy", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
responseControlPolicy := response["ControlPolicy"].(map[string]interface{})
d.SetId(fmt.Sprint(responseControlPolicy["PolicyId"]))
return resourceAlicloudResourceManagerControlPolicyRead(d, meta)
}
func resourceAlicloudResourceManagerControlPolicyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
resourcemanagerService := ResourcemanagerService{client}
object, err := resourcemanagerService.DescribeResourceManagerControlPolicy(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_resource_manager_control_policy resourcemanagerService.DescribeResourceManagerControlPolicy Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("control_policy_name", object["PolicyName"])
d.Set("description", object["Description"])
d.Set("effect_scope", object["EffectScope"])
d.Set("policy_document", object["PolicyDocument"])
return nil
}
func resourceAlicloudResourceManagerControlPolicyUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"PolicyId": d.Id(),
}
if d.HasChange("control_policy_name") {
update = true
request["NewPolicyName"] = d.Get("control_policy_name")
}
if d.HasChange("description") {
update = true
request["NewDescription"] = d.Get("description")
}
if d.HasChange("policy_document") {
update = true
request["NewPolicyDocument"] = d.Get("policy_document")
}
if update {
action := "UpdateControlPolicy"
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudResourceManagerControlPolicyRead(d, meta)
}
func resourceAlicloudResourceManagerControlPolicyDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteControlPolicy"
var response map[string]interface{}
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"PolicyId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.ControlPolicy"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudResourceManagerControlPolicyAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudResourceManagerControlPolicyAttachmentCreate,
Read: resourceAlicloudResourceManagerControlPolicyAttachmentRead,
Delete: resourceAlicloudResourceManagerControlPolicyAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"policy_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"target_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudResourceManagerControlPolicyAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AttachControlPolicy"
request := make(map[string]interface{})
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
request["PolicyId"] = d.Get("policy_id")
request["TargetId"] = d.Get("target_id")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_resource_manager_control_policy_attachment", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["PolicyId"], ":", request["TargetId"]))
return resourceAlicloudResourceManagerControlPolicyAttachmentRead(d, meta)
}
func resourceAlicloudResourceManagerControlPolicyAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
resourcemanagerService := ResourcemanagerService{client}
_, err := resourcemanagerService.DescribeResourceManagerControlPolicyAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_resource_manager_control_policy_attachment resourcemanagerService.DescribeResourceManagerControlPolicyAttachment Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("policy_id", parts[0])
d.Set("target_id", parts[1])
return nil
}
func resourceAlicloudResourceManagerControlPolicyAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DetachControlPolicy"
var response map[string]interface{}
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"PolicyId": parts[0],
"TargetId": parts[1],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Target"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudResourceManagerFolder() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudResourceManagerFolderCreate,
Read: resourceAlicloudResourceManagerFolderRead,
Update: resourceAlicloudResourceManagerFolderUpdate,
Delete: resourceAlicloudResourceManagerFolderDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"folder_name": {
Type: schema.TypeString,
Required: true,
},
"parent_folder_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudResourceManagerFolderCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateFolder"
request := make(map[string]interface{})
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
request["FolderName"] = d.Get("folder_name")
if v, ok := d.GetOk("parent_folder_id"); ok {
request["ParentFolderId"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_resource_manager_folder", action, AlibabaCloudSdkGoERROR)
}
responseFolder := response["Folder"].(map[string]interface{})
d.SetId(fmt.Sprint(responseFolder["FolderId"]))
return resourceAlicloudResourceManagerFolderRead(d, meta)
}
func resourceAlicloudResourceManagerFolderRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
resourcemanagerService := ResourcemanagerService{client}
object, err := resourcemanagerService.DescribeResourceManagerFolder(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_resource_manager_folder resourcemanagerService.DescribeResourceManagerFolder Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("folder_name", object["FolderName"])
d.Set("parent_folder_id", object["ParentFolderId"])
return nil
}
func resourceAlicloudResourceManagerFolderUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
if d.HasChange("folder_name") {
request := map[string]interface{}{
"FolderId": d.Id(),
}
request["NewFolderName"] = d.Get("folder_name")
action := "UpdateFolder"
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudResourceManagerFolderRead(d, meta)
}
func resourceAlicloudResourceManagerFolderDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteFolder"
var response map[string]interface{}
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"FolderId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Folder", "EntityNotExists.ResourceDirectory"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudResourceManagerHandshake() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudResourceManagerHandshakeCreate,
Read: resourceAlicloudResourceManagerHandshakeRead,
Delete: resourceAlicloudResourceManagerHandshakeDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"expire_time": {
Type: schema.TypeString,
Computed: true,
},
"master_account_id": {
Type: schema.TypeString,
Computed: true,
},
"master_account_name": {
Type: schema.TypeString,
Computed: true,
},
"modify_time": {
Type: schema.TypeString,
Computed: true,
},
"note": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"resource_directory_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"target_entity": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"target_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Account", "Email"}, false),
},
},
}
}
func resourceAlicloudResourceManagerHandshakeCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "InviteAccountToResourceDirectory"
request := make(map[string]interface{})
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("note"); ok {
request["Note"] = v
}
request["TargetEntity"] = d.Get("target_entity")
request["TargetType"] = d.Get("target_type")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_resource_manager_handshake", action, AlibabaCloudSdkGoERROR)
}
responseHandshake := response["Handshake"].(map[string]interface{})
d.SetId(fmt.Sprint(responseHandshake["HandshakeId"]))
return resourceAlicloudResourceManagerHandshakeRead(d, meta)
}
func resourceAlicloudResourceManagerHandshakeRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
resourcemanagerService := ResourcemanagerService{client}
object, err := resourcemanagerService.DescribeResourceManagerHandshake(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_resource_manager_handshake resourcemanagerService.DescribeResourceManagerHandshake Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("expire_time", object["ExpireTime"])
d.Set("master_account_id", object["MasterAccountId"])
d.Set("master_account_name", object["MasterAccountName"])
d.Set("modify_time", object["ModifyTime"])
d.Set("note", object["Note"])
d.Set("resource_directory_id", object["ResourceDirectoryId"])
d.Set("status", object["Status"])
d.Set("target_entity", object["TargetEntity"])
d.Set("target_type", object["TargetType"])
return nil
}
func resourceAlicloudResourceManagerHandshakeDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "CancelHandshake"
var response map[string]interface{}
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"HandshakeId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Handshake", "HandshakeStatusMismatch"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudResourceManagerPolicy() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudResourceManagerPolicyCreate,
Read: resourceAlicloudResourceManagerPolicyRead,
Update: resourceAlicloudResourceManagerPolicyUpdate,
Delete: resourceAlicloudResourceManagerPolicyDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"default_version": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Field 'default_version' has been deprecated from provider version 1.90.0",
},
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"policy_document": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.ValidateJsonString,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
equal, _ := compareJsonTemplateAreEquivalent(old, new)
return equal
},
},
"policy_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"policy_type": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudResourceManagerPolicyCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreatePolicy"
request := make(map[string]interface{})
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["PolicyDocument"] = d.Get("policy_document")
request["PolicyName"] = d.Get("policy_name")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_resource_manager_policy", action, AlibabaCloudSdkGoERROR)
}
responsePolicy := response["Policy"].(map[string]interface{})
d.SetId(fmt.Sprint(responsePolicy["PolicyName"]))
return resourceAlicloudResourceManagerPolicyUpdate(d, meta)
}
func resourceAlicloudResourceManagerPolicyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
resourcemanagerService := ResourcemanagerService{client}
object, err := resourcemanagerService.DescribeResourceManagerPolicy(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_resource_manager_policy resourcemanagerService.DescribeResourceManagerPolicy Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("policy_name", d.Id())
d.Set("default_version", object["DefaultVersion"])
d.Set("description", object["Description"])
d.Set("policy_type", object["PolicyType"])
getPolicyVersionObject, err := resourcemanagerService.GetPolicyVersion(d.Id(), d)
if err != nil {
return WrapError(err)
}
d.Set("policy_document", getPolicyVersionObject["PolicyDocument"])
return nil
}
func resourceAlicloudResourceManagerPolicyUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
if !d.IsNewResource() && d.HasChange("default_version") {
request := map[string]interface{}{
"PolicyName": d.Id(),
}
request["VersionId"] = d.Get("default_version")
action := "SetDefaultPolicyVersion"
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudResourceManagerPolicyRead(d, meta)
}
func resourceAlicloudResourceManagerPolicyDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeletePolicy"
var response map[string]interface{}
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"PolicyName": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist.Policy"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudResourceManagerPolicyAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudResourceManagerPolicyAttachmentCreate,
Read: resourceAlicloudResourceManagerPolicyAttachmentRead,
Delete: resourceAlicloudResourceManagerPolicyAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"policy_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"policy_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Custom", "System"}, false),
},
"principal_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"principal_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"IMSGroup", "IMSUser", "ServiceRole"}, false),
},
"resource_group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudResourceManagerPolicyAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AttachPolicy"
request := make(map[string]interface{})
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
request["PolicyName"] = d.Get("policy_name")
request["PolicyType"] = d.Get("policy_type")
request["PrincipalName"] = d.Get("principal_name")
request["PrincipalType"] = d.Get("principal_type")
request["ResourceGroupId"] = d.Get("resource_group_id")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_resource_manager_policy_attachment", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["PolicyName"], ":", request["PolicyType"], ":", request["PrincipalName"], ":", request["PrincipalType"], ":", request["ResourceGroupId"]))
return resourceAlicloudResourceManagerPolicyAttachmentRead(d, meta)
}
func resourceAlicloudResourceManagerPolicyAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
resourcemanagerService := ResourcemanagerService{client}
if len(strings.Split(d.Id(), ":")) != 5 {
d.SetId(fmt.Sprintf("%v:%v", d.Id(), d.Get("resource_group_id").(string)))
}
_, err := resourcemanagerService.DescribeResourceManagerPolicyAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_resource_manager_policy_attachment resourcemanagerService.DescribeResourceManagerPolicyAttachment Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 5)
if err != nil {
return WrapError(err)
}
d.Set("policy_name", parts[0])
d.Set("policy_type", parts[1])
d.Set("principal_name", parts[2])
d.Set("principal_type", parts[3])
d.Set("resource_group_id", parts[4])
return nil
}
func resourceAlicloudResourceManagerPolicyAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
if len(strings.Split(d.Id(), ":")) != 5 {
d.SetId(fmt.Sprintf("%v:%v", d.Id(), d.Get("resource_group_id").(string)))
}
parts, err := ParseResourceId(d.Id(), 5)
if err != nil {
return WrapError(err)
}
action := "DetachPolicy"
var response map[string]interface{}
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"PolicyName": parts[0],
"PolicyType": parts[1],
"PrincipalName": parts[2],
"PrincipalType": parts[3],
"ResourceGroupId": parts[4],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist.Policy", "EntityNotExists.ResourceGroup"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"strconv"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudResourceManagerPolicyVersion() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudResourceManagerPolicyVersionCreate,
Read: resourceAlicloudResourceManagerPolicyVersionRead,
Update: resourceAlicloudResourceManagerPolicyVersionUpdate,
Delete: resourceAlicloudResourceManagerPolicyVersionDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"is_default_version": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Deprecated: "Field 'is_default_version' has been deprecated from provider version 1.90.0",
},
"policy_document": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.ValidateJsonString,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
equal, _ := compareJsonTemplateAreEquivalent(old, new)
return equal
},
},
"policy_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"create_date": {
Type: schema.TypeString,
Computed: true,
Removed: "Field 'create_date' has been removed from provider version 1.100.0.",
},
"version_id": {
Type: schema.TypeString,
Computed: true,
ForceNew: true,
Removed: "Field 'version_id' has been removed from provider version 1.100.0.",
},
},
}
}
func resourceAlicloudResourceManagerPolicyVersionCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreatePolicyVersion"
request := make(map[string]interface{})
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("is_default_version"); ok {
request["SetAsDefault"] = v
}
request["PolicyDocument"] = d.Get("policy_document")
request["PolicyName"] = d.Get("policy_name")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_resource_manager_policy_version", action, AlibabaCloudSdkGoERROR)
}
responsePolicyVersion := response["PolicyVersion"].(map[string]interface{})
d.SetId(fmt.Sprint(request["PolicyName"], ":", responsePolicyVersion["VersionId"]))
return resourceAlicloudResourceManagerPolicyVersionRead(d, meta)
}
func resourceAlicloudResourceManagerPolicyVersionRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
resourcemanagerService := ResourcemanagerService{client}
object, err := resourcemanagerService.DescribeResourceManagerPolicyVersion(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_resource_manager_policy_version resourcemanagerService.DescribeResourceManagerPolicyVersion Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("policy_name", parts[0])
d.Set("is_default_version", object["IsDefaultVersion"])
d.Set("policy_document", object["PolicyDocument"])
return nil
}
func resourceAlicloudResourceManagerPolicyVersionUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
resourcemanagerService := ResourcemanagerService{client}
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
if d.HasChange("is_default_version") {
object, err := resourcemanagerService.DescribeResourceManagerPolicyVersion(d.Id())
if err != nil {
return WrapError(err)
}
target := strconv.FormatBool(d.Get("is_default_version").(bool))
if strconv.FormatBool(object["IsDefaultVersion"].(bool)) != target {
if target == "true" {
request := map[string]interface{}{
"PolicyName": parts[0],
"VersionId": parts[1],
}
action := "SetDefaultPolicyVersion"
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
}
}
return resourceAlicloudResourceManagerPolicyVersionRead(d, meta)
}
func resourceAlicloudResourceManagerPolicyVersionDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeletePolicyVersion"
var response map[string]interface{}
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"PolicyName": parts[0],
"VersionId": parts[1],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist.Policy", "EntityNotExist.Policy.Version"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudResourceManagerResourceDirectory() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudResourceManagerResourceDirectoryCreate,
Read: resourceAlicloudResourceManagerResourceDirectoryRead,
Update: resourceAlicloudResourceManagerResourceDirectoryUpdate,
Delete: resourceAlicloudResourceManagerResourceDirectoryDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Update: schema.DefaultTimeout(6 * time.Minute),
},
Schema: map[string]*schema.Schema{
"master_account_id": {
Type: schema.TypeString,
Computed: true,
},
"master_account_name": {
Type: schema.TypeString,
Computed: true,
},
"root_folder_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Disabled", "Enabled"}, false),
},
},
}
}
func resourceAlicloudResourceManagerResourceDirectoryCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "InitResourceDirectory"
request := make(map[string]interface{})
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_resource_manager_resource_directory", action, AlibabaCloudSdkGoERROR)
}
responseResourceDirectory := response["ResourceDirectory"].(map[string]interface{})
d.SetId(fmt.Sprint(responseResourceDirectory["ResourceDirectoryId"]))
return resourceAlicloudResourceManagerResourceDirectoryUpdate(d, meta)
}
func resourceAlicloudResourceManagerResourceDirectoryRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
resourcemanagerService := ResourcemanagerService{client}
object, err := resourcemanagerService.DescribeResourceManagerResourceDirectory(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_resource_manager_resource_directory resourcemanagerService.DescribeResourceManagerResourceDirectory Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("master_account_id", object["MasterAccountId"])
d.Set("master_account_name", object["MasterAccountName"])
d.Set("root_folder_id", object["RootFolderId"])
d.Set("status", object["ScpStatus"])
return nil
}
func resourceAlicloudResourceManagerResourceDirectoryUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
resourcemanagerService := ResourcemanagerService{client}
var response map[string]interface{}
d.Partial(true)
if d.HasChange("status") {
object, err := resourcemanagerService.DescribeResourceManagerResourceDirectory(d.Id())
if err != nil {
return WrapError(err)
}
target := d.Get("status").(string)
if object["ScpStatus"].(string) != target {
if target == "Disabled" {
request := map[string]interface{}{}
action := "DisableControlPolicy"
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Disabled"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, resourcemanagerService.ResourceManagerResourceDirectoryStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if target == "Enabled" {
request := map[string]interface{}{}
action := "EnableControlPolicy"
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Enabled"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, resourcemanagerService.ResourceManagerResourceDirectoryStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.SetPartial("status")
}
}
d.Partial(false)
return resourceAlicloudResourceManagerResourceDirectoryRead(d, meta)
}
func resourceAlicloudResourceManagerResourceDirectoryDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DestroyResourceDirectory"
var response map[string]interface{}
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{}
wait := incrementalWait(3*time.Second, 0*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2020-03-31"), StringPointer("AK"), request, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudResourceManagerResourceGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudResourceManagerResourceGroupCreate,
Read: resourceAlicloudResourceManagerResourceGroupRead,
Update: resourceAlicloudResourceManagerResourceGroupUpdate,
Delete: resourceAlicloudResourceManagerResourceGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(11 * time.Minute),
},
Schema: map[string]*schema.Schema{
"account_id": {
Type: schema.TypeString,
Computed: true,
},
"create_date": {
Type: schema.TypeString,
Computed: true,
Removed: "Field 'create_date' has been removed from provider version 1.114.0.",
},
"display_name": {
Type: schema.TypeString,
Required: true,
},
"region_statuses": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"region_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"resource_group_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"name"},
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Deprecated: "Field 'name' has been deprecated from version 1.114.0. Use 'resource_group_name' instead.",
ConflictsWith: []string{"resource_group_name"},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudResourceManagerResourceGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
resourcemanagerService := ResourcemanagerService{client}
var response map[string]interface{}
action := "CreateResourceGroup"
request := make(map[string]interface{})
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
request["DisplayName"] = d.Get("display_name")
if v, ok := d.GetOk("resource_group_name"); ok {
request["Name"] = v
} else if v, ok := d.GetOk("name"); ok {
request["Name"] = v
} else {
return WrapError(Error(`[ERROR] Argument "name" or "resource_group_name" must be set one!`))
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_resource_manager_resource_group", action, AlibabaCloudSdkGoERROR)
}
responseResourceGroup := response["ResourceGroup"].(map[string]interface{})
d.SetId(fmt.Sprint(responseResourceGroup["Id"]))
stateConf := BuildStateConf([]string{}, []string{"OK"}, d.Timeout(schema.TimeoutCreate), 10*time.Second, resourcemanagerService.ResourceManagerResourceGroupStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudResourceManagerResourceGroupRead(d, meta)
}
func resourceAlicloudResourceManagerResourceGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
resourcemanagerService := ResourcemanagerService{client}
object, err := resourcemanagerService.DescribeResourceManagerResourceGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_resource_manager_resource_group resourcemanagerService.DescribeResourceManagerResourceGroup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("account_id", object["AccountId"])
d.Set("display_name", object["DisplayName"])
regionStatus := make([]map[string]interface{}, 0)
if regionStatusList, ok := object["RegionStatuses"].(map[string]interface{})["RegionStatus"].([]interface{}); ok {
for _, v := range regionStatusList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"region_id": m1["RegionId"],
"status": m1["Status"],
}
regionStatus = append(regionStatus, temp1)
}
}
}
if err := d.Set("region_statuses", regionStatus); err != nil {
return WrapError(err)
}
d.Set("resource_group_name", object["Name"])
d.Set("name", object["Name"])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudResourceManagerResourceGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"ResourceGroupId": d.Id(),
}
if d.HasChange("display_name") {
update = true
}
request["NewDisplayName"] = d.Get("display_name")
if update {
action := "UpdateResourceGroup"
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudResourceManagerResourceGroupRead(d, meta)
}
func resourceAlicloudResourceManagerResourceGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteResourceGroup"
var response map[string]interface{}
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ResourceGroupId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.ResourceGroup"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudResourceManagerResourceShare() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudResourceManagerResourceShareCreate,
Read: resourceAlicloudResourceManagerResourceShareRead,
Update: resourceAlicloudResourceManagerResourceShareUpdate,
Delete: resourceAlicloudResourceManagerResourceShareDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Delete: schema.DefaultTimeout(11 * time.Minute),
},
Schema: map[string]*schema.Schema{
"resource_share_name": {
Type: schema.TypeString,
Required: true,
},
"resource_share_owner": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudResourceManagerResourceShareCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateResourceShare"
request := make(map[string]interface{})
conn, err := client.NewRessharingClient()
if err != nil {
return WrapError(err)
}
request["ResourceShareName"] = d.Get("resource_share_name")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_resource_manager_resource_share", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
response = response["ResourceShare"].(map[string]interface{})
d.SetId(fmt.Sprint(response["ResourceShareId"]))
return resourceAlicloudResourceManagerResourceShareRead(d, meta)
}
func resourceAlicloudResourceManagerResourceShareRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
resourcesharingService := ResourcesharingService{client}
object, err := resourcesharingService.DescribeResourceManagerResourceShare(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_resource_manager_resource_share resourcesharingService.DescribeResourceManagerResourceShare Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("resource_share_name", object["ResourceShareName"])
d.Set("resource_share_owner", object["ResourceShareOwner"])
d.Set("status", object["ResourceShareStatus"])
return nil
}
func resourceAlicloudResourceManagerResourceShareUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"ResourceShareId": d.Id(),
}
if d.HasChange("resource_share_name") {
update = true
}
request["ResourceShareName"] = d.Get("resource_share_name")
if update {
action := "UpdateResourceShare"
conn, err := client.NewRessharingClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudResourceManagerResourceShareRead(d, meta)
}
func resourceAlicloudResourceManagerResourceShareDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
resourcesharingService := ResourcesharingService{client}
action := "DeleteResourceShare"
var response map[string]interface{}
conn, err := client.NewRessharingClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ResourceShareId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Deleted"}, d.Timeout(schema.TimeoutDelete), 5*time.Second, resourcesharingService.ResourceManagerResourceShareStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudResourceManagerRole() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudResourceManagerRoleCreate,
Read: resourceAlicloudResourceManagerRoleRead,
Update: resourceAlicloudResourceManagerRoleUpdate,
Delete: resourceAlicloudResourceManagerRoleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"arn": {
Type: schema.TypeString,
Computed: true,
},
"assume_role_policy_document": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.ValidateJsonString,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
equal, _ := compareJsonTemplateAreEquivalent(old, new)
return equal
},
},
"create_date": {
Type: schema.TypeString,
Computed: true,
Removed: "Field 'create_date' has been removed from provider version 1.114.0.",
},
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"max_session_duration": {
Type: schema.TypeInt,
Optional: true,
Default: 3600,
},
"role_id": {
Type: schema.TypeString,
Computed: true,
},
"role_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"update_date": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudResourceManagerRoleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateRole"
request := make(map[string]interface{})
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
request["AssumeRolePolicyDocument"] = d.Get("assume_role_policy_document")
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("max_session_duration"); ok {
request["MaxSessionDuration"] = v
}
request["RoleName"] = d.Get("role_name")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_resource_manager_role", action, AlibabaCloudSdkGoERROR)
}
responseRole := response["Role"].(map[string]interface{})
d.SetId(fmt.Sprint(responseRole["RoleName"]))
return resourceAlicloudResourceManagerRoleRead(d, meta)
}
func resourceAlicloudResourceManagerRoleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
resourcemanagerService := ResourcemanagerService{client}
object, err := resourcemanagerService.DescribeResourceManagerRole(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_resource_manager_role resourcemanagerService.DescribeResourceManagerRole Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("role_name", d.Id())
d.Set("arn", object["Arn"])
d.Set("assume_role_policy_document", object["AssumeRolePolicyDocument"])
d.Set("description", object["Description"])
d.Set("max_session_duration", object["MaxSessionDuration"])
d.Set("role_id", object["RoleId"])
d.Set("update_date", object["UpdateDate"])
return nil
}
func resourceAlicloudResourceManagerRoleUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"RoleName": d.Id(),
}
if d.HasChange("assume_role_policy_document") {
update = true
}
request["NewAssumeRolePolicyDocument"] = d.Get("assume_role_policy_document")
if d.HasChange("max_session_duration") {
update = true
request["NewMaxSessionDuration"] = d.Get("max_session_duration")
}
if update {
action := "UpdateRole"
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudResourceManagerRoleRead(d, meta)
}
func resourceAlicloudResourceManagerRoleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteRole"
var response map[string]interface{}
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"RoleName": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist.Role"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudResourceManagerSharedResource() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudResourceManagerSharedResourceCreate,
Read: resourceAlicloudResourceManagerSharedResourceRead,
Delete: resourceAlicloudResourceManagerSharedResourceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(11 * time.Minute),
Delete: schema.DefaultTimeout(11 * time.Minute),
},
Schema: map[string]*schema.Schema{
"resource_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"resource_share_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"resource_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"VSwitch"}, false),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudResourceManagerSharedResourceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
resourcesharingService := ResourcesharingService{client}
var response map[string]interface{}
action := "AssociateResourceShare"
request := make(map[string]interface{})
conn, err := client.NewRessharingClient()
if err != nil {
return WrapError(err)
}
request["Resources.1.ResourceId"] = d.Get("resource_id")
request["ResourceShareId"] = d.Get("resource_share_id")
request["Resources.1.ResourceType"] = d.Get("resource_type")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_resource_manager_shared_resource", action, AlibabaCloudSdkGoERROR)
}
response = response["ResourceShareAssociations"].([]interface{})[0].(map[string]interface{})
d.SetId(fmt.Sprint(response["ResourceShareId"], ":", response["EntityId"], ":", response["EntityType"]))
stateConf := BuildStateConf([]string{}, []string{"Associated"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, resourcesharingService.ResourceManagerSharedResourceStateRefreshFunc(d.Id(), []string{"Failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudResourceManagerSharedResourceRead(d, meta)
}
func resourceAlicloudResourceManagerSharedResourceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
resourcesharingService := ResourcesharingService{client}
object, err := resourcesharingService.DescribeResourceManagerSharedResource(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_resource_manager_shared_resource resourcesharingService.DescribeResourceManagerSharedResource Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
d.Set("resource_id", parts[1])
d.Set("resource_share_id", parts[0])
d.Set("resource_type", parts[2])
d.Set("status", object["AssociationStatus"])
return nil
}
func resourceAlicloudResourceManagerSharedResourceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
resourcesharingService := ResourcesharingService{client}
action := "DisassociateResourceShare"
var response map[string]interface{}
conn, err := client.NewRessharingClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"Resources.1.ResourceId": parts[1],
"ResourceShareId": parts[0],
"Resources.1.ResourceType": parts[2],
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Disassociated"}, d.Timeout(schema.TimeoutDelete), 5*time.Second, resourcesharingService.ResourceManagerSharedResourceStateRefreshFunc(d.Id(), []string{"Failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudResourceManagerSharedTarget() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudResourceManagerSharedTargetCreate,
Read: resourceAlicloudResourceManagerSharedTargetRead,
Delete: resourceAlicloudResourceManagerSharedTargetDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(11 * time.Minute),
Delete: schema.DefaultTimeout(11 * time.Minute),
},
Schema: map[string]*schema.Schema{
"resource_share_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"target_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudResourceManagerSharedTargetCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
resourcesharingService := ResourcesharingService{client}
var response map[string]interface{}
action := "AssociateResourceShare"
request := make(map[string]interface{})
conn, err := client.NewRessharingClient()
if err != nil {
return WrapError(err)
}
request["ResourceShareId"] = d.Get("resource_share_id")
request["Targets"] = []string{d.Get("target_id").(string)}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_resource_manager_shared_target", action, AlibabaCloudSdkGoERROR)
}
response = response["ResourceShareAssociations"].([]interface{})[0].(map[string]interface{})
d.SetId(fmt.Sprint(response["ResourceShareId"], ":", response["EntityId"]))
stateConf := BuildStateConf([]string{}, []string{"Associated"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, resourcesharingService.ResourceManagerSharedTargetStateRefreshFunc(d.Id(), []string{"Failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudResourceManagerSharedTargetRead(d, meta)
}
func resourceAlicloudResourceManagerSharedTargetRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
resourcesharingService := ResourcesharingService{client}
object, err := resourcesharingService.DescribeResourceManagerSharedTarget(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_resource_manager_shared_target resourcesharingService.DescribeResourceManagerSharedTarget Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("resource_share_id", parts[0])
d.Set("target_id", parts[1])
d.Set("status", object["AssociationStatus"])
return nil
}
func resourceAlicloudResourceManagerSharedTargetDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
resourcesharingService := ResourcesharingService{client}
action := "DisassociateResourceShare"
var response map[string]interface{}
conn, err := client.NewRessharingClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ResourceShareId": parts[0],
"Targets": []string{parts[1]},
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Disassociated"}, d.Timeout(schema.TimeoutDelete), 5*time.Second, resourcesharingService.ResourceManagerSharedTargetStateRefreshFunc(d.Id(), []string{"Failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudRosChangeSet() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRosChangeSetCreate,
Read: resourceAlicloudRosChangeSetRead,
Delete: resourceAlicloudRosChangeSetDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(11 * time.Minute),
},
Schema: map[string]*schema.Schema{
"change_set_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"change_set_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "UPDATE",
},
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"disable_rollback": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"notification_urls": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
ForceNew: true,
},
"parameters": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"parameter_key": {
Type: schema.TypeString,
Required: true,
},
"parameter_value": {
Type: schema.TypeString,
Required: true,
},
},
},
ForceNew: true,
},
"ram_role_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"replacement_option": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"stack_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"stack_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"stack_policy_body": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.ValidateJsonString,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
equal, _ := compareJsonTemplateAreEquivalent(old, new)
return equal
},
},
"stack_policy_during_update_body": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"stack_policy_during_update_url": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"stack_policy_url": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"template_body": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.ValidateJsonString,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
equal, _ := compareJsonTemplateAreEquivalent(old, new)
return equal
},
},
"template_url": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"timeout_in_minutes": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ForceNew: true,
},
"use_previous_parameters": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudRosChangeSetCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rosService := RosService{client}
var response map[string]interface{}
action := "CreateChangeSet"
request := make(map[string]interface{})
conn, err := client.NewRosClient()
if err != nil {
return WrapError(err)
}
request["ChangeSetName"] = d.Get("change_set_name")
if v, ok := d.GetOk("change_set_type"); ok {
request["ChangeSetType"] = v
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOkExists("disable_rollback"); ok {
request["DisableRollback"] = v
}
if v, ok := d.GetOk("notification_urls"); ok {
request["NotificationURLs"] = v.(*schema.Set).List()
}
if v, ok := d.GetOk("parameters"); ok {
request["Parameters"] = v.(*schema.Set).List()
}
if v, ok := d.GetOk("ram_role_name"); ok {
request["RamRoleName"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("replacement_option"); ok {
request["ReplacementOption"] = v
}
if v, ok := d.GetOk("resources_to_import"); ok {
request["ResourcesToImport"] = v.(*schema.Set).List()
}
if v, ok := d.GetOk("stack_id"); ok {
request["StackId"] = v
}
if v, ok := d.GetOk("stack_name"); ok {
request["StackName"] = v
}
if v, ok := d.GetOk("stack_policy_body"); ok {
request["StackPolicyBody"] = v
}
if v, ok := d.GetOk("stack_policy_during_update_body"); ok {
request["StackPolicyDuringUpdateBody"] = v
}
if v, ok := d.GetOk("stack_policy_during_update_url"); ok {
request["StackPolicyDuringUpdateURL"] = v
}
if v, ok := d.GetOk("stack_policy_url"); ok {
request["StackPolicyURL"] = v
}
if v, ok := d.GetOk("template_body"); ok {
request["TemplateBody"] = v
}
if v, ok := d.GetOk("template_url"); ok {
request["TemplateURL"] = v
}
if v, ok := d.GetOk("timeout_in_minutes"); ok {
request["TimeoutInMinutes"] = v
}
if v, ok := d.GetOkExists("use_previous_parameters"); ok {
request["UsePreviousParameters"] = v
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("CreateChangeSet")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ros_change_set", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetId(fmt.Sprint(response["ChangeSetId"]))
stateConf := BuildStateConf([]string{}, []string{"CREATE_COMPLETE"}, d.Timeout(schema.TimeoutCreate), 60*time.Second, rosService.RosChangeSetStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudRosChangeSetRead(d, meta)
}
func resourceAlicloudRosChangeSetRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rosService := RosService{client}
object, err := rosService.DescribeRosChangeSet(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ros_change_set rosService.DescribeRosChangeSet Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("change_set_name", object["ChangeSetName"])
d.Set("change_set_type", object["ChangeSetType"])
d.Set("description", object["Description"])
d.Set("disable_rollback", object["DisableRollback"])
Parameters := object["Parameters"].([]interface{})
parameters := make([]map[string]interface{}, len(Parameters))
for i, v := range Parameters {
parameters[i] = make(map[string]interface{})
parameters[i]["parameter_key"] = v.(map[string]interface{})["ParameterKey"]
parameters[i]["parameter_value"] = v.(map[string]interface{})["ParameterValue"]
}
if err := d.Set("parameters", parameters); err != nil {
return WrapError(err)
}
d.Set("stack_id", object["StackId"])
d.Set("stack_name", object["StackName"])
d.Set("status", object["Status"])
d.Set("template_body", object["TemplateBody"])
d.Set("timeout_in_minutes", formatInt(object["TimeoutInMinutes"]))
return nil
}
func resourceAlicloudRosChangeSetDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteChangeSet"
var response map[string]interface{}
conn, err := client.NewRosClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ChangeSetId": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ChangeSetNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudRosStack() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRosStackCreate,
Read: resourceAlicloudRosStackRead,
Update: resourceAlicloudRosStackUpdate,
Delete: resourceAlicloudRosStackDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(11 * time.Minute),
Delete: schema.DefaultTimeout(6 * time.Minute),
Update: schema.DefaultTimeout(11 * time.Minute),
},
Schema: map[string]*schema.Schema{
"create_option": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"deletion_protection": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Disabled", "Enabled"}, false),
Default: "Disabled",
},
"disable_rollback": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"notification_urls": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
ForceNew: true,
},
"parameters": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"parameter_key": {
Type: schema.TypeString,
Optional: true,
},
"parameter_value": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"ram_role_name": {
Type: schema.TypeString,
Optional: true,
},
"replacement_option": {
Type: schema.TypeString,
Optional: true,
},
"retain_all_resources": {
Type: schema.TypeBool,
Optional: true,
},
"retain_resources": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"stack_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"stack_policy_body": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateJsonString,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
equal, _ := compareJsonTemplateAreEquivalent(old, new)
return equal
},
},
"stack_policy_during_update_body": {
Type: schema.TypeString,
Optional: true,
},
"stack_policy_during_update_url": {
Type: schema.TypeString,
Optional: true,
},
"stack_policy_url": {
Type: schema.TypeString,
Optional: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
"template_body": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateJsonString,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
equal, _ := compareJsonTemplateAreEquivalent(old, new)
return equal
},
},
"template_url": {
Type: schema.TypeString,
Optional: true,
},
"template_version": {
Type: schema.TypeString,
Optional: true,
},
"timeout_in_minutes": {
Type: schema.TypeInt,
Optional: true,
Default: 60,
},
"use_previous_parameters": {
Type: schema.TypeBool,
Optional: true,
},
},
}
}
func resourceAlicloudRosStackCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rosService := RosService{client}
var response map[string]interface{}
action := "CreateStack"
request := make(map[string]interface{})
conn, err := client.NewRosClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("create_option"); ok {
request["CreateOption"] = v
}
if v, ok := d.GetOk("deletion_protection"); ok {
request["DeletionProtection"] = v
}
if v, ok := d.GetOkExists("disable_rollback"); ok {
request["DisableRollback"] = v
}
if v, ok := d.GetOk("notification_urls"); ok {
request["NotificationURLs"] = v.(*schema.Set).List()
}
if v, ok := d.GetOk("parameters"); ok {
parameters := make([]map[string]interface{}, len(v.(*schema.Set).List()))
for i, j := range v.(*schema.Set).List() {
parameters[i] = make(map[string]interface{})
parameters[i]["ParameterKey"] = j.(map[string]interface{})["parameter_key"]
parameters[i]["ParameterValue"] = j.(map[string]interface{})["parameter_value"]
}
request["Parameters"] = parameters
}
if v, ok := d.GetOk("ram_role_name"); ok {
request["RamRoleName"] = v
}
request["RegionId"] = client.RegionId
request["StackName"] = d.Get("stack_name")
if v, ok := d.GetOk("stack_policy_body"); ok {
request["StackPolicyBody"] = v
}
if v, ok := d.GetOk("stack_policy_url"); ok {
request["StackPolicyURL"] = v
}
if v, ok := d.GetOk("template_body"); ok {
request["TemplateBody"] = v
}
if v, ok := d.GetOk("template_url"); ok {
request["TemplateURL"] = v
}
if v, ok := d.GetOk("template_version"); ok {
request["TemplateVersion"] = v
}
if v, ok := d.GetOk("timeout_in_minutes"); ok {
request["TimeoutInMinutes"] = v
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("CreateStack")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ros_stack", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetId(fmt.Sprint(response["StackId"]))
stateConf := BuildStateConf([]string{}, []string{"CREATE_COMPLETE"}, d.Timeout(schema.TimeoutCreate), 100*time.Second, rosService.RosStackStateRefreshFunc(d.Id(), []string{"CREATE_FAILED", "CREATE_ROLLBACK_COMPLETE", "CREATE_ROLLBACK_FAILED"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudRosStackUpdate(d, meta)
}
func resourceAlicloudRosStackRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rosService := RosService{client}
object, err := rosService.DescribeRosStack(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ros_stack rosService.DescribeRosStack Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("deletion_protection", object["DeletionProtection"])
d.Set("disable_rollback", object["DisableRollback"])
parameters := make([]map[string]interface{}, 0)
if parametersList, ok := object["Parameters"].([]interface{}); ok {
for _, v := range parametersList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"parameter_key": m1["ParameterKey"],
"parameter_value": m1["ParameterValue"],
}
if !strings.HasPrefix(v.(map[string]interface{})["ParameterKey"].(string), "ALIYUN::") {
parameters = append(parameters, temp1)
}
}
}
}
if err := d.Set("parameters", parameters); err != nil {
return WrapError(err)
}
d.Set("ram_role_name", object["RamRoleName"])
d.Set("stack_name", object["StackName"])
d.Set("status", object["Status"])
d.Set("timeout_in_minutes", formatInt(object["TimeoutInMinutes"]))
listTagResourcesObject, err := rosService.ListTagResources(d.Id(), "stack")
if err != nil {
return WrapError(err)
}
d.Set("tags", tagsToMap(listTagResourcesObject))
getStackPolicyObject, err := rosService.GetStackPolicy(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("stack_policy_body", getStackPolicyObject["StackPolicyBody"])
return nil
}
func resourceAlicloudRosStackUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rosService := RosService{client}
var response map[string]interface{}
d.Partial(true)
if d.HasChange("tags") {
if err := rosService.SetResourceTags(d, "stack"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
update := false
request := map[string]interface{}{
"StackId": d.Id(),
}
request["RegionId"] = client.RegionId
if !d.IsNewResource() && d.HasChange("disable_rollback") {
update = true
request["DisableRollback"] = d.Get("disable_rollback")
}
if !d.IsNewResource() && d.HasChange("parameters") {
update = true
parameters := make([]map[string]interface{}, len(d.Get("parameters").(*schema.Set).List()))
for i, v := range d.Get("parameters").(*schema.Set).List() {
parameters[i] = make(map[string]interface{})
parameters[i]["ParameterKey"] = v.(map[string]interface{})["parameter_key"]
parameters[i]["ParameterValue"] = v.(map[string]interface{})["parameter_value"]
}
request["Parameters"] = parameters
}
if !d.IsNewResource() && d.HasChange("ram_role_name") {
update = true
request["RamRoleName"] = d.Get("ram_role_name")
}
if !d.IsNewResource() && d.HasChange("stack_policy_body") {
update = true
request["StackPolicyBody"] = d.Get("stack_policy_body")
}
if !d.IsNewResource() && d.HasChange("timeout_in_minutes") {
update = true
request["TimeoutInMinutes"] = d.Get("timeout_in_minutes")
}
if update {
if _, ok := d.GetOk("replacement_option"); ok {
request["ReplacementOption"] = d.Get("replacement_option")
}
if _, ok := d.GetOk("stack_policy_during_update_body"); ok {
request["StackPolicyDuringUpdateBody"] = d.Get("stack_policy_during_update_body")
}
if _, ok := d.GetOk("stack_policy_during_update_url"); ok {
request["StackPolicyDuringUpdateURL"] = d.Get("stack_policy_during_update_url")
}
if _, ok := d.GetOk("stack_policy_url"); ok {
request["StackPolicyURL"] = d.Get("stack_policy_url")
}
if _, ok := d.GetOk("template_body"); ok {
request["TemplateBody"] = d.Get("template_body")
}
if _, ok := d.GetOk("template_url"); ok {
request["TemplateURL"] = d.Get("template_url")
}
if _, ok := d.GetOk("template_version"); ok {
request["TemplateVersion"] = d.Get("template_version")
}
if _, ok := d.GetOkExists("use_previous_parameters"); ok {
request["UsePreviousParameters"] = d.Get("use_previous_parameters")
}
action := "UpdateStack"
conn, err := client.NewRosClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("UpdateStack")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"UPDATE_COMPLETE"}, d.Timeout(schema.TimeoutUpdate), 100*time.Second, rosService.RosStackStateRefreshFunc(d.Id(), []string{"UPDATE_FAILED", "ROLLBACK_FAILED"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("disable_rollback")
d.SetPartial("parameters")
d.SetPartial("ram_role_name")
d.SetPartial("stack_policy_body")
d.SetPartial("timeout_in_minutes")
}
d.Partial(false)
return resourceAlicloudRosStackRead(d, meta)
}
func resourceAlicloudRosStackDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rosService := RosService{client}
action := "DeleteStack"
var response map[string]interface{}
conn, err := client.NewRosClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"StackId": d.Id(),
}
if v, ok := d.GetOk("ram_role_name"); ok {
request["RamRoleName"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOkExists("retain_all_resources"); ok {
request["RetainAllResources"] = v
}
if v, ok := d.GetOk("retain_resources"); ok {
request["RetainResources"] = v.(*schema.Set).List()
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"StackNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"DELETE_COMPLETE"}, d.Timeout(schema.TimeoutDelete), 100*time.Second, rosService.RosStackStateRefreshFunc(d.Id(), []string{"DELETE_FAILED"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudRosStackGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRosStackGroupCreate,
Read: resourceAlicloudRosStackGroupRead,
Update: resourceAlicloudRosStackGroupUpdate,
Delete: resourceAlicloudRosStackGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(6 * time.Minute),
Update: schema.DefaultTimeout(6 * time.Minute),
},
Schema: map[string]*schema.Schema{
"account_ids": {
Type: schema.TypeString,
Optional: true,
},
"administration_role_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"execution_role_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"operation_description": {
Type: schema.TypeString,
Optional: true,
},
"operation_preferences": {
Type: schema.TypeString,
Optional: true,
},
"parameters": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"parameter_key": {
Type: schema.TypeString,
Optional: true,
},
"parameter_value": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"region_ids": {
Type: schema.TypeString,
Optional: true,
},
"stack_group_id": {
Type: schema.TypeString,
Computed: true,
},
"stack_group_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"template_body": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateJsonString,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
equal, _ := compareJsonTemplateAreEquivalent(old, new)
return equal
},
},
"template_url": {
Type: schema.TypeString,
Optional: true,
},
"template_version": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudRosStackGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rosService := RosService{client}
var response map[string]interface{}
action := "CreateStackGroup"
request := make(map[string]interface{})
conn, err := client.NewRosClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("administration_role_name"); ok {
request["AdministrationRoleName"] = v
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("execution_role_name"); ok {
request["ExecutionRoleName"] = v
}
if v, ok := d.GetOk("parameters"); ok {
parameters := make([]map[string]interface{}, len(v.(*schema.Set).List()))
for i, j := range v.(*schema.Set).List() {
parameters[i] = make(map[string]interface{})
parameters[i]["ParameterKey"] = j.(map[string]interface{})["parameter_key"]
parameters[i]["ParameterValue"] = j.(map[string]interface{})["parameter_value"]
}
request["Parameters"] = parameters
}
request["RegionId"] = client.RegionId
request["StackGroupName"] = d.Get("stack_group_name")
if v, ok := d.GetOk("template_body"); ok {
request["TemplateBody"] = v
}
if v, ok := d.GetOk("template_url"); ok {
request["TemplateURL"] = v
}
if v, ok := d.GetOk("template_version"); ok {
request["TemplateVersion"] = v
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("CreateStackGroup")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ros_stack_group", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetId(fmt.Sprint(request["StackGroupName"]))
stateConf := BuildStateConf([]string{}, []string{"ACTIVE"}, d.Timeout(schema.TimeoutCreate), 60*time.Second, rosService.RosStackGroupStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudRosStackGroupRead(d, meta)
}
func resourceAlicloudRosStackGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rosService := RosService{client}
object, err := rosService.DescribeRosStackGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ros_stack_group rosService.DescribeRosStackGroup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("stack_group_name", d.Id())
d.Set("administration_role_name", object["AdministrationRoleName"])
d.Set("description", object["Description"])
d.Set("execution_role_name", object["ExecutionRoleName"])
parameters := make([]map[string]interface{}, 0)
if parametersList, ok := object["Parameters"].([]interface{}); ok {
for _, v := range parametersList {
if m1, ok := v.(map[string]interface{}); ok {
temp1 := map[string]interface{}{
"parameter_key": m1["ParameterKey"],
"parameter_value": m1["ParameterValue"],
}
parameters = append(parameters, temp1)
}
}
}
if err := d.Set("parameters", parameters); err != nil {
return WrapError(err)
}
d.Set("stack_group_id", object["StackGroupId"])
d.Set("status", object["Status"])
d.Set("template_body", object["TemplateBody"])
return nil
}
func resourceAlicloudRosStackGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rosService := RosService{client}
var response map[string]interface{}
update := false
request := map[string]interface{}{
"StackGroupName": d.Id(),
}
request["RegionId"] = client.RegionId
if d.HasChange("administration_role_name") {
update = true
request["AdministrationRoleName"] = d.Get("administration_role_name")
}
if d.HasChange("description") {
update = true
request["Description"] = d.Get("description")
}
if d.HasChange("execution_role_name") {
update = true
request["ExecutionRoleName"] = d.Get("execution_role_name")
}
if d.HasChange("parameters") {
update = true
parameters := make([]map[string]interface{}, len(d.Get("parameters").(*schema.Set).List()))
for i, j := range d.Get("parameters").(*schema.Set).List() {
parameters[i] = make(map[string]interface{})
parameters[i]["ParameterKey"] = j.(map[string]interface{})["parameter_key"]
parameters[i]["ParameterValue"] = j.(map[string]interface{})["parameter_value"]
}
request["Parameters"] = parameters
}
if d.HasChange("template_body") {
update = true
request["TemplateBody"] = d.Get("template_body")
}
if update {
if _, ok := d.GetOk("account_ids"); ok {
request["AccountIds"] = d.Get("account_ids")
}
if _, ok := d.GetOk("operation_description"); ok {
request["OperationDescription"] = d.Get("operation_description")
}
if _, ok := d.GetOk("operation_preferences"); ok {
request["OperationPreferences"] = d.Get("operation_preferences")
}
if _, ok := d.GetOk("region_ids"); ok {
request["RegionIds"] = d.Get("region_ids")
}
if _, ok := d.GetOk("template_url"); ok {
request["TemplateURL"] = d.Get("template_url")
}
if _, ok := d.GetOk("template_version"); ok {
request["TemplateVersion"] = d.Get("template_version")
}
action := "UpdateStackGroup"
conn, err := client.NewRosClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("UpdateStackGroup")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"ACTIVE"}, d.Timeout(schema.TimeoutUpdate), 60*time.Second, rosService.RosStackGroupStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudRosStackGroupRead(d, meta)
}
func resourceAlicloudRosStackGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteStackGroup"
var response map[string]interface{}
conn, err := client.NewRosClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"StackGroupName": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudRosStackInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRosStackInstanceCreate,
Read: resourceAlicloudRosStackInstanceRead,
Update: resourceAlicloudRosStackInstanceUpdate,
Delete: resourceAlicloudRosStackInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"operation_description": {
Type: schema.TypeString,
Optional: true,
},
"operation_preferences": {
Type: schema.TypeString,
Optional: true,
},
"parameter_overrides": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"parameter_key": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"parameter_value": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
},
},
Sensitive: true,
},
"stack_group_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-zA-Z][-_a-zA-Z0-9]{1,254}$`), "The name can be up to 255 characters in length and can contain digits, letters, hyphens (-), and underscores (_). It must start with a digit or letter."),
},
"stack_instance_account_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^\d+$`), "It can only be made of numbers."),
},
"stack_instance_region_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"timeout_in_minutes": {
Type: schema.TypeString,
Optional: true,
},
"retain_stacks": {
Type: schema.TypeBool,
Optional: true,
},
},
}
}
func resourceAlicloudRosStackInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateStackInstances"
request := make(map[string]interface{})
conn, err := client.NewRosClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("parameter_overrides"); ok {
for parameterOverridesPtr, parameterOverrides := range v.(*schema.Set).List() {
parameterOverridesArg := parameterOverrides.(map[string]interface{})
request["ParameterOverrides."+fmt.Sprint(parameterOverridesPtr+1)+".ParameterKey"] = parameterOverridesArg["parameter_key"]
request["ParameterOverrides."+fmt.Sprint(parameterOverridesPtr+1)+".ParameterValue"] = parameterOverridesArg["parameter_value"]
}
}
request["RegionId"] = client.RegionId
request["StackGroupName"] = d.Get("stack_group_name")
request["AccountIds"] = convertListToJsonString([]interface{}{d.Get("stack_instance_account_id")})
request["RegionIds"] = convertListToJsonString([]interface{}{d.Get("stack_instance_region_id")})
if v, ok := d.GetOk("timeout_in_minutes"); ok {
request["TimeoutInMinutes"] = v
}
if v, ok := d.GetOk("operation_preferences"); ok {
request["OperationPreferences"] = v
}
request["ClientToken"] = buildClientToken("CreateStackInstances")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ros_stack_instance", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["StackGroupName"], ":", d.Get("stack_instance_account_id"), ":", d.Get("stack_instance_region_id")))
rosService := RosService{client}
stateConf := BuildStateConf([]string{}, []string{"CURRENT"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, rosService.RosStackInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudRosStackInstanceRead(d, meta)
}
func resourceAlicloudRosStackInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rosService := RosService{client}
object, err := rosService.DescribeRosStackInstance(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ros_stack_instance rosService.DescribeRosStackInstance Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
d.Set("stack_group_name", parts[0])
d.Set("stack_instance_account_id", parts[1])
d.Set("stack_instance_region_id", parts[2])
if parameterOverridesList, ok := object["ParameterOverrides"]; ok && parameterOverridesList != nil {
parameterOverridesMaps := make([]map[string]interface{}, 0)
for _, parameterOverridesListItem := range parameterOverridesList.([]interface{}) {
if v, ok := parameterOverridesListItem.(map[string]interface{}); ok {
parameterOverridesListItemMap := make(map[string]interface{})
parameterOverridesListItemMap["parameter_key"] = v["ParameterKey"]
parameterOverridesListItemMap["parameter_value"] = v["ParameterValue"]
parameterOverridesMaps = append(parameterOverridesMaps, parameterOverridesListItemMap)
}
}
d.Set("parameter_overrides", parameterOverridesMaps)
}
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudRosStackInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"StackGroupName": parts[0],
"AccountIds": convertListToJsonString([]interface{}{parts[1]}),
"RegionIds": convertListToJsonString([]interface{}{parts[2]}),
}
request["RegionId"] = client.RegionId
if d.HasChange("parameter_overrides") {
update = true
if v, ok := d.GetOk("parameter_overrides"); ok {
for parameterOverridesPtr, parameterOverrides := range v.(*schema.Set).List() {
parameterOverridesArg := parameterOverrides.(map[string]interface{})
request["ParameterOverrides."+fmt.Sprint(parameterOverridesPtr+1)+".ParameterKey"] = parameterOverridesArg["parameter_key"]
request["ParameterOverrides."+fmt.Sprint(parameterOverridesPtr+1)+".ParameterValue"] = parameterOverridesArg["parameter_value"]
}
}
}
if d.HasChange("operation_description") {
update = true
if v, ok := d.GetOk("operation_description"); ok {
request["OperationDescription"] = v
}
}
if d.HasChange("operation_preferences") {
update = true
if v, ok := d.GetOk("operation_preferences"); ok {
request["OperationPreferences"] = v
}
}
if d.HasChange("timeout_in_minutes") {
update = true
if v, ok := d.GetOk("timeout_in_minutes"); ok {
request["TimeoutInMinutes"] = v
}
}
if update {
action := "UpdateStackInstances"
conn, err := client.NewRosClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("UpdateStackInstances")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) || IsExpectedErrors(err, []string{"StackGroupOperationInProgress"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudRosStackInstanceRead(d, meta)
}
func resourceAlicloudRosStackInstanceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rosService := RosService{client}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
action := "DeleteStackInstances"
var response map[string]interface{}
conn, err := client.NewRosClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"StackGroupName": parts[0],
"AccountIds": convertListToJsonString([]interface{}{parts[1]}),
"RegionIds": convertListToJsonString([]interface{}{parts[2]}),
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOkExists("retain_stacks"); ok {
request["RetainStacks"] = v
} else {
request["RetainStacks"] = false
}
request["ClientToken"] = buildClientToken("DeleteStackInstances")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) || IsExpectedErrors(err, []string{"StackGroupOperationInProgress"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, rosService.RosStackInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudRosTemplate() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRosTemplateCreate,
Read: resourceAlicloudRosTemplateRead,
Update: resourceAlicloudRosTemplateUpdate,
Delete: resourceAlicloudRosTemplateDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
},
"tags": tagsSchema(),
"template_body": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.ValidateJsonString,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
equal, _ := compareJsonTemplateAreEquivalent(old, new)
return equal
},
},
"template_name": {
Type: schema.TypeString,
Required: true,
},
"template_url": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudRosTemplateCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateTemplate"
request := make(map[string]interface{})
conn, err := client.NewRosClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("template_body"); ok {
request["TemplateBody"] = v
}
request["TemplateName"] = d.Get("template_name")
if v, ok := d.GetOk("template_url"); ok {
request["TemplateURL"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ros_template", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["TemplateId"]))
return resourceAlicloudRosTemplateUpdate(d, meta)
}
func resourceAlicloudRosTemplateRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rosService := RosService{client}
object, err := rosService.DescribeRosTemplate(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ros_template rosService.DescribeRosTemplate Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", object["Description"])
d.Set("template_body", object["TemplateBody"])
d.Set("template_name", object["TemplateName"])
listTagResourcesObject, err := rosService.ListTagResources(d.Id(), "template")
if err != nil {
return WrapError(err)
}
d.Set("tags", tagsToMap(listTagResourcesObject))
return nil
}
func resourceAlicloudRosTemplateUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rosService := RosService{client}
var response map[string]interface{}
d.Partial(true)
if d.HasChange("tags") {
if err := rosService.SetResourceTags(d, "template"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
update := false
request := map[string]interface{}{
"TemplateId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("description") {
update = true
request["Description"] = d.Get("description")
}
if !d.IsNewResource() && d.HasChange("template_body") {
update = true
request["TemplateBody"] = d.Get("template_body")
}
if !d.IsNewResource() && d.HasChange("template_name") {
update = true
request["TemplateName"] = d.Get("template_name")
}
if update {
if _, ok := d.GetOk("template_url"); ok {
request["TemplateURL"] = d.Get("template_url")
}
action := "UpdateTemplate"
conn, err := client.NewRosClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("description")
d.SetPartial("template_body")
d.SetPartial("template_name")
}
d.Partial(false)
return resourceAlicloudRosTemplateRead(d, meta)
}
func resourceAlicloudRosTemplateDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteTemplate"
var response map[string]interface{}
conn, err := client.NewRosClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"TemplateId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ChangeSetNotFound", "StackNotFound", "TemplateNotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudRosTemplateScratch() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRosTemplateScratchCreate,
Read: resourceAlicloudRosTemplateScratchRead,
Update: resourceAlicloudRosTemplateScratchUpdate,
Delete: resourceAlicloudRosTemplateScratchDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
Delete: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
},
"execution_mode": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Async", "Sync"}, false),
},
"logical_id_strategy": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"LongTypePrefixAndIndexSuffix", "LongTypePrefixAndHashSuffix", "ShortTypePrefixAndHashSuffix"}, false),
},
"preference_parameters": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"parameter_key": {
Type: schema.TypeString,
Required: true,
},
"parameter_value": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"source_tag": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
ExactlyOneOf: []string{"source_resource_group", "source_tag", "source_resources"},
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"resource_tags": {
Type: schema.TypeMap,
Required: true,
},
"resource_type_filter": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
MaxItems: 20,
},
},
},
},
"source_resource_group": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"resource_group_id": {
Type: schema.TypeString,
Required: true,
},
"resource_type_filter": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
MaxItems: 20,
},
},
},
},
"source_resources": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"resource_id": {
Type: schema.TypeString,
Required: true,
},
"resource_type": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"template_scratch_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ResourceImport", "ArchitectureReplication"}, false),
},
},
}
}
func resourceAlicloudRosTemplateScratchCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateTemplateScratch"
request := make(map[string]interface{})
conn, err := client.NewRosClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("execution_mode"); ok {
request["ExecutionMode"] = v
}
if v, ok := d.GetOk("logical_id_strategy"); ok {
request["LogicalIdStrategy"] = v
}
if v, ok := d.GetOk("preference_parameters"); ok {
preferenceParametersMaps := make([]map[string]interface{}, 0)
for _, preferenceParameters := range v.(*schema.Set).List() {
preferenceParametersArg := preferenceParameters.(map[string]interface{})
preferenceParametersMap := map[string]interface{}{}
preferenceParametersMap["ParameterKey"] = preferenceParametersArg["parameter_key"]
preferenceParametersMap["ParameterValue"] = preferenceParametersArg["parameter_value"]
preferenceParametersMaps = append(preferenceParametersMaps, preferenceParametersMap)
}
if v, err := convertListMapToJsonString(preferenceParametersMaps); err != nil {
return WrapError(err)
} else {
request["PreferenceParameters"] = v
}
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("source_resource_group"); ok {
sourceResourceGroupMap := map[string]interface{}{}
for _, sourceResourceGroup := range v.(*schema.Set).List() {
sourceResourceGroupArg := sourceResourceGroup.(map[string]interface{})
sourceResourceGroupMap["ResourceGroupId"] = sourceResourceGroupArg["resource_group_id"]
resourceTypeFilterList := make([]string, 0)
for _, v := range sourceResourceGroupArg["resource_type_filter"].([]interface{}) {
resourceTypeFilterList = append(resourceTypeFilterList, v.(string))
}
sourceResourceGroupMap["ResourceTypeFilter"] = resourceTypeFilterList
}
if v, err := convertMaptoJsonString(sourceResourceGroupMap); err != nil {
return WrapError(err)
} else {
request["SourceResourceGroup"] = v
}
}
if v, ok := d.GetOk("source_resources"); ok {
sourceResourcesMaps := make([]map[string]interface{}, 0)
for _, sourceResources := range v.(*schema.Set).List() {
sourceResourcesArg := sourceResources.(map[string]interface{})
sourceResourcesMap := map[string]interface{}{}
sourceResourcesMap["ResourceId"] = sourceResourcesArg["resource_id"]
sourceResourcesMap["ResourceType"] = sourceResourcesArg["resource_type"]
sourceResourcesMaps = append(sourceResourcesMaps, sourceResourcesMap)
}
if v, err := convertListMapToJsonString(sourceResourcesMaps); err != nil {
return WrapError(err)
} else {
request["SourceResources"] = v
}
}
if v, ok := d.GetOk("source_tag"); ok {
sourceTagMap := map[string]interface{}{}
for _, sourceResources := range v.(*schema.Set).List() {
sourceTagArg := sourceResources.(map[string]interface{})
sourceTagMap["ResourceTags"] = sourceTagArg["resource_tags"]
resourceTypeFilterList := make([]string, 0)
for _, v := range sourceTagArg["resource_type_filter"].([]interface{}) {
resourceTypeFilterList = append(resourceTypeFilterList, v.(string))
}
sourceTagMap["ResourceTypeFilter"] = resourceTypeFilterList
}
if v, err := convertMaptoJsonString(sourceTagMap); err != nil {
return WrapError(err)
} else {
request["SourceTag"] = v
}
}
request["TemplateScratchType"] = d.Get("template_scratch_type")
request["ClientToken"] = buildClientToken("CreateTemplateScratch")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ros_template_scratch", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["TemplateScratchId"]))
rosService := RosService{client}
stateConf := BuildStateConf([]string{}, []string{"GENERATE_COMPLETE"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, rosService.RosTemplateScratchStateRefreshFunc(d.Id(), []string{"GENERATE_FAILED"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudRosTemplateScratchRead(d, meta)
}
func resourceAlicloudRosTemplateScratchRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rosService := RosService{client}
object, err := rosService.DescribeRosTemplateScratch(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ros_template_scratch rosService.DescribeRosTemplateScratch Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", object["Description"])
d.Set("logical_id_strategy", object["LogicalIdStrategy"])
if preferenceParametersList, ok := object["PreferenceParameters"]; ok && preferenceParametersList != nil {
preferenceParametersMaps := make([]map[string]interface{}, 0)
for _, preferenceParametersListItem := range preferenceParametersList.([]interface{}) {
if preferenceParametersListItemMap, ok := preferenceParametersListItem.(map[string]interface{}); ok {
if v, ok := preferenceParametersListItemMap["ParameterValue"]; ok && fmt.Sprint(v) != "" {
preferenceParametersListItemArg := make(map[string]interface{}, 0)
preferenceParametersListItemArg["parameter_key"] = preferenceParametersListItemMap["ParameterKey"]
preferenceParametersListItemArg["parameter_value"] = v
preferenceParametersMaps = append(preferenceParametersMaps, preferenceParametersListItemArg)
}
}
}
d.Set("preference_parameters", preferenceParametersMaps)
}
sourceTagSli := make([]map[string]interface{}, 0)
if v, ok := object["SourceTag"]; ok {
if sourceTag, ok := v.(map[string]interface{}); ok && len(sourceTag) > 0 {
sourceTagMap := make(map[string]interface{})
sourceTagMap["resource_tags"] = sourceTag["ResourceTags"]
resourceTypeFilter := make([]interface{}, 0)
if v, ok := sourceTag["ResourceTypeFilter"]; ok {
if vv, ok := v.([]interface{}); ok && len(vv) > 0 {
resourceTypeFilter = append(resourceTypeFilter, vv...)
}
}
sourceTagMap["resource_type_filter"] = resourceTypeFilter
sourceTagSli = append(sourceTagSli, sourceTagMap)
}
}
d.Set("source_tag", sourceTagSli)
sourceResourceGroupSli := make([]map[string]interface{}, 0)
if v, ok := object["SourceResourceGroup"]; ok {
if sourceResourceGroup, ok := v.(map[string]interface{}); ok && len(sourceResourceGroup) > 0 {
sourceResourceGroupMap := make(map[string]interface{})
sourceResourceGroupMap["resource_group_id"] = sourceResourceGroup["ResourceGroupId"]
resourceTypeFilter := make([]interface{}, 0)
if v, ok := sourceResourceGroup["ResourceTypeFilter"]; ok {
if vv, ok := v.([]interface{}); ok && len(vv) > 0 {
resourceTypeFilter = append(resourceTypeFilter, vv...)
}
}
sourceResourceGroupMap["resource_type_filter"] = resourceTypeFilter
sourceResourceGroupSli = append(sourceResourceGroupSli, sourceResourceGroupMap)
}
}
d.Set("source_resource_group", sourceResourceGroupSli)
if sourceResourcesList, ok := object["SourceResources"]; ok && sourceResourcesList != nil {
sourceResourcesMaps := make([]map[string]interface{}, 0)
for _, sourceResourcesListItem := range sourceResourcesList.([]interface{}) {
if sourceResourcesListItemMap, ok := sourceResourcesListItem.(map[string]interface{}); ok {
sourceResourcesListItemArg := make(map[string]interface{}, 0)
sourceResourcesListItemArg["resource_id"] = sourceResourcesListItemMap["ResourceId"]
sourceResourcesListItemArg["resource_type"] = sourceResourcesListItemMap["ResourceType"]
sourceResourcesMaps = append(sourceResourcesMaps, sourceResourcesListItemArg)
}
}
d.Set("source_resources", sourceResourcesMaps)
}
d.Set("status", object["Status"])
d.Set("template_scratch_type", object["TemplateScratchType"])
return nil
}
func resourceAlicloudRosTemplateScratchUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rosService := RosService{client}
var response map[string]interface{}
update := false
request := map[string]interface{}{
"TemplateScratchId": d.Id(),
}
request["RegionId"] = client.RegionId
if d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
}
if d.HasChange("logical_id_strategy") {
update = true
if v, ok := d.GetOk("logical_id_strategy"); ok {
request["LogicalIdStrategy"] = v
}
}
if d.HasChange("source_tag") {
update = true
if v, ok := d.GetOkExists("source_tag"); ok {
sourceTagMap := map[string]interface{}{}
for _, sourceResources := range v.(*schema.Set).List() {
sourceTagArg := sourceResources.(map[string]interface{})
if len(sourceTagArg["resource_tags"].(map[string]interface{})) > 0 {
sourceTagMap["ResourceTags"] = sourceTagArg["resource_tags"]
resourceTypeFilterList := make([]string, 0)
for _, v := range sourceTagArg["resource_type_filter"].([]interface{}) {
resourceTypeFilterList = append(resourceTypeFilterList, v.(string))
}
sourceTagMap["ResourceTypeFilter"] = resourceTypeFilterList
}
}
if v, err := convertMaptoJsonString(sourceTagMap); err != nil {
return WrapError(err)
} else {
request["SourceTag"] = v
}
}
}
if d.HasChange("preference_parameters") {
update = true
}
if v, ok := d.GetOk("preference_parameters"); ok {
preferenceParametersMaps := make([]map[string]interface{}, 0)
for _, preferenceParameters := range v.(*schema.Set).List() {
preferenceParametersArg := preferenceParameters.(map[string]interface{})
preferenceParametersMap := map[string]interface{}{}
preferenceParametersMap["ParameterKey"] = preferenceParametersArg["parameter_key"]
preferenceParametersMap["ParameterValue"] = preferenceParametersArg["parameter_value"]
preferenceParametersMaps = append(preferenceParametersMaps, preferenceParametersMap)
}
if v, err := convertListMapToJsonString(preferenceParametersMaps); err != nil {
return WrapError(err)
} else {
request["PreferenceParameters"] = v
}
}
if d.HasChange("source_resource_group") {
update = true
if v, ok := d.GetOk("source_resource_group"); ok {
sourceResourceGroupMap := map[string]interface{}{}
for _, sourceResourceGroup := range v.(*schema.Set).List() {
sourceResourceGroupArg := sourceResourceGroup.(map[string]interface{})
sourceResourceGroupMap["ResourceGroupId"] = sourceResourceGroupArg["resource_group_id"]
resourceTypeFilterList := make([]string, 0)
for _, v := range sourceResourceGroupArg["resource_type_filter"].([]interface{}) {
resourceTypeFilterList = append(resourceTypeFilterList, v.(string))
}
sourceResourceGroupMap["ResourceTypeFilter"] = resourceTypeFilterList
}
if v, err := convertMaptoJsonString(sourceResourceGroupMap); err != nil {
return WrapError(err)
} else {
request["SourceResourceGroup"] = v
}
}
}
if d.HasChange("source_resources") {
update = true
if v, ok := d.GetOk("source_resources"); ok {
sourceResourcesMaps := make([]map[string]interface{}, 0)
for _, sourceResources := range v.(*schema.Set).List() {
sourceResourcesArg := sourceResources.(map[string]interface{})
sourceResourcesMap := map[string]interface{}{}
sourceResourcesMap["ResourceId"] = sourceResourcesArg["resource_id"]
sourceResourcesMap["ResourceType"] = sourceResourcesArg["resource_type"]
sourceResourcesMaps = append(sourceResourcesMaps, sourceResourcesMap)
}
if v, err := convertListMapToJsonString(sourceResourcesMaps); err != nil {
return WrapError(err)
} else {
request["SourceResources"] = v
}
}
}
if update {
if v, ok := d.GetOk("execution_mode"); ok {
request["ExecutionMode"] = v
}
action := "UpdateTemplateScratch"
conn, err := client.NewRosClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("UpdateTemplateScratch")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"GENERATE_COMPLETE"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, rosService.RosTemplateScratchStateRefreshFunc(d.Id(), []string{"GENERATE_FAILED"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudRosTemplateScratchRead(d, meta)
}
func resourceAlicloudRosTemplateScratchDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rosService := RosService{client}
action := "DeleteTemplateScratch"
var response map[string]interface{}
conn, err := client.NewRosClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"TemplateScratchId": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, rosService.RosTemplateScratchStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliyunRouteEntry() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunRouteEntryCreate,
Read: resourceAliyunRouteEntryRead,
Delete: resourceAliyunRouteEntryDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"router_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Attribute router_id has been deprecated and suggest removing it from your template.",
},
"route_table_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"destination_cidrblock": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"nexthop_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"nexthop_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(2, 128),
},
},
}
}
func resourceAliyunRouteEntryCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
rtId := d.Get("route_table_id").(string)
cidr := d.Get("destination_cidrblock").(string)
nt := d.Get("nexthop_type").(string)
ni := d.Get("nexthop_id").(string)
table, err := vpcService.QueryRouteTableById(rtId)
if err != nil {
return WrapError(err)
}
request := vpc.CreateCreateRouteEntryRequest()
request.RegionId = client.RegionId
request.RouteTableId = rtId
request.DestinationCidrBlock = cidr
request.NextHopType = nt
request.NextHopId = ni
request.ClientToken = buildClientToken(request.GetActionName())
request.RouteEntryName = d.Get("name").(string)
// retry 10 min to create lots of entries concurrently
err = resource.Retry(10*time.Minute, func() *resource.RetryError {
if err := vpcService.WaitForAllRouteEntriesAvailable(rtId, DefaultTimeout); err != nil {
return resource.NonRetryableError(err)
}
args := *request
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.CreateRouteEntry(&args)
})
if err != nil {
// Route Entry does not support concurrence when creating or deleting it;
// Route Entry does not support creating or deleting within 5 seconds frequently
// It must ensure all the route entries, vpc, vswitches' status must be available before creating or deleting route entry.
if IsExpectedErrors(err, []string{"TaskConflict", "IncorrectRouteEntryStatus", Throttling, "IncorrectVpcStatus"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"RouterEntryConflict.Duplicated"}) {
en, err := vpcService.DescribeRouteEntry(rtId + ":" + table.VRouterId + ":" + cidr + ":" + nt + ":" + ni)
if err != nil {
return WrapError(err)
}
return WrapError(Error("The route entry %s has already existed. "+
"Please import it using ID '%s:%s:%s:%s:%s' or specify a new 'destination_cidrblock' and try again.",
en.DestinationCidrBlock, en.RouteTableId, table.VRouterId, en.DestinationCidrBlock, en.NextHopType, ni))
}
return WrapErrorf(err, DefaultErrorMsg, "alicloud_route_entry", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
// route_table_id:router_id:destination_cidrblock:nexthop_type:nexthop_id
d.SetId(rtId + ":" + table.VRouterId + ":" + cidr + ":" + nt + ":" + ni)
if err := vpcService.WaitForRouteEntry(d.Id(), Available, DefaultTimeout); err != nil {
return WrapError(err)
}
return resourceAliyunRouteEntryRead(d, meta)
}
func resourceAliyunRouteEntryRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
parts, err := ParseResourceId(d.Id(), 5)
if err != nil {
return WrapError(err)
}
object, err := vpcService.DescribeRouteEntry(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("router_id", parts[1])
d.Set("route_table_id", object.RouteTableId)
d.Set("destination_cidrblock", object.DestinationCidrBlock)
d.Set("nexthop_type", object.NextHopType)
d.Set("nexthop_id", object.InstanceId)
d.Set("name", object.RouteEntryName)
return nil
}
func resourceAliyunRouteEntryDelete(d *schema.ResourceData, meta interface{}) error {
request, err := buildAliyunRouteEntryDeleteArgs(d, meta)
if err != nil {
return WrapError(err)
}
client := meta.(*connectivity.AliyunClient)
request.RegionId = client.RegionId
vpcService := VpcService{client}
parts, err := ParseResourceId(d.Id(), 5)
rtId := parts[0]
if err := vpcService.WaitForAllRouteEntriesAvailable(rtId, DefaultTimeout); err != nil {
return WrapError(err)
}
retryTimes := 7
err = resource.Retry(10*time.Minute, func() *resource.RetryError {
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DeleteRouteEntry(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectVpcStatus", "TaskConflict", "IncorrectRouteEntryStatus", "Forbbiden", "UnknownError"}) {
// Route Entry does not support creating or deleting within 5 seconds frequently
time.Sleep(time.Duration(retryTimes) * time.Second)
retryTimes += 7
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidRouteEntry.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(vpcService.WaitForRouteEntry(d.Id(), Deleted, DefaultTimeout))
}
func buildAliyunRouteEntryDeleteArgs(d *schema.ResourceData, meta interface{}) (*vpc.DeleteRouteEntryRequest, error) {
request := vpc.CreateDeleteRouteEntryRequest()
request.RouteTableId = d.Get("route_table_id").(string)
request.DestinationCidrBlock = d.Get("destination_cidrblock").(string)
if v := d.Get("destination_cidrblock").(string); v != "" {
request.DestinationCidrBlock = v
}
if v := d.Get("nexthop_id").(string); v != "" {
request.NextHopId = v
}
return request, nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudRouteTable() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRouteTableCreate,
Read: resourceAlicloudRouteTableRead,
Update: resourceAlicloudRouteTableUpdate,
Delete: resourceAlicloudRouteTableDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"route_table_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"name"},
ValidateFunc: validation.StringLenBetween(2, 128),
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Field 'name' has been deprecated from provider version 1.119.1. New field 'route_table_name' instead.",
ConflictsWith: []string{"route_table_name"},
ValidateFunc: validation.StringLenBetween(2, 128),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
"vpc_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudRouteTableCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
action := "CreateRouteTable"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("route_table_name"); ok {
request["RouteTableName"] = v
} else if v, ok := d.GetOk("name"); ok {
request["RouteTableName"] = v
}
request["VpcId"] = d.Get("vpc_id")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("CreateRouteTable")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) || IsExpectedErrors(err, []string{"OperationConflict"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_route_table", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetId(fmt.Sprint(response["RouteTableId"]))
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, vpcService.RouteTableStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudRouteTableUpdate(d, meta)
}
func resourceAlicloudRouteTableRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeRouteTable(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_route_table vpcService.DescribeRouteTable Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", object["Description"])
d.Set("route_table_name", object["RouteTableName"])
d.Set("name", object["RouteTableName"])
d.Set("status", object["Status"])
if v, ok := object["Tags"].(map[string]interface{}); ok {
d.Set("tags", tagsToMap(v["Tag"]))
}
d.Set("vpc_id", object["VpcId"])
return nil
}
func resourceAlicloudRouteTableUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
d.Partial(true)
if d.HasChange("tags") {
if err := vpcService.SetResourceTags(d, "ROUTETABLE"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
update := false
request := map[string]interface{}{
"RouteTableId": d.Id(),
}
request["RegionId"] = client.RegionId
if !d.IsNewResource() && d.HasChange("description") {
update = true
request["Description"] = d.Get("description")
}
if !d.IsNewResource() && d.HasChange("route_table_name") {
update = true
request["RouteTableName"] = d.Get("route_table_name")
}
if !d.IsNewResource() && d.HasChange("name") {
update = true
request["RouteTableName"] = d.Get("name")
}
if update {
action := "ModifyRouteTableAttributes"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
return WrapErrorf(err, ResponseCodeMsg, d.Id(), action, response)
}
d.SetPartial("description")
d.SetPartial("name")
d.SetPartial("route_table_name")
}
d.Partial(false)
return resourceAlicloudRouteTableRead(d, meta)
}
func resourceAlicloudRouteTableDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteRouteTable"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"RouteTableId": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"OperationConflict", "DependencyViolation.RouteEntry", "IncorrectRouteTableStatus"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliyunRouteTableAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunRouteTableAttachmentCreate,
Read: resourceAliyunRouteTableAttachmentRead,
Delete: resourceAliyunRouteTableAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"route_table_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"vswitch_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAliyunRouteTableAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
request := vpc.CreateAssociateRouteTableRequest()
request.RegionId = client.RegionId
request.RouteTableId = Trim(d.Get("route_table_id").(string))
request.VSwitchId = Trim(d.Get("vswitch_id").(string))
request.ClientToken = buildClientToken(request.GetActionName())
if err := resource.Retry(3*time.Minute, func() *resource.RetryError {
args := *request
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.AssociateRouteTable(&args)
})
if err != nil {
if IsExpectedErrors(err, []string{"TaskConflict"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_route_table_attachment", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetId(request.RouteTableId + COLON_SEPARATED + request.VSwitchId)
err := vpcService.WaitForRouteTableAttachment(d.Id(), Available, DefaultTimeout)
if err != nil {
return WrapError(err)
}
if err := vpcService.WaitForVSwitch(request.VSwitchId, Available, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
return resourceAliyunRouteTableAttachmentRead(d, meta)
}
func resourceAliyunRouteTableAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeRouteTableAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("route_table_id", object["RouteTableId"])
d.Set("vswitch_id", parts[1])
return nil
}
func resourceAliyunRouteTableAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request := vpc.CreateUnassociateRouteTableRequest()
request.RegionId = client.RegionId
request.RouteTableId = parts[0]
request.VSwitchId = parts[1]
request.ClientToken = buildClientToken(request.GetActionName())
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
args := *request
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.UnassociateRouteTable(&args)
})
//Waiting for unassociate the route table
if err != nil {
if IsExpectedErrors(err, []string{"TaskConflict"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(vpcService.WaitForRouteTableAttachment(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"time"
"github.com/denverdino/aliyungo/common"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudRouterInterface() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRouterInterfaceCreate,
Read: resourceAlicloudRouterInterfaceRead,
Update: resourceAlicloudRouterInterfaceUpdate,
Delete: resourceAlicloudRouterInterfaceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"opposite_region": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"router_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
string(VRouter), string(VBR)}, false),
ForceNew: true,
DiffSuppressFunc: routerInterfaceAcceptsideDiffSuppressFunc,
},
"router_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"role": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
string(InitiatingSide), string(AcceptingSide)}, false),
ForceNew: true,
},
"specification": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice(GetAllRouterInterfaceSpec(), false),
DiffSuppressFunc: routerInterfaceAcceptsideDiffSuppressFunc,
},
"name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 128),
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"health_check_source_ip": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: routerInterfaceVBRTypeDiffSuppressFunc,
},
"health_check_target_ip": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: routerInterfaceVBRTypeDiffSuppressFunc,
},
"instance_charge_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: PostPaid,
ValidateFunc: validation.StringInSlice([]string{string(common.PrePaid), string(common.PostPaid)}, false),
},
"period": {
Type: schema.TypeInt,
Optional: true,
DiffSuppressFunc: PostPaidDiffSuppressFunc,
ValidateFunc: validation.Any(
validation.IntBetween(1, 9),
validation.IntInSlice([]int{12, 24, 36})),
},
"access_point_id": {
Type: schema.TypeString,
Computed: true,
Deprecated: "Attribute 'opposite_access_point_id' has been deprecated from version 1.11.0.",
},
"opposite_access_point_id": {
Type: schema.TypeString,
Optional: true,
Deprecated: "Attribute 'opposite_access_point_id' has been deprecated from version 1.11.0.",
},
"opposite_router_type": {
Type: schema.TypeString,
Computed: true,
Deprecated: "Attribute 'opposite_router_type' has been deprecated from version 1.11.0. Use resource alicloud_router_interface_connection's 'opposite_router_type' instead.",
},
"opposite_router_id": {
Type: schema.TypeString,
Computed: true,
Deprecated: "Attribute 'opposite_router_id' has been deprecated from version 1.11.0. Use resource alicloud_router_interface_connection's 'opposite_router_id' instead.",
},
"opposite_interface_id": {
Type: schema.TypeString,
Computed: true,
Deprecated: "Attribute 'opposite_interface_id' has been deprecated from version 1.11.0. Use resource alicloud_router_interface_connection's 'opposite_interface_id' instead.",
},
"opposite_interface_owner_id": {
Type: schema.TypeString,
Computed: true,
Deprecated: "Attribute 'opposite_interface_owner_id' has been deprecated from version 1.11.0. Use resource alicloud_router_interface_connection's 'opposite_interface_owner_id' instead.",
},
},
}
}
func resourceAlicloudRouterInterfaceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
request, err := buildAlicloudRouterInterfaceCreateArgs(d, meta)
if err != nil {
return WrapError(err)
}
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.CreateRouterInterface(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_router_interface", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*vpc.CreateRouterInterfaceResponse)
d.SetId(response.RouterInterfaceId)
if err := vpcService.WaitForRouterInterface(d.Id(), client.RegionId, Idle, 300); err != nil {
return WrapError(err)
}
return resourceAlicloudRouterInterfaceUpdate(d, meta)
}
func resourceAlicloudRouterInterfaceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
d.Partial(true)
request, attributeUpdate, err := buildAlicloudRouterInterfaceModifyAttrArgs(d, meta)
if err != nil {
return WrapError(err)
}
request.RegionId = client.RegionId
if attributeUpdate {
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.ModifyRouterInterfaceAttribute(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
if d.HasChange("specification") && !d.IsNewResource() {
d.SetPartial("specification")
request := vpc.CreateModifyRouterInterfaceSpecRequest()
request.RegionId = string(client.Region)
request.RouterInterfaceId = d.Id()
request.Spec = d.Get("specification").(string)
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.ModifyRouterInterfaceSpec(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
d.Partial(false)
return resourceAlicloudRouterInterfaceRead(d, meta)
}
func resourceAlicloudRouterInterfaceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeRouterInterface(d.Id(), client.RegionId)
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
}
d.Set("role", object.Role)
d.Set("specification", object.Spec)
d.Set("name", object.Name)
d.Set("router_id", object.RouterId)
d.Set("router_type", object.RouterType)
d.Set("description", object.Description)
d.Set("access_point_id", object.AccessPointId)
d.Set("opposite_region", object.OppositeRegionId)
d.Set("opposite_router_type", object.OppositeRouterType)
d.Set("opposite_router_id", object.OppositeRouterId)
d.Set("opposite_interface_id", object.OppositeInterfaceId)
d.Set("opposite_interface_owner_id", object.OppositeInterfaceOwnerId)
d.Set("health_check_source_ip", object.HealthCheckSourceIp)
d.Set("health_check_target_ip", object.HealthCheckTargetIp)
if object.ChargeType == "Prepaid" {
d.Set("instance_charge_type", PrePaid)
//period, err := computePeriodByUnit(object.CreationTime, object.EndTime, d.Get("period").(int), "Month")
//if err != nil {
// return WrapError(err)
//}
//d.Set("period", period)
} else {
d.Set("instance_charge_type", PostPaid)
}
return nil
}
func resourceAlicloudRouterInterfaceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
if object, err := vpcService.DescribeRouterInterface(d.Id(), client.RegionId); err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
} else if object.Status == string(Active) {
if err := vpcService.DeactivateRouterInterface(d.Id()); err != nil {
return WrapError(err)
}
}
request := vpc.CreateDeleteRouterInterfaceRequest()
request.RegionId = string(client.Region)
request.RouterInterfaceId = d.Id()
request.ClientToken = buildClientToken(request.GetActionName())
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
args := *request
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DeleteRouterInterface(&args)
})
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectStatus", "DependencyViolation.RouterInterfaceReferedByRouteEntry"}) {
time.Sleep(5 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidInstanceId.NotFound"}) {
return nil
}
WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(vpcService.WaitForRouterInterface(d.Id(), client.RegionId, Deleted, DefaultTimeoutMedium))
}
func buildAlicloudRouterInterfaceCreateArgs(d *schema.ResourceData, meta interface{}) (*vpc.CreateRouterInterfaceRequest, error) {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
oppositeRegion := d.Get("opposite_region").(string)
if err := ecsService.JudgeRegionValidation("opposite_region", oppositeRegion); err != nil {
return nil, WrapError(err)
}
request := vpc.CreateCreateRouterInterfaceRequest()
request.RegionId = client.RegionId
request.RouterType = d.Get("router_type").(string)
request.RouterId = d.Get("router_id").(string)
request.Role = d.Get("role").(string)
request.Spec = d.Get("specification").(string)
request.InstanceChargeType = d.Get("instance_charge_type").(string)
if request.InstanceChargeType == string(PrePaid) {
period := d.Get("period").(int)
request.Period = requests.NewInteger(period)
request.PricingCycle = string(Month)
if period > 9 {
request.Period = requests.NewInteger(period / 12)
request.PricingCycle = string(Year)
}
request.AutoPay = requests.NewBoolean(true)
}
request.OppositeRegionId = oppositeRegion
// Accepting side router interface spec only be Negative and router type only be VRouter.
if request.Role == string(AcceptingSide) {
request.Spec = string(Negative)
request.RouterType = string(VRouter)
} else {
if request.Spec == "" {
return request, WrapError(Error("'specification': required field is not set when role is %s.", InitiatingSide))
}
}
// Get VBR access point
if request.RouterType == string(VBR) {
describeVirtualBorderRoutersRequest := vpc.CreateDescribeVirtualBorderRoutersRequest()
values := []string{request.RouterId}
filters := []vpc.DescribeVirtualBorderRoutersFilter{{
Key: "VbrId",
Value: &values,
}}
describeVirtualBorderRoutersRequest.Filter = &filters
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeVirtualBorderRouters(describeVirtualBorderRoutersRequest)
})
if err != nil {
return request, WrapErrorf(err, DefaultErrorMsg, "alicloud_router_interface", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*vpc.DescribeVirtualBorderRoutersResponse)
if response.TotalCount > 0 {
request.AccessPointId = response.VirtualBorderRouterSet.VirtualBorderRouterType[0].AccessPointId
}
}
request.ClientToken = buildClientToken(request.GetActionName())
return request, nil
}
func buildAlicloudRouterInterfaceModifyAttrArgs(d *schema.ResourceData, meta interface{}) (*vpc.ModifyRouterInterfaceAttributeRequest, bool, error) {
sourceIp, sourceOk := d.GetOk("health_check_source_ip")
targetIp, targetOk := d.GetOk("health_check_target_ip")
if sourceOk && !targetOk || !sourceOk && targetOk {
return nil, false, WrapError(Error("The 'health_check_source_ip' and 'health_check_target_ip' should be specified or not at one time."))
}
request := vpc.CreateModifyRouterInterfaceAttributeRequest()
request.RouterInterfaceId = d.Id()
attributeUpdate := false
if d.HasChange("health_check_source_ip") {
d.SetPartial("health_check_source_ip")
request.HealthCheckSourceIp = sourceIp.(string)
request.HealthCheckTargetIp = targetIp.(string)
attributeUpdate = true
}
if d.HasChange("health_check_target_ip") {
d.SetPartial("health_check_target_ip")
request.HealthCheckTargetIp = targetIp.(string)
request.HealthCheckSourceIp = sourceIp.(string)
attributeUpdate = true
}
if d.HasChange("name") {
d.SetPartial("name")
request.Name = d.Get("name").(string)
attributeUpdate = true
}
if d.HasChange("description") {
d.SetPartial("description")
request.Description = d.Get("description").(string)
attributeUpdate = true
}
return request, attributeUpdate, nil
}
package alicloud
import (
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudRouterInterfaceConnection() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudRouterInterfaceConnectionCreate,
Read: resourceAlicloudRouterInterfaceConnectionRead,
Delete: resourceAlicloudRouterInterfaceConnectionDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"interface_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"opposite_interface_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"opposite_router_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{
string(VRouter), string(VBR)}, false),
Default: VRouter,
ForceNew: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return !d.HasChange("opposite_interface_owner_id")
},
},
"opposite_router_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return !d.HasChange("opposite_interface_owner_id")
},
},
"opposite_interface_owner_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
},
}
}
func resourceAlicloudRouterInterfaceConnectionCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
oppositeId := d.Get("opposite_interface_id").(string)
interfaceId := d.Get("interface_id").(string)
object, err := vpcService.DescribeRouterInterface(interfaceId, client.RegionId)
if err != nil {
return WrapError(err)
}
// At present, the interface with "active/inactive" status can not be modify opposite connection information
// and it is RouterInterface product limitation.
if object.OppositeInterfaceId == oppositeId {
if object.Status == string(Active) {
return WrapError(Error("The specified router interface connection has existed, and please import it using id %s.", interfaceId))
}
if object.Status == string(Inactive) {
if err = vpcService.ActivateRouterInterface(interfaceId); err != nil {
return WrapError(err)
}
d.SetId(object.RouterInterfaceId)
if err = vpcService.WaitForRouterInterfaceConnection(d.Id(), client.RegionId, Active, DefaultTimeout); err != nil {
return WrapError(err)
}
return resourceAlicloudRouterInterfaceConnectionRead(d, meta)
}
}
request := vpc.CreateModifyRouterInterfaceAttributeRequest()
request.RegionId = client.RegionId
request.RouterInterfaceId = interfaceId
request.OppositeInterfaceId = oppositeId
if owner_id, ok := d.GetOk("opposite_interface_owner_id"); ok && owner_id.(string) != "" {
request.OppositeInterfaceOwnerId = requests.Integer(owner_id.(string))
if v, o := d.GetOk("opposite_router_type"); !o || v.(string) == "" {
return WrapError(Error("'opposite_router_type' is required when 'opposite_interface_owner_id' is set."))
} else {
request.OppositeRouterType = v.(string)
}
if v, o := d.GetOk("opposite_router_id"); !o || v.(string) == "" {
return WrapError(Error("'opposite_router_id' is required when 'opposite_interface_owner_id' is set."))
} else {
request.OppositeRouterId = v.(string)
}
} else {
owner := object.OppositeInterfaceOwnerId
if owner == "" {
owner, err = client.AccountId()
if err != nil {
return WrapError(err)
}
}
if owner == "" {
return WrapError(Error("Opposite router interface owner id is empty. Please use field 'opposite_interface_owner_id' or globle field 'account_id' to set."))
}
oppositeRi, err := vpcService.DescribeRouterInterface(oppositeId, object.OppositeRegionId)
if err != nil {
return WrapError(err)
}
request.OppositeRouterId = oppositeRi.RouterId
request.OppositeRouterType = oppositeRi.RouterType
request.OppositeInterfaceOwnerId = requests.Integer(owner)
}
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.ModifyRouterInterfaceAttribute(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_router_interface_connection", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetId(interfaceId)
if err = vpcService.WaitForRouterInterfaceConnection(d.Id(), client.RegionId, Idle, DefaultTimeout); err != nil {
return WrapError(err)
}
if object.Role == string(InitiatingSide) {
connectRequest := vpc.CreateConnectRouterInterfaceRequest()
connectRequest.RegionId = client.RegionId
connectRequest.RouterInterfaceId = interfaceId
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.ConnectRouterInterface(connectRequest)
})
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectOppositeInterfaceInfo.NotSet"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(connectRequest.GetActionName(), raw, connectRequest.RpcRequest, connectRequest)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), connectRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
if err := vpcService.WaitForRouterInterfaceConnection(d.Id(), client.RegionId, Active, DefaultTimeout); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), connectRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudRouterInterfaceConnectionRead(d, meta)
}
func resourceAlicloudRouterInterfaceConnectionRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeRouterInterfaceConnection(d.Id(), client.RegionId)
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
if object.Status == string(Inactive) {
if err := vpcService.ActivateRouterInterface(d.Id()); err != nil {
return WrapError(err)
}
if err := vpcService.WaitForRouterInterfaceConnection(d.Id(), client.RegionId, Active, DefaultTimeout); err != nil {
return WrapError(err)
}
}
d.Set("interface_id", object.RouterInterfaceId)
d.Set("opposite_interface_id", object.OppositeInterfaceId)
d.Set("opposite_router_type", object.OppositeRouterType)
d.Set("opposite_router_id", object.OppositeRouterId)
d.Set("opposite_interface_owner_id", object.OppositeInterfaceOwnerId)
return nil
}
func resourceAlicloudRouterInterfaceConnectionDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeRouterInterfaceConnection(d.Id(), client.RegionId)
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
}
if object.Status == string(Idle) {
d.SetId("")
return nil
}
// At present, the interface with "active/inactive" status can not be modify opposite connection information
// and it is RouterInterface product limitation. So, the connection delete action is only modifying it to inactive.
if object.Status == string(Active) {
if err := vpcService.DeactivateRouterInterface(d.Id()); err != nil {
return WrapError(err)
}
}
return WrapError(vpcService.WaitForRouterInterfaceConnection(d.Id(), client.RegionId, Inactive, DefaultTimeoutMedium))
}
package alicloud
import (
"encoding/json"
"fmt"
"log"
"strconv"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudSaeApplication() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSaeApplicationCreate,
Read: resourceAlicloudSaeApplicationRead,
Update: resourceAlicloudSaeApplicationUpdate,
Delete: resourceAlicloudSaeApplicationDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"app_description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"app_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"auto_config": {
Type: schema.TypeBool,
Optional: true,
},
"auto_enable_application_scaling_rule": {
Type: schema.TypeBool,
Computed: true,
Optional: true,
},
"batch_wait_time": {
Type: schema.TypeInt,
Computed: true,
Optional: true,
},
"change_order_desc": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"command": {
Type: schema.TypeString,
Optional: true,
},
"command_args": {
Type: schema.TypeString,
Optional: true,
},
"config_map_mount_desc": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"cpu": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{1000, 16000, 2000, 32000, 4000, 500, 8000}),
},
"custom_host_alias": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"deploy": {
Type: schema.TypeBool,
Optional: true,
},
"edas_container_version": {
Type: schema.TypeString,
Optional: true,
},
"enable_ahas": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"enable_grey_tag_route": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"envs": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"image_url": {
Type: schema.TypeString,
Optional: true,
},
"jar_start_args": {
Type: schema.TypeString,
Optional: true,
},
"jar_start_options": {
Type: schema.TypeString,
Optional: true,
},
"jdk": {
Type: schema.TypeString,
Optional: true,
},
"liveness": {
Type: schema.TypeString,
Optional: true,
},
"memory": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{1024, 131072, 16384, 2048, 32768, 4096, 65536, 8192}),
},
"min_ready_instances": {
Type: schema.TypeInt,
Computed: true,
Optional: true,
},
"mount_desc": {
Type: schema.TypeString,
Optional: true,
},
"mount_host": {
Type: schema.TypeString,
Optional: true,
},
"namespace_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"nas_id": {
Type: schema.TypeString,
Optional: true,
},
"oss_ak_id": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"oss_ak_secret": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"oss_mount_descs": {
Type: schema.TypeString,
Optional: true,
},
"package_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"FatJar", "Image", "War"}, false),
},
"package_url": {
Type: schema.TypeString,
Optional: true,
},
"package_version": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"php_arms_config_location": {
Type: schema.TypeString,
Optional: true,
},
"php_config": {
Type: schema.TypeString,
Optional: true,
},
"php_config_location": {
Type: schema.TypeString,
Optional: true,
},
"post_start": {
Type: schema.TypeString,
Optional: true,
},
"pre_stop": {
Type: schema.TypeString,
Optional: true,
},
"readiness": {
Type: schema.TypeString,
Optional: true,
},
"replicas": {
Type: schema.TypeInt,
Required: true,
},
"security_group_id": {
Type: schema.TypeString,
Optional: true,
},
"sls_configs": {
Type: schema.TypeString,
Optional: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"RUNNING", "STOPPED", "UNKNOWN"}, false),
},
"termination_grace_period_seconds": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(1, 60),
},
"timezone": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"tomcat_config": {
Type: schema.TypeString,
Optional: true,
},
"update_strategy": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"version_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"war_start_options": {
Type: schema.TypeString,
Optional: true,
},
"web_container": {
Type: schema.TypeString,
Optional: true,
},
"intranet": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"https_cert_id": {
Type: schema.TypeString,
Optional: true,
},
"protocol": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"TCP", "HTTP", "HTTPS"}, false),
Optional: true,
},
"target_port": {
Type: schema.TypeInt,
Optional: true,
},
"port": {
Type: schema.TypeInt,
Optional: true,
},
},
},
},
"internet": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"https_cert_id": {
Type: schema.TypeString,
Optional: true,
},
"protocol": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"TCP", "HTTP", "HTTPS"}, false),
Optional: true,
},
"target_port": {
Type: schema.TypeInt,
Optional: true,
},
"port": {
Type: schema.TypeInt,
Optional: true,
},
},
},
},
"internet_slb_id": {
Type: schema.TypeString,
Optional: true,
},
"intranet_slb_id": {
Type: schema.TypeString,
Optional: true,
},
"internet_ip": {
Type: schema.TypeString,
Computed: true,
},
"intranet_ip": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudSaeApplicationCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "/pop/v1/sam/app/createApplication"
request := make(map[string]*string)
conn, err := client.NewServerlessClient()
if err != nil {
return WrapError(err)
}
request["AppName"] = StringPointer(d.Get("app_name").(string))
request["PackageType"] = StringPointer(d.Get("package_type").(string))
request["Replicas"] = StringPointer(strconv.Itoa(d.Get("replicas").(int)))
if v, ok := d.GetOk("app_description"); ok {
request["AppDescription"] = StringPointer(v.(string))
}
if v, ok := d.GetOkExists("auto_config"); ok {
request["AutoConfig"] = StringPointer(strconv.FormatBool(v.(bool)))
}
if v, ok := d.GetOk("command"); ok {
request["Command"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("command_args"); ok {
request["CommandArgs"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("config_map_mount_desc"); ok {
request["ConfigMapMountDesc"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("cpu"); ok {
request["Cpu"] = StringPointer(strconv.Itoa(v.(int)))
}
if v, ok := d.GetOk("custom_host_alias"); ok {
request["CustomHostAlias"] = StringPointer(v.(string))
}
if v, ok := d.GetOkExists("deploy"); ok {
request["Deploy"] = StringPointer(strconv.FormatBool(v.(bool)))
}
if v, ok := d.GetOk("edas_container_version"); ok {
request["EdasContainerVersion"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("envs"); ok {
request["Envs"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("image_url"); ok {
request["ImageUrl"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("jar_start_args"); ok {
request["JarStartArgs"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("jar_start_options"); ok {
request["JarStartOptions"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("jdk"); ok {
request["Jdk"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("liveness"); ok {
request["Liveness"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("memory"); ok {
request["Memory"] = StringPointer(strconv.Itoa(v.(int)))
}
if v, ok := d.GetOk("mount_desc"); ok {
request["MountDesc"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("mount_host"); ok {
request["MountHost"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("namespace_id"); ok {
request["NamespaceId"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("nas_id"); ok {
request["NasId"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("oss_ak_id"); ok {
request["OssAkId"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("oss_ak_secret"); ok {
request["OssAkSecret"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("oss_mount_descs"); ok {
request["OssMountDescs"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("package_url"); ok {
request["PackageUrl"] = StringPointer(v.(string))
}
request["PackageVersion"] = StringPointer(strconv.FormatInt(time.Now().Unix(), 10))
if v, ok := d.GetOk("php_arms_config_location"); ok {
request["PhpArmsConfigLocation"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("php_config"); ok {
request["PhpConfig"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("php_config_location"); ok {
request["PhpConfigLocation"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("post_start"); ok {
request["PostStart"] = StringPointer(v.(string))
}
if d.HasChange("pre_stop") {
request["PreStop"] = StringPointer(d.Get("pre_stop").(string))
}
if v, ok := d.GetOk("pre_stop"); ok {
request["PreStop"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("readiness"); ok {
request["Readiness"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("security_group_id"); ok {
request["SecurityGroupId"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("sls_configs"); ok {
request["SlsConfigs"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("termination_grace_period_seconds"); ok {
request["TerminationGracePeriodSeconds"] = StringPointer(strconv.Itoa(v.(int)))
}
if v, ok := d.GetOk("timezone"); ok {
request["Timezone"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("tomcat_config"); ok {
request["TomcatConfig"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("war_start_options"); ok {
request["WarStartOptions"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("web_container"); ok {
request["WebContainer"] = StringPointer(v.(string))
}
if v, exist := d.GetOk("vpc_id"); exist {
request["VpcId"] = StringPointer(v.(string))
}
if v, exist := d.GetOk("vswitch_id"); exist {
request["VSwitchId"] = StringPointer(v.(string))
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("POST"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_sae_application", "POST "+action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return WrapError(fmt.Errorf("%s failed, response: %v", "POST "+action, response))
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", "POST "+action, response))
}
responseData := response["Data"].(map[string]interface{})
d.SetId(fmt.Sprint(responseData["AppId"]))
return resourceAlicloudSaeApplicationUpdate(d, meta)
}
func resourceAlicloudSaeApplicationRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
saeService := SaeService{client}
object, err := saeService.DescribeSaeApplication(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_sae_application saeService.DescribeSaeApplication Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("app_description", object["AppDescription"])
d.Set("app_name", object["AppName"])
d.Set("command", object["Command"])
d.Set("command_args", object["CommandArgs"])
d.Set("config_map_mount_desc", object["ConfigMapMountDesc"])
if v, ok := object["Cpu"]; ok && fmt.Sprint(v) != "0" {
d.Set("cpu", formatInt(v))
}
d.Set("custom_host_alias", object["CustomHostAlias"])
d.Set("edas_container_version", object["EdasContainerVersion"])
d.Set("envs", object["Envs"])
d.Set("image_url", object["ImageUrl"])
d.Set("jar_start_args", object["JarStartArgs"])
d.Set("jar_start_options", object["JarStartOptions"])
d.Set("jdk", object["Jdk"])
d.Set("liveness", object["Liveness"])
if v, ok := object["Memory"]; ok && fmt.Sprint(v) != "0" {
d.Set("memory", formatInt(v))
}
if v, ok := object["MinReadyInstances"]; ok && fmt.Sprint(v) != "0" {
d.Set("min_ready_instances", formatInt(v))
}
if v, ok := object["MountDesc"].([]interface{}); ok {
mountDesc, err := convertListObjectToCommaSeparate(v)
if err != nil {
return WrapError(err)
}
d.Set("mount_desc", mountDesc)
}
d.Set("mount_host", object["MountHost"])
d.Set("namespace_id", object["NamespaceId"])
d.Set("nas_id", object["NasId"])
d.Set("oss_ak_id", object["OssAkId"])
d.Set("oss_ak_secret", object["OssAkSecret"])
d.Set("oss_mount_descs", object["OssMountDescs"])
d.Set("package_type", object["PackageType"])
d.Set("package_url", object["PackageUrl"])
d.Set("package_version", object["PackageVersion"])
d.Set("php_arms_config_location", object["PhpArmsConfigLocation"])
d.Set("php_config", object["PhpConfig"])
d.Set("php_config_location", object["PhpConfigLocation"])
d.Set("post_start", object["PostStart"])
d.Set("pre_stop", object["PreStop"])
d.Set("readiness", object["Readiness"])
if v, ok := object["Replicas"]; ok && fmt.Sprint(v) != "0" {
d.Set("replicas", formatInt(v))
}
d.Set("security_group_id", object["SecurityGroupId"])
d.Set("sls_configs", object["SlsConfigs"])
if v, ok := object["TerminationGracePeriodSeconds"]; ok && fmt.Sprint(v) != "0" {
d.Set("termination_grace_period_seconds", formatInt(v))
}
d.Set("timezone", object["Timezone"])
d.Set("tomcat_config", object["TomcatConfig"])
d.Set("vswitch_id", object["VSwitchId"])
d.Set("vpc_id", object["VpcId"])
d.Set("war_start_options", object["WarStartOptions"])
d.Set("web_container", object["WebContainer"])
describeApplicationStatusObject, err := saeService.DescribeApplicationStatus(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("status", describeApplicationStatusObject["CurrentStatus"])
describeApplicationSlbObject, err := saeService.DescribeApplicationSlb(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("internet_ip", describeApplicationSlbObject["InternetIp"])
d.Set("intranet_ip", describeApplicationSlbObject["IntranetIp"])
d.Set("intranet_slb_id", describeApplicationSlbObject["IntranetSlbId"])
d.Set("internet_slb_id", describeApplicationSlbObject["InternetSlbId"])
intranetArray := make([]interface{}, 0)
if v, ok := describeApplicationSlbObject["Intranet"]; ok {
for _, intranet := range v.([]interface{}) {
intranetObject := intranet.(map[string]interface{})
intranetObj := map[string]interface{}{
"https_cert_id": intranetObject["HttpsCertId"],
"protocol": intranetObject["Protocol"],
"target_port": intranetObject["TargetPort"],
"port": intranetObject["Port"],
}
intranetArray = append(intranetArray, intranetObj)
}
}
d.Set("intranet", intranetArray)
internetArray := make([]interface{}, 0)
if v, ok := describeApplicationSlbObject["Internet"]; ok {
for _, internet := range v.([]interface{}) {
internetObject := internet.(map[string]interface{})
internetObj := map[string]interface{}{
"https_cert_id": internetObject["HttpsCertId"],
"protocol": internetObject["Protocol"],
"target_port": internetObject["TargetPort"],
"port": internetObject["Port"],
}
internetArray = append(internetArray, internetObj)
}
}
d.Set("internet", internetArray)
return nil
}
func resourceAlicloudSaeApplicationUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewServerlessClient()
if err != nil {
return WrapError(err)
}
saeService := SaeService{client}
var response map[string]interface{}
update := false
d.Partial(true)
request := map[string]*string{
"AppId": StringPointer(d.Id()),
}
update = false
if d.HasChange("replicas") && !d.IsNewResource() {
update = true
}
request["Replicas"] = StringPointer(strconv.Itoa(d.Get("replicas").(int)))
if update {
action := "/pop/v1/sam/app/rescaleApplication"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("PUT"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Application.InvalidStatus", "Application.ChangerOrderRunning"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "POST "+action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return WrapError(fmt.Errorf("%s failed, response: %v", "POST "+action, response))
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", "POST "+action, response))
}
}
update = false
//DeployApplication
request = map[string]*string{
"AppId": StringPointer(d.Id()),
}
if d.HasChange("command") {
update = true
}
if v, ok := d.GetOk("command"); ok {
request["Command"] = StringPointer(v.(string))
}
if d.HasChange("command_args") {
update = true
}
if v, ok := d.GetOk("command_args"); ok {
request["CommandArgs"] = StringPointer(v.(string))
}
if d.HasChange("config_map_mount_desc") {
update = true
}
if v, ok := d.GetOk("config_map_mount_desc"); ok {
request["ConfigMapMountDesc"] = StringPointer(v.(string))
}
if d.HasChange("custom_host_alias") {
update = true
}
if v, ok := d.GetOk("custom_host_alias"); ok {
request["CustomHostAlias"] = StringPointer(v.(string))
}
if d.HasChange("edas_container_version") {
update = true
}
if v, ok := d.GetOk("edas_container_version"); ok {
request["EdasContainerVersion"] = StringPointer(v.(string))
}
if d.HasChange("envs") {
update = true
}
if v, ok := d.GetOk("envs"); ok {
request["Envs"] = StringPointer(v.(string))
}
if d.HasChange("image_url") {
update = true
}
if v, ok := d.GetOk("image_url"); ok {
request["ImageUrl"] = StringPointer(v.(string))
}
if d.HasChange("jar_start_args") {
update = true
}
if v, ok := d.GetOk("jar_start_args"); ok {
request["JarStartArgs"] = StringPointer(v.(string))
}
if d.HasChange("jar_start_options") {
update = true
}
if v, ok := d.GetOk("jar_start_options"); ok {
request["JarStartOptions"] = StringPointer(v.(string))
}
if d.HasChange("jdk") {
update = true
}
if v, ok := d.GetOk("jdk"); ok {
request["Jdk"] = StringPointer(v.(string))
}
if d.HasChange("liveness") {
update = true
}
if v, ok := d.GetOk("liveness"); ok {
request["Liveness"] = StringPointer(v.(string))
}
if d.HasChange("mount_desc") {
update = true
}
if v, ok := d.GetOk("mount_desc"); ok {
request["MountDesc"] = StringPointer(v.(string))
}
if d.HasChange("mount_host") {
update = true
}
if v, ok := d.GetOk("mount_host"); ok {
request["MountHost"] = StringPointer(v.(string))
}
if d.HasChange("nas_id") {
update = true
}
if v, ok := d.GetOk("nas_id"); ok {
request["NasId"] = StringPointer(v.(string))
}
if d.HasChange("oss_ak_id") {
update = true
}
if v, ok := d.GetOk("oss_ak_id"); ok {
request["OssAkId"] = StringPointer(v.(string))
}
if d.HasChange("oss_ak_secret") {
update = true
}
if v, ok := d.GetOk("oss_ak_secret"); ok {
request["OssAkSecret"] = StringPointer(v.(string))
}
if d.HasChange("oss_mount_descs") {
update = true
}
if v, ok := d.GetOk("oss_mount_descs"); ok {
request["OssMountDescs"] = StringPointer(v.(string))
}
if d.HasChange("package_url") {
update = true
}
if v, ok := d.GetOk("package_url"); ok {
request["PackageUrl"] = StringPointer(v.(string))
}
if d.HasChange("php_arms_config_location") {
update = true
}
if v, ok := d.GetOk("php_arms_config_location"); ok {
request["PhpArmsConfigLocation"] = StringPointer(v.(string))
}
if d.HasChange("php_config") {
update = true
}
if v, ok := d.GetOk("php_config"); ok {
request["PhpConfig"] = StringPointer(v.(string))
}
if d.HasChange("php_config_location") {
update = true
}
if v, ok := d.GetOk("php_config_location"); ok {
request["PhpConfigLocation"] = StringPointer(v.(string))
}
if d.HasChange("post_start") {
update = true
}
if v, ok := d.GetOk("post_start"); ok {
request["PostStart"] = StringPointer(v.(string))
}
if d.HasChange("pre_stop") {
update = true
}
if v, ok := d.GetOk("pre_stop"); ok {
request["PreStop"] = StringPointer(v.(string))
}
if d.HasChange("readiness") {
update = true
}
if v, ok := d.GetOk("readiness"); ok {
request["Readiness"] = StringPointer(v.(string))
}
if d.HasChange("sls_configs") {
update = true
}
if v, ok := d.GetOk("sls_configs"); ok {
request["SlsConfigs"] = StringPointer(v.(string))
}
if d.HasChange("termination_grace_period_seconds") {
update = true
}
if v, ok := d.GetOk("termination_grace_period_seconds"); ok {
request["TerminationGracePeriodSeconds"] = StringPointer(strconv.Itoa(v.(int)))
}
if d.HasChange("timezone") {
update = true
}
if v, ok := d.GetOk("timezone"); ok {
request["Timezone"] = StringPointer(v.(string))
}
if d.HasChange("tomcat_config") {
update = true
}
if v, ok := d.GetOk("tomcat_config"); ok {
request["TomcatConfig"] = StringPointer(v.(string))
}
if d.HasChange("war_start_options") {
update = true
}
if v, ok := d.GetOk("war_start_options"); ok {
request["WarStartOptions"] = StringPointer(v.(string))
}
if d.HasChange("web_container") {
update = true
}
if v, ok := d.GetOk("web_container"); ok {
request["WebContainer"] = StringPointer(v.(string))
}
if d.HasChange("auto_enable_application_scaling_rule") {
update = true
}
if v, ok := d.GetOk("auto_enable_application_scaling_rule"); ok {
request["AutoEnableApplicationScalingRule"] = StringPointer(strconv.FormatBool(v.(bool)))
}
if d.HasChange("min_ready_instances") {
update = true
}
if v, ok := d.GetOk("min_ready_instances"); ok {
request["MinReadyInstances"] = StringPointer(strconv.Itoa(v.(int)))
}
if v, ok := d.GetOk("batch_wait_time"); ok {
request["BatchWaitTime"] = StringPointer(strconv.Itoa(v.(int)))
}
if d.HasChange("change_order_desc") {
update = true
}
if v, ok := d.GetOk("change_order_desc"); ok {
request["ChangeOrderDesc"] = StringPointer(v.(string))
}
if d.HasChange("enable_ahas") {
update = true
}
if v, ok := d.GetOk("enable_ahas"); ok {
request["EnableAhas"] = StringPointer(v.(string))
}
if d.HasChange("enable_grey_tag_route") {
update = true
}
if v, ok := d.GetOkExists("enable_grey_tag_route"); ok {
request["EnableGreyTagRoute"] = StringPointer(v.(string))
}
if d.HasChange("update_strategy") {
update = true
}
if v, ok := d.GetOk("update_strategy"); ok {
request["UpdateStrategy"] = StringPointer(v.(string))
}
if update {
action := "/pop/v1/sam/app/deployApplication"
wait := incrementalWait(3*time.Second, 3*time.Second)
request["PackageVersion"] = StringPointer(strconv.FormatInt(time.Now().Unix(), 10))
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("POST"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Application.ChangerOrderRunning"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "POST "+action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return WrapError(fmt.Errorf("%s failed, response: %v", "POST "+action, response))
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", "POST "+action, response))
}
d.SetPartial("command")
d.SetPartial("command_args")
d.SetPartial("config_map_mount_desc")
d.SetPartial("custom_host_alias")
d.SetPartial("edas_container_version")
d.SetPartial("envs")
d.SetPartial("image_url")
d.SetPartial("jar_start_args")
d.SetPartial("jar_start_options")
d.SetPartial("jdk")
d.SetPartial("liveness")
d.SetPartial("mount_desc")
d.SetPartial("mount_host")
d.SetPartial("nas_id")
d.SetPartial("oss_ak_id")
d.SetPartial("oss_ak_secret")
d.SetPartial("oss_mount_descs")
d.SetPartial("package_url")
d.SetPartial("package_version")
d.SetPartial("php_arms_config_location")
d.SetPartial("php_config")
d.SetPartial("php_config_location")
d.SetPartial("post_start")
d.SetPartial("pre_stop")
d.SetPartial("readiness")
d.SetPartial("sls_configs")
d.SetPartial("min_ready_instances")
d.SetPartial("auto_enable_application_scaling_rule")
d.SetPartial("termination_grace_period_seconds")
d.SetPartial("timezone")
d.SetPartial("tomcat_config")
d.SetPartial("war_start_options")
d.SetPartial("web_container")
}
// update SLB
update = false
if err := saeService.UpdateSlb(d); err != nil {
return WrapError(err)
}
// 【Exists】update security_group_id
if d.HasChange("security_group_id") {
d.Partial(true)
request := map[string]*string{
"AppId": StringPointer(d.Id()),
}
if v, ok := d.GetOk("security_group_id"); ok {
request["SecurityGroupId"] = StringPointer(v.(string))
}
action := "/pop/v1/sam/app/updateAppSecurityGroup"
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("PUT"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Application.ChangerOrderRunning"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "PUT "+action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return WrapError(fmt.Errorf("%s failed, response: %v", "PUT "+action, response))
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", "PUT "+action, response))
}
d.SetPartial("security_group_id")
}
// 【Exists】update rescaleApplicationVertically(CPU+Memory)
if (d.HasChange("cpu") || d.HasChange("memory")) && !d.IsNewResource() {
d.Partial(true)
request := map[string]*string{
"AppId": StringPointer(d.Id()),
}
if v, ok := d.GetOk("cpu"); ok {
request["Cpu"] = StringPointer(strconv.Itoa(v.(int)))
}
if v, ok := d.GetOk("memory"); ok {
request["Memory"] = StringPointer(strconv.Itoa(v.(int)))
}
action := "/pop/v1/sam/app/rescaleApplicationVertically"
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("POST"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Application.ChangerOrderRunning"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "POST "+action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return WrapError(fmt.Errorf("%s failed, response: %v", "POST "+action, response))
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", "POST "+action, response))
}
d.SetPartial("cpu")
d.SetPartial("memory")
}
// 【Exists】update status
if d.HasChange("status") {
d.Partial(true)
object, err := saeService.DescribeApplicationStatus(d.Id())
if err != nil {
return WrapError(err)
}
target := d.Get("status").(string)
if object["CurrentStatus"].(string) != target {
if target == "RUNNING" {
request := map[string]*string{
"AppId": StringPointer(d.Id()),
}
action := "/pop/v1/sam/app/startApplication"
conn, err := client.NewServerlessClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("PUT"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Application.ChangerOrderRunning"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return WrapError(fmt.Errorf("%s failed, response: %v", "Put "+action, response))
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", "Put "+action, response))
}
}
if target == "STOPPED" {
request := map[string]*string{
"AppId": StringPointer(d.Id()),
}
action := "/pop/v1/sam/app/stopApplication"
conn, err := client.NewServerlessClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("PUT"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Application.InvalidStatus"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "PUT "+action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return WrapError(fmt.Errorf("%s failed, response: %v", "Put "+action, response))
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", "Put "+action, response))
}
}
d.SetPartial("status")
}
}
d.Partial(false)
stateConf := BuildStateConf([]string{}, []string{"SUCCESS"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, saeService.SaeApplicationStateRefreshFunc(d.Id(), []string{"FAIL", "ABORT", "SYSTEM_FAIL"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudSaeApplicationRead(d, meta)
}
func resourceAlicloudSaeApplicationDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "/pop/v1/sam/app/deleteApplication"
var response map[string]interface{}
conn, err := client.NewServerlessClient()
if err != nil {
return WrapError(err)
}
request := map[string]*string{
"AppId": StringPointer(d.Id()),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("DELETE"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Application.ChangerOrderRunning"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DELETE "+action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return WrapError(fmt.Errorf("%s failed, response: %v", "DELETE "+action, response))
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", "DELETE "+action, response))
}
action = "/pop/v1/sam/app/describeApplicationConfig"
request = map[string]*string{
"AppId": StringPointer(d.Id()),
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait = incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("GET"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if response != nil {
err = fmt.Errorf("application have not been destroyed yet")
return resource.RetryableError(err)
}
return nil
})
if err != nil {
return WrapError(err)
}
return nil
}
func convertListObjectToCommaSeparate(configured []interface{}) (string, error) {
if len(configured) < 1 {
return "", nil
}
result := "["
for i, v := range configured {
rail := ","
if i == len(configured)-1 {
rail = ""
}
vv, err := json.Marshal(v)
if err != nil {
return "", err
}
result += string(vv) + rail
}
return result + "]", nil
}
package alicloud
import (
"encoding/json"
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudSaeConfigMap() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSaeConfigMapCreate,
Read: resourceAlicloudSaeConfigMapRead,
Update: resourceAlicloudSaeConfigMapUpdate,
Delete: resourceAlicloudSaeConfigMapDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"data": {
Type: schema.TypeString,
Required: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"namespace_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudSaeConfigMapCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "/pop/v1/sam/configmap/configMap"
request := make(map[string]*string)
conn, err := client.NewServerlessClient()
if err != nil {
return WrapError(err)
}
request["Data"] = StringPointer(d.Get("data").(string))
if v, ok := d.GetOk("description"); ok {
request["Description"] = StringPointer(v.(string))
}
request["Name"], request["NamespaceId"] = StringPointer(d.Get("name").(string)), StringPointer(d.Get("namespace_id").(string))
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("POST"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_sae_config_map", "POST "+action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return WrapError(fmt.Errorf("%s failed, response: %v", "POST "+action, response))
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
responseData := response["Data"].(map[string]interface{})
d.SetId(fmt.Sprint(responseData["ConfigMapId"]))
return resourceAlicloudSaeConfigMapRead(d, meta)
}
func resourceAlicloudSaeConfigMapRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
saeService := SaeService{client}
object, err := saeService.DescribeSaeConfigMap(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_sae_config_map saeService.DescribeSaeConfigMap Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
resp, err := json.Marshal(object["Data"])
if err != nil {
return WrapError(err)
}
d.Set("data", string(resp))
d.Set("description", object["Description"])
d.Set("name", object["Name"])
d.Set("namespace_id", object["NamespaceId"])
return nil
}
func resourceAlicloudSaeConfigMapUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]*string{
"ConfigMapId": StringPointer(d.Id()),
}
if d.HasChange("data") {
update = true
}
request["Data"] = StringPointer(d.Get("data").(string))
if d.HasChange("description") {
update = true
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = StringPointer(v.(string))
}
if update {
action := "/pop/v1/sam/configmap/configMap"
conn, err := client.NewServerlessClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("PUT"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"NotFound.ConfigMap"}) {
return WrapErrorf(Error(GetNotFoundMessage("SAE:ConfigMap", d.Id())), NotFoundMsg, ProviderERROR)
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "PUT "+action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return WrapError(fmt.Errorf("%s failed, response: %v", "Put "+action, response))
}
addDebug(action, response, request)
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
}
return resourceAlicloudSaeConfigMapRead(d, meta)
}
func resourceAlicloudSaeConfigMapDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "/pop/v1/sam/configmap/configMap"
var response map[string]interface{}
conn, err := client.NewServerlessClient()
if err != nil {
return WrapError(err)
}
request := map[string]*string{
"ConfigMapId": StringPointer(d.Id()),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("DELETE"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DELETE "+action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return WrapError(fmt.Errorf("%s failed, response: %v", "DELETE "+action, response))
}
addDebug(action, response, request)
if IsExpectedErrorCodes(fmt.Sprint(response["Code"]), []string{"NotFound.ConfigMap"}) {
return nil
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
return nil
}
package alicloud
import (
"fmt"
"log"
"strconv"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudSaeIngress() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSaeIngressCreate,
Read: resourceAlicloudSaeIngressRead,
Update: resourceAlicloudSaeIngressUpdate,
Delete: resourceAlicloudSaeIngressDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"cert_id": {
Type: schema.TypeString,
Optional: true,
},
"default_rule": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"app_id": {
Type: schema.TypeString,
Optional: true,
},
"app_name": {
Type: schema.TypeString,
Optional: true,
},
"container_port": {
Type: schema.TypeInt,
Optional: true,
},
},
},
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"listener_port": {
Type: schema.TypeInt,
Required: true,
},
"namespace_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"rules": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"app_id": {
Type: schema.TypeString,
Required: true,
},
"app_name": {
Type: schema.TypeString,
Required: true,
},
"container_port": {
Type: schema.TypeInt,
Required: true,
},
"domain": {
Type: schema.TypeString,
Required: true,
},
"path": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"slb_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudSaeIngressCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "/pop/v1/sam/ingress/Ingress"
request := make(map[string]*string)
conn, err := client.NewServerlessClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("cert_id"); ok {
request["CertId"] = StringPointer(v.(string))
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = StringPointer(v.(string))
}
request["ListenerPort"] = StringPointer(strconv.Itoa(d.Get("listener_port").(int)))
request["NamespaceId"] = StringPointer(d.Get("namespace_id").(string))
defaultrulesMap := map[string]interface{}{}
for _, rules := range d.Get("default_rule").(*schema.Set).List() {
rulesArg := rules.(map[string]interface{})
defaultrulesMap["appId"] = rulesArg["app_id"]
defaultrulesMap["containerPort"] = rulesArg["container_port"]
}
if v, err := convertArrayObjectToJsonString(defaultrulesMap); err != nil {
return WrapError(err)
} else {
request["DefaultRule"] = StringPointer(v)
}
rulesMaps := make([]map[string]interface{}, 0)
for _, rules := range d.Get("rules").(*schema.Set).List() {
rulesArg := rules.(map[string]interface{})
rulesMap := map[string]interface{}{}
rulesMap["appId"] = rulesArg["app_id"]
rulesMap["appName"] = rulesArg["app_name"]
rulesMap["containerPort"] = rulesArg["container_port"]
rulesMap["domain"] = rulesArg["domain"]
rulesMap["path"] = rulesArg["path"]
rulesMaps = append(rulesMaps, rulesMap)
}
if v, err := convertArrayObjectToJsonString(rulesMaps); err != nil {
return WrapError(err)
} else {
request["Rules"] = StringPointer(v)
}
request["SlbId"] = StringPointer(d.Get("slb_id").(string))
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("POST"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_sae_ingress", action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return WrapError(fmt.Errorf("%s failed, response: %v", "POST "+action, response))
}
addDebug(action, response, request)
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
responseData := response["Data"].(map[string]interface{})
d.SetId(fmt.Sprint(responseData["IngressId"]))
return resourceAlicloudSaeIngressRead(d, meta)
}
func resourceAlicloudSaeIngressRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
saeService := SaeService{client}
object, err := saeService.DescribeSaeIngress(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_sae_ingress saeService.DescribeSaeIngress Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
if v, ok := object["CertId"]; ok && v.(string) != "" {
d.Set("cert_id", v)
}
d.Set("description", object["Description"])
defaultRuleConfig := make([]map[string]interface{}, 0)
if defaultRule, ok := object["DefaultRule"]; ok {
defaultRule_convert := defaultRule.(map[string]interface{})
defaultRuleData := make(map[string]interface{}, 0)
defaultRuleData["app_id"] = defaultRule_convert["AppId"]
defaultRuleData["container_port"] = defaultRule_convert["ContainerPort"]
defaultRuleConfig = append(defaultRuleConfig, defaultRuleData)
d.Set("default_rule", defaultRuleConfig)
}
config := make([]map[string]interface{}, 0)
if quotaDimension, ok := object["Rules"]; ok {
quotaDimension_convert := quotaDimension.([]interface{})
for _, obj := range quotaDimension_convert {
obj_convert := obj.(map[string]interface{})
data := make(map[string]interface{}, 0)
data["app_id"] = obj_convert["AppId"]
data["app_name"] = obj_convert["AppName"]
data["container_port"] = obj_convert["ContainerPort"]
data["domain"] = obj_convert["Domain"]
data["path"] = obj_convert["Path"]
config = append(config, data)
}
d.Set("rules", config)
}
if v, ok := object["ListenerPort"]; ok && fmt.Sprint(v) != "0" {
d.Set("listener_port", formatInt(v))
}
d.Set("namespace_id", object["NamespaceId"])
d.Set("slb_id", object["SlbId"])
return nil
}
func resourceAlicloudSaeIngressUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]*string{
"IngressId": StringPointer(d.Id()),
}
if d.HasChange("cert_id") {
update = true
if v, ok := d.GetOk("cert_id"); ok {
request["CertId"] = StringPointer(v.(string))
}
}
if d.HasChange("default_rule") {
update = true
defaultrulesMap := map[string]interface{}{}
for _, rules := range d.Get("default_rule").(*schema.Set).List() {
rulesArg := rules.(map[string]interface{})
defaultrulesMap["appId"] = rulesArg["app_id"]
defaultrulesMap["containerPort"] = rulesArg["container_port"]
}
if v, err := convertArrayObjectToJsonString(defaultrulesMap); err == nil {
request["DefaultRule"] = StringPointer(v)
} else {
return WrapError(err)
}
}
if d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
request["Description"] = StringPointer(v.(string))
}
}
if d.HasChange("listener_port") {
update = true
request["ListenerPort"] = StringPointer(strconv.Itoa(d.Get("listener_port").(int)))
}
if d.HasChange("rules") {
update = true
rulesMaps := make([]map[string]interface{}, 0)
for _, rules := range d.Get("rules").(*schema.Set).List() {
rulesArg := rules.(map[string]interface{})
rulesMap := map[string]interface{}{}
rulesMap["appId"] = rulesArg["app_id"]
rulesMap["appName"] = rulesArg["app_name"]
rulesMap["containerPort"] = rulesArg["container_port"]
rulesMap["domain"] = rulesArg["domain"]
rulesMap["path"] = rulesArg["path"]
rulesMaps = append(rulesMaps, rulesMap)
}
if v, err := convertArrayObjectToJsonString(rulesMaps); err == nil {
request["Rules"] = StringPointer(v)
} else {
return WrapError(err)
}
}
if update {
action := "/pop/v1/sam/ingress/Ingress"
conn, err := client.NewServerlessClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("PUT"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", "PUT "+action, response))
}
}
return resourceAlicloudSaeIngressRead(d, meta)
}
func resourceAlicloudSaeIngressDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "/pop/v1/sam/ingress/Ingress"
var response map[string]interface{}
conn, err := client.NewServerlessClient()
if err != nil {
return WrapError(err)
}
request := map[string]*string{
"IngressId": StringPointer(d.Id()),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("DELETE"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", "DELETE "+action, response))
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudSaeNamespace() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSaeNamespaceCreate,
Read: resourceAlicloudSaeNamespaceRead,
Update: resourceAlicloudSaeNamespaceUpdate,
Delete: resourceAlicloudSaeNamespaceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Delete: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"namespace_description": {
Type: schema.TypeString,
Optional: true,
},
"namespace_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"namespace_name": {
Type: schema.TypeString,
Required: true,
},
},
}
}
func resourceAlicloudSaeNamespaceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "/pop/v1/paas/namespace"
request := make(map[string]*string)
conn, err := client.NewServerlessClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("namespace_description"); ok {
request["NamespaceDescription"] = StringPointer(v.(string))
}
request["NamespaceId"], request["NamespaceName"] = StringPointer(d.Get("namespace_id").(string)), StringPointer(d.Get("namespace_name").(string))
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("POST"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_sae_namespace", "POST "+action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return WrapError(fmt.Errorf("%s failed, response: %v", "POST "+action, response))
}
addDebug(action, response, request)
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", "POST "+action, response))
}
d.SetId(*request["NamespaceId"])
return resourceAlicloudSaeNamespaceRead(d, meta)
}
func resourceAlicloudSaeNamespaceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
saeService := SaeService{client}
object, err := saeService.DescribeSaeNamespace(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_sae_namespace saeService.DescribeSaeNamespace Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("namespace_id", d.Id())
d.Set("namespace_description", object["NamespaceDescription"])
d.Set("namespace_name", object["NamespaceName"])
return nil
}
func resourceAlicloudSaeNamespaceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]*string{
"NamespaceId": StringPointer(d.Id()),
}
if d.HasChange("namespace_name") {
update = true
}
request["NamespaceName"] = StringPointer(d.Get("namespace_name").(string))
if d.HasChange("namespace_description") {
update = true
}
request["NamespaceDescription"] = StringPointer(d.Get("namespace_description").(string))
if update {
action := "/pop/v1/paas/namespace"
conn, err := client.NewServerlessClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("PUT"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidNamespaceId.NotFound"}) {
return WrapErrorf(Error(GetNotFoundMessage("SAE:Namespace", d.Id())), NotFoundMsg, ProviderERROR)
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "PUT "+action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return WrapError(fmt.Errorf("%s failed, response: %v", "Put "+action, response))
}
addDebug(action, response, request)
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", "Put "+action, response))
}
}
return resourceAlicloudSaeNamespaceRead(d, meta)
}
func resourceAlicloudSaeNamespaceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "/pop/v1/paas/namespace"
var response map[string]interface{}
conn, err := client.NewServerlessClient()
if err != nil {
return WrapError(err)
}
request := map[string]*string{
"NamespaceId": StringPointer(d.Id()),
}
wait := incrementalWait(3*time.Second, 1*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("DELETE"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidNamespaceId.NotFound"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "DELETE "+action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return WrapError(fmt.Errorf("%s failed, response: %v", "DELETE "+action, response))
}
addDebug(action, response, request)
if IsExpectedErrorCodes(fmt.Sprint(response["Code"]), []string{"InvalidNamespaceId.NotFound"}) {
return nil
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", "AlicloudSaeNamespaceDelete", response))
}
return nil
}
package alicloud
import (
"github.com/aliyun/alibaba-cloud-sdk-go/services/smartag"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudSagAcl() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSagAclCreate,
Read: resourceAlicloudSagAclRead,
Update: resourceAlicloudSagAclUpdate,
Delete: resourceAlicloudSagAclDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(2, 128),
},
},
}
}
func resourceAlicloudSagAclCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := smartag.CreateCreateACLRequest()
request.Name = d.Get("name").(string)
raw, err := client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.CreateACL(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_sag_acl", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*smartag.CreateACLResponse)
d.SetId(response.AclId)
return resourceAlicloudSagAclRead(d, meta)
}
func resourceAlicloudSagAclRead(d *schema.ResourceData, meta interface{}) error {
sagService := SagService{meta.(*connectivity.AliyunClient)}
object, err := sagService.DescribeSagAcl(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", object.Name)
return nil
}
func resourceAlicloudSagAclUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
if d.HasChange("name") {
request := smartag.CreateModifyACLRequest()
request.AclId = d.Id()
request.Name = d.Get("name").(string)
raw, err := client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.ModifyACL(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
return resourceAlicloudSagAclRead(d, meta)
}
func resourceAlicloudSagAclDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sagService := SagService{client}
request := smartag.CreateDeleteACLRequest()
request.AclId = d.Id()
raw, err := client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.DeleteACL(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ParameterSagACLId"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(sagService.WaitForSagAcl(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/smartag"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudSagAclRule() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSagAclRuleCreate,
Read: resourceAlicloudSagAclRuleRead,
Update: resourceAlicloudSagAclRuleUpdate,
Delete: resourceAlicloudSagAclRuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"acl_id": {
Type: schema.TypeString,
Required: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"policy": {
Type: schema.TypeString,
Required: true,
},
"ip_protocol": {
Type: schema.TypeString,
Required: true,
},
"direction": {
Type: schema.TypeString,
Required: true,
},
"source_cidr": {
Type: schema.TypeString,
Required: true,
},
"source_port_range": {
Type: schema.TypeString,
Required: true,
},
"dest_cidr": {
Type: schema.TypeString,
Required: true,
},
"dest_port_range": {
Type: schema.TypeString,
Required: true,
},
"priority": {
Type: schema.TypeInt,
Optional: true,
},
},
}
}
func resourceAlicloudSagAclRuleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := smartag.CreateAddACLRuleRequest()
request.AclId = d.Get("acl_id").(string)
request.Policy = d.Get("policy").(string)
request.IpProtocol = d.Get("ip_protocol").(string)
request.Direction = d.Get("direction").(string)
request.SourceCidr = d.Get("source_cidr").(string)
request.SourcePortRange = d.Get("source_port_range").(string)
request.DestCidr = d.Get("dest_cidr").(string)
request.DestPortRange = d.Get("dest_port_range").(string)
if v, ok := d.GetOk("description"); ok && v.(string) != "" {
request.Description = v.(string)
}
if v, ok := d.GetOk("priority"); ok && v.(int) != 0 {
request.Priority = requests.NewInteger(v.(int))
}
raw, err := client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.AddACLRule(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_sag_acl_rule", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*smartag.AddACLRuleResponse)
d.SetId(fmt.Sprintf("%s%s%s", response.AclId, COLON_SEPARATED, response.AcrId))
return resourceAlicloudSagAclRuleRead(d, meta)
}
func resourceAlicloudSagAclRuleRead(d *schema.ResourceData, meta interface{}) error {
sagService := SagService{meta.(*connectivity.AliyunClient)}
object, err := sagService.DescribeSagAclRule(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("acl_id", object.AclId)
d.Set("description", object.Description)
d.Set("policy", object.Policy)
d.Set("ip_protocol", object.IpProtocol)
d.Set("direction", object.Direction)
d.Set("source_cidr", object.SourceCidr)
d.Set("source_port_range", object.SourcePortRange)
d.Set("dest_cidr", object.DestCidr)
d.Set("dest_port_range", object.DestPortRange)
d.Set("priority", object.Priority)
return nil
}
func resourceAlicloudSagAclRuleUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
update := false
request := smartag.CreateModifyACLRuleRequest()
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request.AclId = parts[0]
request.AcrId = parts[1]
if d.HasChange("description") {
request.Description = d.Get("description").(string)
update = true
}
if d.HasChange("policy") {
request.Policy = d.Get("policy").(string)
update = true
}
if d.HasChange("ip_protocol") {
request.IpProtocol = d.Get("ip_protocol").(string)
update = true
}
if d.HasChange("direction") {
request.Direction = d.Get("direction").(string)
update = true
}
if d.HasChange("source_cidr") {
request.SourceCidr = d.Get("source_cidr").(string)
update = true
}
if d.HasChange("source_port_range") {
request.SourcePortRange = d.Get("source_port_range").(string)
update = true
}
if d.HasChange("dest_cidr") {
request.DestCidr = d.Get("dest_cidr").(string)
update = true
}
if d.HasChange("dest_port_range") {
request.DestPortRange = d.Get("dest_port_range").(string)
update = true
}
if d.HasChange("priority") {
request.Priority = requests.NewInteger(d.Get("priority").(int))
update = true
}
if update {
raw, err := client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.ModifyACLRule(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
return resourceAlicloudSagAclRuleRead(d, meta)
}
func resourceAlicloudSagAclRuleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sagService := SagService{client}
request := smartag.CreateDeleteACLRuleRequest()
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request.AclId = parts[0]
request.AcrId = parts[1]
raw, err := client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.DeleteACLRule(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ParameterSagACLRuleId"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(sagService.WaitForSagAclRule(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"fmt"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/smartag"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudSagClientUser() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSagClientUserCreate,
Read: resourceAlicloudSagClientUserRead,
Update: resourceAlicloudSagClientUserUpdate,
Delete: resourceAlicloudSagClientUserDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"sag_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"bandwidth": {
Type: schema.TypeInt,
Required: true,
},
"user_mail": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"client_ip": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.SingleIP(),
},
"user_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(2, 128),
},
"password": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
DiffSuppressFunc: sagClientUserPasswordSuppressFunc,
},
"kms_encrypted_password": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: kmsDiffSuppressFunc,
},
"kms_encryption_context": {
Type: schema.TypeMap,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("kms_encrypted_password").(string) == ""
},
Elem: schema.TypeString,
},
},
}
}
func resourceAlicloudSagClientUserCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := smartag.CreateCreateSmartAccessGatewayClientUserRequest()
request.SmartAGId = d.Get("sag_id").(string)
request.UserMail = d.Get("user_mail").(string)
request.Bandwidth = requests.NewInteger(d.Get("bandwidth").(int))
if v, ok := d.GetOk("client_ip"); ok && v.(string) != "" {
request.ClientIp = v.(string)
}
if v, ok := d.GetOk("user_name"); ok && v.(string) != "" {
request.UserName = v.(string)
password := d.Get("password").(string)
kmsPassword := d.Get("kms_encrypted_password").(string)
if password == "" && kmsPassword == "" {
return WrapError(Error("One of the 'password' and 'kms_encrypted_password' should be set when 'user_name' was set."))
}
if password != "" {
request.Password = password
} else {
kmsService := KmsService{client}
decryptResp, err := kmsService.Decrypt(kmsPassword, d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return WrapError(err)
}
request.Password = decryptResp
}
}
raw, err := client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.CreateSmartAccessGatewayClientUser(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_sag_client_user", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*smartag.CreateSmartAccessGatewayClientUserResponse)
d.SetId(fmt.Sprintf("%s%s%s", d.Get("sag_id").(string), COLON_SEPARATED, response.UserName))
return resourceAlicloudSagClientUserRead(d, meta)
}
func resourceAlicloudSagClientUserRead(d *schema.ResourceData, meta interface{}) error {
sagService := SagService{meta.(*connectivity.AliyunClient)}
object, err := sagService.DescribeSagClientUser(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
parts, _ := ParseResourceId(d.Id(), 2)
d.Set("sag_id", parts[0])
d.Set("bandwidth", object.Bandwidth)
d.Set("user_mail", object.UserMail)
d.Set("client_ip", object.ClientIp)
d.Set("user_name", object.UserName)
return nil
}
func resourceAlicloudSagClientUserUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
if d.HasChange("bandwidth") {
request := smartag.CreateModifySmartAccessGatewayClientUserRequest()
request.SmartAGId = parts[0]
request.UserName = parts[1]
request.Bandwidth = requests.NewInteger(d.Get("bandwidth").(int))
raw, err := client.WithSagClient(func(ccnClient *smartag.Client) (interface{}, error) {
return ccnClient.ModifySmartAccessGatewayClientUser(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
return resourceAlicloudSagClientUserRead(d, meta)
}
func resourceAlicloudSagClientUserDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sagService := SagService{client}
request := smartag.CreateDeleteSmartAccessGatewayClientUserRequest()
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request.SmartAGId = parts[0]
request.UserName = parts[1]
raw, err := client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.DeleteSmartAccessGatewayClientUser(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ParameterSagClientId"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(sagService.WaitForSagClientUser(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/smartag"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudSagDnatEntry() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSagDnatCreate,
Read: resourceAlicloudSagDnatRead,
Delete: resourceAlicloudSagDnatDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"sag_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Intranet", "Internet"}, false),
},
"ip_protocol": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"tcp", "udp", "any"}, false),
},
"external_ip": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.SingleIP(),
DiffSuppressFunc: sagDnatEntryTypeDiffSuppressFunc,
},
"external_port": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"internal_ip": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.SingleIP(),
},
"internal_port": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudSagDnatCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := smartag.CreateAddDnatEntryRequest()
request.SagId = d.Get("sag_id").(string)
request.Type = d.Get("type").(string)
request.IpProtocol = d.Get("ip_protocol").(string)
request.ExternalIp = d.Get("external_ip").(string)
request.InternalIp = d.Get("internal_ip").(string)
request.ExternalPort = d.Get("external_port").(string)
request.InternalPort = d.Get("internal_port").(string)
raw, err := client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.AddDnatEntry(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_sag_dnat_entry", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*smartag.AddDnatEntryResponse)
d.SetId(fmt.Sprintf("%s%s%s", request.SagId, COLON_SEPARATED, response.DnatEntryId))
return resourceAlicloudSagDnatRead(d, meta)
}
func resourceAlicloudSagDnatRead(d *schema.ResourceData, meta interface{}) error {
sagService := SagService{meta.(*connectivity.AliyunClient)}
object, err := sagService.DescribeSagDnatEntry(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("sag_id", object.SagId)
d.Set("type", object.Type)
d.Set("ip_protocol", object.IpProtocol)
d.Set("external_ip", object.ExternalIp)
d.Set("external_port", object.ExternalPort)
d.Set("internal_ip", object.InternalIp)
d.Set("internal_port", object.InternalPort)
return nil
}
func resourceAlicloudSagDnatDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sagService := SagService{client}
request := smartag.CreateDeleteDnatEntryRequest()
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request.SagId = parts[0]
request.DnatEntryId = parts[1]
raw, err := client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.DeleteDnatEntry(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ParameterSagClientId"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(sagService.WaitForSagDnatEntry(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"github.com/aliyun/alibaba-cloud-sdk-go/services/smartag"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudSagQos() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSagQosCreate,
Read: resourceAlicloudSagQosRead,
Update: resourceAlicloudSagQosUpdate,
Delete: resourceAlicloudSagQosDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(2, 128),
},
},
}
}
func resourceAlicloudSagQosCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := smartag.CreateCreateQosRequest()
request.QosName = d.Get("name").(string)
raw, err := client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.CreateQos(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_sag_qos", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*smartag.CreateQosResponse)
d.SetId(response.QosId)
return resourceAlicloudSagQosRead(d, meta)
}
func resourceAlicloudSagQosRead(d *schema.ResourceData, meta interface{}) error {
sagService := SagService{meta.(*connectivity.AliyunClient)}
object, err := sagService.DescribeSagQos(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", object.QosName)
return nil
}
func resourceAlicloudSagQosUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
if d.HasChange("name") {
request := smartag.CreateModifyQosRequest()
request.QosId = d.Id()
request.QosName = d.Get("name").(string)
raw, err := client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.ModifyQos(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
return resourceAlicloudSagQosRead(d, meta)
}
func resourceAlicloudSagQosDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sagService := SagService{client}
request := smartag.CreateDeleteQosRequest()
request.QosId = d.Id()
raw, err := client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.DeleteQos(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ParameterSagQosId"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(sagService.WaitForSagQos(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"fmt"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/smartag"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudSagQosCar() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSagQosCarCreate,
Read: resourceAlicloudSagQosCarRead,
Update: resourceAlicloudSagQosCarUpdate,
Delete: resourceAlicloudSagQosCarDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"qos_id": {
Type: schema.TypeString,
Required: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 128),
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"priority": {
Type: schema.TypeInt,
Required: true,
},
"limit_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"Absolute", "Percent"}, false),
},
"min_bandwidth_abs": {
Type: schema.TypeInt,
Optional: true,
},
"max_bandwidth_abs": {
Type: schema.TypeInt,
Optional: true,
},
"min_bandwidth_percent": {
Type: schema.TypeInt,
Optional: true,
},
"max_bandwidth_percent": {
Type: schema.TypeInt,
Optional: true,
},
"percent_source_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"InternetUpBandwidth", "CcnBandwidth"}, false),
Default: "InternetUpBandwidth",
},
},
}
}
func resourceAlicloudSagQosCarCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := smartag.CreateCreateQosCarRequest()
request.QosId = d.Get("qos_id").(string)
request.Priority = requests.NewInteger(d.Get("priority").(int))
request.LimitType = d.Get("limit_type").(string)
if v, ok := d.GetOk("name"); ok && v.(string) != "" {
request.Name = v.(string)
}
if v, ok := d.GetOk("description"); ok && v.(string) != "" {
request.Description = v.(string)
}
if v, ok := d.GetOk("limit_type"); ok && v.(string) == "Absolute" {
request.MinBandwidthAbs = requests.NewInteger(d.Get("min_bandwidth_abs").(int))
request.MaxBandwidthAbs = requests.NewInteger(d.Get("max_bandwidth_abs").(int))
}
if v, ok := d.GetOk("limit_type"); ok && v.(string) == "Percent" {
request.MinBandwidthPercent = requests.NewInteger(d.Get("min_bandwidth_percent").(int))
request.MaxBandwidthPercent = requests.NewInteger(d.Get("max_bandwidth_percent").(int))
request.PercentSourceType = d.Get("percent_source_type").(string)
}
var response *smartag.CreateQosCarResponse
err := resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.CreateQosCar(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ResourceInOperating"}) {
time.Sleep(2 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*smartag.CreateQosCarResponse)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_sag_qos_car", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprintf("%s%s%s", response.QosId, COLON_SEPARATED, response.QosCarId))
return resourceAlicloudSagQosCarRead(d, meta)
}
func resourceAlicloudSagQosCarRead(d *schema.ResourceData, meta interface{}) error {
sagService := SagService{meta.(*connectivity.AliyunClient)}
object, err := sagService.DescribeSagQosCar(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("qos_id", object.QosId)
d.Set("name", object.Name)
d.Set("description", object.Description)
d.Set("priority", object.Priority)
d.Set("limit_type", object.LimitType)
d.Set("min_bandwidth_abs", object.MinBandwidthAbs)
d.Set("max_bandwidth_abs", object.MaxBandwidthAbs)
d.Set("min_bandwidth_percent", object.MinBandwidthPercent)
d.Set("max_bandwidth_percent", object.MaxBandwidthPercent)
d.Set("percent_source_type", object.PercentSourceType)
return nil
}
func resourceAlicloudSagQosCarUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
update := false
request := smartag.CreateModifyQosCarRequest()
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request.QosId = parts[0]
request.QosCarId = parts[1]
if d.HasChange("name") {
request.Name = d.Get("name").(string)
update = true
}
if d.HasChange("description") {
request.Description = d.Get("description").(string)
update = true
}
if d.HasChange("priority") {
request.Priority = requests.NewInteger(d.Get("priority").(int))
update = true
}
if d.HasChange("limit_type") {
request.LimitType = d.Get("limit_type").(string)
update = true
}
if d.HasChange("min_bandwidth_abs") {
request.MinBandwidthAbs = requests.NewInteger(d.Get("min_bandwidth_abs").(int))
update = true
}
if d.HasChange("max_bandwidth_abs") {
request.MaxBandwidthAbs = requests.NewInteger(d.Get("max_bandwidth_abs").(int))
update = true
}
if d.HasChange("min_bandwidth_percent") {
request.MinBandwidthPercent = requests.NewInteger(d.Get("min_bandwidth_percent").(int))
update = true
}
if d.HasChange("max_bandwidth_percent") {
request.MaxBandwidthPercent = requests.NewInteger(d.Get("max_bandwidth_percent").(int))
update = true
}
if d.HasChange("percent_source_type") {
request.PercentSourceType = d.Get("percent_source_type").(string)
update = true
}
if update {
raw, err := client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.ModifyQosCar(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
return resourceAlicloudSagQosCarRead(d, meta)
}
func resourceAlicloudSagQosCarDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sagService := SagService{client}
request := smartag.CreateDeleteQosCarRequest()
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request.QosId = parts[0]
request.QosCarId = parts[1]
if err := resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.DeleteQosCar(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ResourceInOperating"}) {
time.Sleep(2 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}); err != nil {
if IsExpectedErrors(err, []string{"ParameterSagQosCarId"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(sagService.WaitForSagQosCar(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"fmt"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/smartag"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudSagQosPolicy() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSagQosPolicyCreate,
Read: resourceAlicloudSagQosPolicyRead,
Update: resourceAlicloudSagQosPolicyUpdate,
Delete: resourceAlicloudSagQosPolicyDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"qos_id": {
Type: schema.TypeString,
Required: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 128),
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"priority": {
Type: schema.TypeInt,
Required: true,
},
"ip_protocol": {
Type: schema.TypeString,
Required: true,
},
"source_cidr": {
Type: schema.TypeString,
Required: true,
},
"source_port_range": {
Type: schema.TypeString,
Required: true,
},
"dest_cidr": {
Type: schema.TypeString,
Required: true,
},
"dest_port_range": {
Type: schema.TypeString,
Required: true,
},
"start_time": {
Type: schema.TypeString,
Optional: true,
},
"end_time": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudSagQosPolicyCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := smartag.CreateCreateQosPolicyRequest()
request.QosId = d.Get("qos_id").(string)
request.Priority = requests.NewInteger(d.Get("priority").(int))
request.IpProtocol = d.Get("ip_protocol").(string)
request.SourceCidr = d.Get("source_cidr").(string)
request.SourcePortRange = d.Get("source_port_range").(string)
request.DestCidr = d.Get("dest_cidr").(string)
request.DestPortRange = d.Get("dest_port_range").(string)
if v, ok := d.GetOk("name"); ok && v.(string) != "" {
request.Description = v.(string)
}
if v, ok := d.GetOk("description"); ok && v.(string) != "" {
request.Description = v.(string)
}
if v, ok := d.GetOk("start_time"); ok && v.(string) != "" {
request.StartTime = v.(string)
}
if v, ok := d.GetOk("end_time"); ok && v.(string) != "" {
request.EndTime = v.(string)
}
var response *smartag.CreateQosPolicyResponse
err := resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.CreateQosPolicy(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ResourceInOperating"}) {
time.Sleep(2 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*smartag.CreateQosPolicyResponse)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_sag_qos_policy", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprintf("%s%s%s", response.QosId, COLON_SEPARATED, response.QosPolicyId))
return resourceAlicloudSagQosPolicyRead(d, meta)
}
func resourceAlicloudSagQosPolicyRead(d *schema.ResourceData, meta interface{}) error {
sagService := SagService{meta.(*connectivity.AliyunClient)}
object, err := sagService.DescribeSagQosPolicy(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("qos_id", object.QosId)
d.Set("name", object.Name)
d.Set("description", object.Description)
d.Set("priority", object.Priority)
d.Set("ip_protocol", object.IpProtocol)
d.Set("source_cidr", object.SourceCidr)
d.Set("source_port_range", object.SourcePortRange)
d.Set("dest_cidr", object.DestCidr)
d.Set("dest_port_range", object.DestPortRange)
d.Set("start_time", object.StartTime)
d.Set("end_time", object.EndTime)
return nil
}
func resourceAlicloudSagQosPolicyUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
update := false
request := smartag.CreateModifyQosPolicyRequest()
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request.QosId = parts[0]
request.QosPolicyId = parts[1]
if d.HasChange("name") {
request.Name = d.Get("name").(string)
update = true
}
if d.HasChange("description") {
request.Description = d.Get("description").(string)
update = true
}
if d.HasChange("priority") {
request.Priority = requests.NewInteger(d.Get("priority").(int))
update = true
}
if d.HasChange("ip_protocol") {
request.IpProtocol = d.Get("ip_protocol").(string)
update = true
}
if d.HasChange("source_cidr") {
request.SourceCidr = d.Get("source_cidr").(string)
update = true
}
if d.HasChange("source_port_range") {
request.SourcePortRange = d.Get("source_port_range").(string)
update = true
}
if d.HasChange("dest_cidr") {
request.DestCidr = d.Get("dest_cidr").(string)
update = true
}
if d.HasChange("dest_port_range") {
request.DestPortRange = d.Get("dest_port_range").(string)
update = true
}
if d.HasChange("start_time") {
request.StartTime = d.Get("start_time").(string)
update = true
}
if d.HasChange("end_time") {
request.EndTime = d.Get("end_time").(string)
update = true
}
if update {
raw, err := client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.ModifyQosPolicy(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
return resourceAlicloudSagQosPolicyRead(d, meta)
}
func resourceAlicloudSagQosPolicyDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sagService := SagService{client}
request := smartag.CreateDeleteQosPolicyRequest()
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request.QosId = parts[0]
request.QosPolicyId = parts[1]
if err := resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.DeleteQosPolicy(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ResourceInOperating"}) {
time.Sleep(2 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}); err != nil {
if IsExpectedErrors(err, []string{"ParameterSagQosPolicyId"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(sagService.WaitForSagQosPolicy(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/smartag"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudSagSnatEntry() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSagSnatCreate,
Read: resourceAlicloudSagSnatRead,
Delete: resourceAlicloudSagSnatDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"sag_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"cidr_block": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateCIDRNetworkAddress,
},
"snat_ip": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.SingleIP(),
},
},
}
}
func resourceAlicloudSagSnatCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := smartag.CreateAddSnatEntryRequest()
request.SmartAGId = d.Get("sag_id").(string)
request.CidrBlock = d.Get("cidr_block").(string)
request.SnatIp = d.Get("snat_ip").(string)
raw, err := client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.AddSnatEntry(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_sag_snat_entry", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*smartag.AddSnatEntryResponse)
d.SetId(fmt.Sprintf("%s%s%s", request.SmartAGId, COLON_SEPARATED, response.InstanceId))
return resourceAlicloudSagSnatRead(d, meta)
}
func resourceAlicloudSagSnatRead(d *schema.ResourceData, meta interface{}) error {
sagService := SagService{meta.(*connectivity.AliyunClient)}
object, err := sagService.DescribeSagSnatEntry(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
parts, _ := ParseResourceId(d.Id(), 2)
d.Set("sag_id", parts[0])
d.Set("cidr_block", object.CidrBlock)
d.Set("snat_ip", object.SnatIp)
return nil
}
func resourceAlicloudSagSnatDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sagService := SagService{client}
request := smartag.CreateDeleteSnatEntryRequest()
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request.SmartAGId = parts[0]
request.InstanceId = parts[1]
raw, err := client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.DeleteSnatEntry(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ParameterSagSnatId"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return WrapError(sagService.WaitForSagSnatEntry(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudScdnDomain() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudScdnDomainCreate,
Read: resourceAlicloudScdnDomainRead,
Update: resourceAlicloudScdnDomainUpdate,
Delete: resourceAlicloudScdnDomainDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(11 * time.Minute),
Delete: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(11 * time.Minute),
},
Schema: map[string]*schema.Schema{
"biz_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"download", "image", "scdn", "video"}, false),
},
"cert_infos": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cert_name": {
Type: schema.TypeString,
Optional: true,
},
"cert_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"upload", "cas", "free"}, false),
},
"ssl_pri": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"ssl_protocol": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"on", "off"}, false),
},
"ssl_pub": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"check_url": {
Type: schema.TypeString,
Optional: true,
},
"domain_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"force_set": {
Type: schema.TypeString,
Optional: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"sources": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"content": {
Type: schema.TypeString,
Required: true,
},
"enabled": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"port": {
Type: schema.TypeInt,
Required: true,
},
"priority": {
Type: schema.TypeString,
Required: true,
},
"type": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"offline", "online"}, false),
},
},
}
}
func resourceAlicloudScdnDomainCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AddScdnDomain"
request := make(map[string]interface{})
conn, err := client.NewScdnClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("check_url"); ok {
request["CheckUrl"] = v
}
request["DomainName"] = d.Get("domain_name")
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
sourcesMaps := make([]map[string]interface{}, 0)
for _, sources := range d.Get("sources").(*schema.Set).List() {
sourcesArg := sources.(map[string]interface{})
sourcesMap := map[string]interface{}{}
sourcesMap["Content"] = sourcesArg["content"]
sourcesMap["Enabled"] = sourcesArg["enabled"]
sourcesMap["Port"] = sourcesArg["port"]
sourcesMap["Priority"] = sourcesArg["priority"]
sourcesMap["Type"] = sourcesArg["type"]
sourcesMaps = append(sourcesMaps, sourcesMap)
}
if v, err := convertArrayObjectToJsonString(sourcesMaps); err == nil {
request["Sources"] = v
} else {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-11-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_scdn_domain", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["DomainName"]))
scdnService := ScdnService{client}
stateConf := BuildStateConf([]string{}, []string{"online"}, d.Timeout(schema.TimeoutCreate), 60*time.Second, scdnService.ScdnDomainStateRefreshFunc(d.Id(), []string{"configure_failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudScdnDomainUpdate(d, meta)
}
func resourceAlicloudScdnDomainRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
scdnService := ScdnService{client}
object, err := scdnService.DescribeScdnDomain(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_scdn_domain scdnService.DescribeScdnDomain Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("domain_name", d.Id())
d.Set("resource_group_id", object["ResourceGroupId"])
if v, ok := object["Sources"].(map[string]interface{})["Source"].([]interface{}); ok {
source := make([]map[string]interface{}, 0)
for _, val := range v {
item := val.(map[string]interface{})
temp := map[string]interface{}{
"content": item["Content"],
"enabled": item["Enabled"],
"port": item["Port"],
"priority": item["Priority"],
"type": item["Type"],
}
source = append(source, temp)
}
if err := d.Set("sources", source); err != nil {
return WrapError(err)
}
}
d.Set("status", object["DomainStatus"])
describeScdnDomainCertificateInfoObject, err := scdnService.DescribeScdnDomainCertificateInfo(d.Id())
if err != nil {
return WrapError(err)
}
if certInfosMap, ok := describeScdnDomainCertificateInfoObject["CertInfos"].(map[string]interface{}); ok && certInfosMap != nil {
if certInfoList, ok := certInfosMap["CertInfo"]; ok && certInfoList != nil {
certInfosMaps := make([]map[string]interface{}, 0)
for _, certInfoListItem := range certInfoList.([]interface{}) {
if certInfoListItemMap, ok := certInfoListItem.(map[string]interface{}); ok {
certInfoListItemMap["cert_name"] = certInfoListItemMap["CertName"]
certInfoListItemMap["cert_type"] = certInfoListItemMap["CertType"]
certInfoListItemMap["ssl_pri"] = certInfoListItemMap["SslPri"]
certInfoListItemMap["ssl_protocol"] = certInfoListItemMap["SslProtocol"]
certInfoListItemMap["ssl_pub"] = certInfoListItemMap["SslPub"]
certInfosMaps = append(certInfosMaps, certInfoListItemMap)
}
}
d.Set("cert_infos", certInfosMaps)
}
}
return nil
}
func resourceAlicloudScdnDomainUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
scdnService := ScdnService{client}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"DomainName": d.Id(),
}
if d.HasChange("biz_name") {
update = true
}
if v, ok := d.GetOk("biz_name"); ok {
request["BizName"] = v
}
if update {
action := "SetScdnDomainBizInfo"
conn, err := client.NewScdnClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2017-11-15"), StringPointer("AK"), request, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("biz_name")
}
update = false
setScdnDomainCertificateReq := map[string]interface{}{
"DomainName": d.Id(),
}
if d.HasChange("ssl_protocol") {
update = true
}
if v, ok := d.GetOk("ssl_protocol"); ok {
setScdnDomainCertificateReq["SSLProtocol"] = v
}
if d.HasChange("cert_name") {
update = true
if v, ok := d.GetOk("cert_name"); ok {
setScdnDomainCertificateReq["CertName"] = v
}
}
if d.HasChange("cert_type") {
update = true
if v, ok := d.GetOk("cert_type"); ok {
setScdnDomainCertificateReq["CertType"] = v
}
}
if d.HasChange("ssl_pri") {
update = true
if v, ok := d.GetOk("ssl_pri"); ok {
setScdnDomainCertificateReq["SSLPri"] = v
}
}
if d.HasChange("ssl_pub") {
update = true
if v, ok := d.GetOk("ssl_pub"); ok {
setScdnDomainCertificateReq["SSLPub"] = v
}
}
if update {
if v, ok := d.GetOk("force_set"); ok {
setScdnDomainCertificateReq["ForceSet"] = v
}
action := "SetScdnDomainCertificate"
conn, err := client.NewScdnClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-11-15"), StringPointer("AK"), nil, setScdnDomainCertificateReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, setScdnDomainCertificateReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"online"}, d.Timeout(schema.TimeoutUpdate), 1*time.Second, scdnService.ScdnDomainStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("ssl_protocol")
d.SetPartial("cert_name")
d.SetPartial("cert_type")
d.SetPartial("ssl_pri")
d.SetPartial("ssl_pub")
}
update = false
updateScdnDomainReq := map[string]interface{}{
"DomainName": d.Id(),
}
if !d.IsNewResource() && d.HasChange("resource_group_id") {
update = true
if v, ok := d.GetOk("resource_group_id"); ok {
updateScdnDomainReq["ResourceGroupId"] = v
}
}
if d.HasChange("sources") {
update = true
sourcesMaps := make([]map[string]interface{}, 0)
for _, sources := range d.Get("sources").(*schema.Set).List() {
sourcesArg := sources.(map[string]interface{})
sourcesMap := map[string]interface{}{}
sourcesMap["Content"] = sourcesArg["content"]
sourcesMap["Enabled"] = sourcesArg["enabled"]
sourcesMap["Port"] = sourcesArg["port"]
sourcesMap["Priority"] = sourcesArg["priority"]
sourcesMap["Type"] = sourcesArg["type"]
sourcesMaps = append(sourcesMaps, sourcesMap)
}
if v, err := convertArrayObjectToJsonString(sourcesMaps); err == nil {
updateScdnDomainReq["Sources"] = v
} else {
return WrapError(err)
}
}
if update {
action := "UpdateScdnDomain"
conn, err := client.NewScdnClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-11-15"), StringPointer("AK"), nil, updateScdnDomainReq, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ServiceBusy"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, updateScdnDomainReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"online"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, scdnService.ScdnDomainStateRefreshFunc(d.Id(), []string{"configure_failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("resource_group_id")
d.SetPartial("sources")
}
if d.HasChange("status") {
object, err := scdnService.DescribeScdnDomain(d.Id())
if err != nil {
return WrapError(err)
}
target := d.Get("status").(string)
if object["DomainStatus"].(string) != target {
if target == "offline" {
request := map[string]interface{}{
"DomainName": d.Id(),
}
action := "StopScdnDomain"
conn, err := client.NewScdnClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-11-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"offline"}, d.Timeout(schema.TimeoutUpdate), 10*time.Second, scdnService.ScdnDomainStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if target == "online" {
request := map[string]interface{}{
"DomainName": d.Id(),
}
action := "StartScdnDomain"
conn, err := client.NewScdnClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-11-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"online"}, d.Timeout(schema.TimeoutUpdate), 10*time.Second, scdnService.ScdnDomainStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.SetPartial("status")
}
}
d.Partial(false)
return resourceAlicloudScdnDomainRead(d, meta)
}
func resourceAlicloudScdnDomainDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
scdnService := ScdnService{client}
action := "DeleteScdnDomain"
var response map[string]interface{}
conn, err := client.NewScdnClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DomainName": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-11-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDomain.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 2*time.Second, scdnService.ScdnDomainStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"encoding/json"
"fmt"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudScdnDomainConfig() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudScdnDomainConfigCreate,
Read: resourceAlicloudScdnDomainConfigRead,
Update: resourceAlicloudScdnDomainConfigUpdate,
Delete: resourceAlicloudScdnDomainConfigDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"config_id": {
Type: schema.TypeString,
Computed: true,
},
"domain_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(5, 67),
},
"function_args": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"arg_name": {
Type: schema.TypeString,
Required: true,
},
"arg_value": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"function_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudScdnDomainConfigCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
scdnService := ScdnService{client}
var response map[string]interface{}
action := "BatchSetScdnDomainConfigs"
request := make(map[string]interface{})
conn, err := client.NewScdnClient()
if err != nil {
return WrapError(err)
}
config := make([]map[string]interface{}, 1)
functionArgs := d.Get("function_args").(*schema.Set).List()
args := make([]map[string]interface{}, len(functionArgs))
for key, value := range functionArgs {
arg := value.(map[string]interface{})
args[key] = map[string]interface{}{
"argName": arg["arg_name"],
"argValue": arg["arg_value"],
}
}
config[0] = map[string]interface{}{
"functionArgs": args,
"functionName": d.Get("function_name").(string),
}
bytconfig, _ := json.Marshal(config)
request["DomainNames"] = d.Get("domain_name").(string)
request["Functions"] = string(bytconfig)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-11-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_scdn_domain", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprintf("%s:%s:%s", request["DomainNames"], d.Get("function_name"), ""))
object, err := scdnService.DescribeScdnDomainConfig(d.Id())
if err != nil {
return WrapError(err)
}
d.SetId(fmt.Sprintf("%s:%s:%s", request["DomainNames"], object["FunctionName"], object["ConfigId"]))
stateConf := BuildStateConf([]string{}, []string{"success"}, d.Timeout(schema.TimeoutCreate), 2*time.Second, scdnService.ScdnDomainConfigStateRefreshFunc(d.Id(), []string{"failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudScdnDomainConfigRead(d, meta)
}
func resourceAlicloudScdnDomainConfigRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
scdnService := &ScdnService{client: client}
object, err := scdnService.DescribeScdnDomainConfig(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
functionArgMaps := make([]map[string]interface{}, 0)
for _, functionArg := range object["FunctionArgs"].(map[string]interface{})["FunctionArg"].([]interface{}) {
functionArgItem := functionArg.(map[string]interface{})
functionArgMap := make(map[string]interface{}, 0)
functionArgMap["arg_name"] = functionArgItem["ArgName"]
functionArgMap["arg_value"] = functionArgItem["ArgValue"]
functionArgMaps = append(functionArgMaps, functionArgMap)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
d.Set("config_id", parts[2])
d.Set("domain_name", parts[0])
d.Set("function_args", functionArgMaps)
d.Set("function_name", parts[1])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudScdnDomainConfigUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
scdnService := ScdnService{client}
var response map[string]interface{}
if d.HasChange("function_args") {
action := "BatchSetScdnDomainConfigs"
request := make(map[string]interface{})
conn, err := client.NewScdnClient()
if err != nil {
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
config := make([]map[string]interface{}, 1)
functionArgs := d.Get("function_args").(*schema.Set).List()
args := make([]map[string]interface{}, len(functionArgs))
for key, value := range functionArgs {
arg := value.(map[string]interface{})
args[key] = map[string]interface{}{
"argName": arg["arg_name"],
"argValue": arg["arg_value"],
}
}
config[0] = map[string]interface{}{
"functionArgs": args,
"functionName": parts[1],
"configId": parts[2],
}
bytconfig, _ := json.Marshal(config)
request["DomainNames"] = parts[0]
request["Functions"] = string(bytconfig)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-11-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"success"}, d.Timeout(schema.TimeoutCreate), 2*time.Second, scdnService.ScdnDomainConfigStateRefreshFunc(d.Id(), []string{"failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudScdnDomainConfigRead(d, meta)
}
func resourceAlicloudScdnDomainConfigDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
scdnService := ScdnService{client}
var response map[string]interface{}
action := "DeleteScdnSpecificConfig"
conn, err := client.NewScdnClient()
if err != nil {
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
request := make(map[string]interface{})
request["ConfigId"] = parts[2]
request["DomainName"] = parts[0]
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-11-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 1*time.Second, scdnService.ScdnDomainConfigStateRefreshFunc(d.Id(), []string{"failed"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudSddpConfig() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSddpConfigCreate,
Read: resourceAlicloudSddpConfigRead,
Update: resourceAlicloudSddpConfigUpdate,
Delete: resourceAlicloudSddpConfigDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"code": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"access_failed_cnt", "access_permission_exprie_max_days", "log_datasize_avg_days"}, false),
},
"description": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"value": {
Type: schema.TypeString,
Optional: true,
},
"lang": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"zh", "en"}, false),
Default: "zh",
Optional: true,
},
},
}
}
func resourceAlicloudSddpConfigCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateConfig"
request := make(map[string]interface{})
conn, err := client.NewSddpClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("code"); ok {
request["Code"] = v
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
if v, ok := d.GetOk("value"); ok {
request["Value"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-03"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_sddp_config", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["Code"]))
return resourceAlicloudSddpConfigRead(d, meta)
}
func resourceAlicloudSddpConfigRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sddpService := SddpService{client}
object, err := sddpService.DescribeSddpConfig(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_sddp_config sddpService.DescribeSddpConfig Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("code", d.Id())
d.Set("description", object["Description"])
d.Set("value", fmt.Sprint(formatInt(object["Value"])))
return nil
}
func resourceAlicloudSddpConfigUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewSddpClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
update := false
request := map[string]interface{}{
"Code": d.Id(),
}
if d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
}
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
if d.HasChange("value") {
update = true
if v, ok := d.GetOk("value"); ok {
request["Value"] = v
}
}
if update {
action := "CreateConfig"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-03"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudSddpConfigRead(d, meta)
}
func resourceAlicloudSddpConfigDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudSddpConfig. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudSddpInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSddpInstanceCreate,
Read: resourceAlicloudSddpInstanceRead,
Update: resourceAlicloudSddpInstanceUpdate,
Delete: resourceAlicloudSddpInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"payment_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Subscription"}, false),
},
"period": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntInSlice([]int{1, 12, 2, 24, 3, 6}),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("payment_type"); ok && v.(string) == "Subscription" {
return false
}
return true
},
},
"renew_period": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(1, 12),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("payment_type"); ok && v.(string) == "Subscription" {
if v, ok := d.GetOk("renewal_status"); ok && v.(string) == "AutoRenewal" {
return false
}
}
return true
},
},
"renewal_status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"AutoRenewal", "ManualRenewal"}, false),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("payment_type"); ok && v.(string) == "Subscription" {
return false
}
return true
},
},
"logistics": {
Type: schema.TypeString,
Optional: true,
},
"dataphin_count": {
Type: schema.TypeString,
Optional: true,
},
"dataphin": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"no", "yes"}, false),
},
"sddp_version": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"version_audit", "version_company", "version_dlp"}, false),
},
"sdc": {
Type: schema.TypeString,
Required: true,
},
"ud_cbool": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"no", "yes"}, false),
},
"sd_cbool": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"no", "yes"}, false),
},
"udc": {
Type: schema.TypeString,
Required: true,
},
"modify_type": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"Upgrade", "Downgrade"}, false),
Optional: true,
},
"authed": {
Type: schema.TypeBool,
Computed: true,
},
"instance_num": {
Type: schema.TypeString,
Computed: true,
},
"odps_set": {
Type: schema.TypeBool,
Computed: true,
},
"oss_bucket_set": {
Type: schema.TypeBool,
Computed: true,
},
"oss_size": {
Type: schema.TypeString,
Computed: true,
},
"rds_set": {
Type: schema.TypeBool,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"remain_days": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudSddpInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateInstance"
request := make(map[string]interface{})
conn, err := client.NewBssopenapiClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("CreateInstance")
request["ProductCode"] = "sddp"
request["ProductType"] = "sddp_pre"
request["SubscriptionType"] = d.Get("payment_type")
if v, ok := d.GetOk("renewal_status"); ok {
request["RenewalStatus"] = v
}
if v, ok := d.GetOk("renewal_duration"); ok {
request["RenewPeriod"] = v
} else if v, ok := d.GetOk("renewal_status"); ok && v.(string) == "AutoRenewal" {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is %v ", "renewal_duration", "renewal_status", d.Get("renewal_status")))
}
if v, ok := d.GetOk("period"); ok {
request["Period"] = v
} else if d.Get("payment_type").(string) == "Subscription" {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is %v", "period", "payment_type", "Subscription"))
}
if v, ok := d.GetOk("logistics"); ok {
request["Logistics"] = v
}
parameterMapList := make([]map[string]interface{}, 0)
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "sddp_version",
"Value": d.Get("sddp_version"),
})
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "SDCbool",
"Value": d.Get("sd_cbool"),
})
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "SDC",
"Value": d.Get("sdc"),
})
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "UDCbool",
"Value": d.Get("ud_cbool"),
})
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "UDC",
"Value": d.Get("udc"),
})
if v, ok := d.GetOk("dataphin"); ok {
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "dataphin",
"Value": v,
})
} else if d.Get("sddp_version").(string) == "version_audit" || d.Get("sddp_version").(string) == "version_company" {
return WrapError(fmt.Errorf("attribute '%s' is required when '%s' is %v or %v", "dataphin", "sddp_version", "version_audit", "version_company"))
}
if v, ok := d.GetOk("dataphin_count"); ok {
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "dataphin_count",
"Value": v,
})
}
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "region",
"Value": client.RegionId,
})
request["Parameter"] = parameterMapList
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-14"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"NotApplicable"}) {
conn.Endpoint = String(connectivity.BssOpenAPIEndpointInternational)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_sddp_instance", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
responseData := response["Data"].(map[string]interface{})
d.SetId(fmt.Sprint(responseData["InstanceId"]))
return resourceAlicloudSddpInstanceRead(d, meta)
}
func resourceAlicloudSddpInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sddpService := SddpService{client}
object, err := sddpService.DescribeSddpInstance(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_sddp_instance sddpService.DescribeSddpInstance Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("payment_type", convertSddpInstancePaymentTypeToStandard(object["ChargeType"]))
d.Set("sddp_version", object["Version"])
d.Set("sdc", fmt.Sprint(formatInt(object["InstanceNum"])))
d.Set("authed", object["Authed"])
d.Set("renewal_status", object["RenewStatus"])
d.Set("instance_num", fmt.Sprint(formatInt(object["InstanceNum"])))
d.Set("odps_set", object["OdpsSet"])
d.Set("oss_bucket_set", object["OssBucketSet"])
d.Set("oss_size", fmt.Sprint(formatInt(object["OssSize"])))
d.Set("rds_set", object["RdsSet"])
d.Set("status", fmt.Sprint(formatInt(object["InstanceStatus"])))
d.Set("remain_days", object["RemainDays"])
return nil
}
func resourceAlicloudSddpInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"InstanceId": d.Id(),
}
request["SubscriptionType"] = d.Get("payment_type")
request["ClientToken"] = buildClientToken("ModifyInstance")
request["ProductCode"] = "sddp"
request["ProductType"] = "sddp_pre"
parameterMapList := make([]map[string]interface{}, 0)
if d.HasChange("sdc") {
update = true
}
if v, ok := d.GetOk("sdc"); ok {
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "SDC",
"Value": v,
})
}
if d.HasChange("oss_size") {
update = true
}
if v, ok := d.GetOk("oss_size"); ok {
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "UDC",
"Value": v,
})
}
if d.HasChange("sd_cbool") {
update = true
}
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "SDCbool",
"Value": d.Get("sd_cbool"),
})
if d.HasChange("ud_cbool") {
update = true
}
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "UDCbool",
"Value": d.Get("ud_cbool"),
})
if d.HasChange("sddp_version") {
update = true
}
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "sddp_version",
"Value": d.Get("sddp_version"),
})
if d.HasChange("sdc") {
update = true
}
if v, ok := d.GetOk("sdc"); ok {
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "SDC",
"Value": v,
})
}
if d.HasChange("udc") {
update = true
}
if v, ok := d.GetOk("udc"); ok {
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "UDC",
"Value": v,
})
}
if d.HasChange("dataphin") {
update = true
}
if v, ok := d.GetOk("dataphin"); ok {
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "dataphin",
"Value": v,
})
}
if d.HasChange("dataphin_count") {
update = true
}
if v, ok := d.GetOk("dataphin_count"); ok {
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "dataphin_count",
"Value": v,
})
}
request["Parameter"] = parameterMapList
if update {
if v, ok := d.GetOk("modify_type"); ok {
request["ModifyType"] = v
}
action := "ModifyInstance"
conn, err := client.NewBssopenapiClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-14"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"NotApplicable"}) {
conn.Endpoint = String(connectivity.BssOpenAPIEndpointInternational)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
}
return resourceAlicloudSddpInstanceRead(d, meta)
}
func resourceAlicloudSddpInstanceDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudSddpInstance. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
func convertSddpInstancePaymentTypeToStandard(source interface{}) interface{} {
switch source {
case "PREPAY":
return "Subscription"
}
return source
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudSddpRule() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSddpRuleCreate,
Read: resourceAlicloudSddpRuleRead,
Update: resourceAlicloudSddpRuleUpdate,
Delete: resourceAlicloudSddpRuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"category": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntInSlice([]int{0, 2}),
ForceNew: true,
},
"content": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"rule_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"content_category": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"custom_type": {
Type: schema.TypeInt,
Computed: true,
Optional: true,
ForceNew: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"lang": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"zh", "en"}, false),
Default: "zh",
Optional: true,
},
"product_code": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"ODPS", "OSS", "RDS"}, false),
Optional: true,
},
"product_id": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"1", "2", "5"}, false),
},
"risk_level_id": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"2", "3", "4", "5"}, false),
},
"rule_type": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3}),
},
"stat_express": {
Type: schema.TypeString,
Optional: true,
},
"status": {
Type: schema.TypeInt,
Computed: true,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{0, 1}),
},
"target": {
Type: schema.TypeString,
Optional: true,
},
"warn_level": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{1, 2, 3}),
},
},
}
}
func resourceAlicloudSddpRuleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateRule"
request := make(map[string]interface{})
conn, err := client.NewSddpClient()
if err != nil {
return WrapError(err)
}
request["Category"] = d.Get("category").(int)
request["Content"] = d.Get("content")
if v, ok := d.GetOk("content_category"); ok {
request["ContentCategory"] = v
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
if v, ok := d.GetOk("product_code"); ok {
request["ProductCode"] = v
}
if v, ok := d.GetOk("product_id"); ok {
request["ProductId"] = v
}
if v, ok := d.GetOk("risk_level_id"); ok {
request["RiskLevelId"] = v
}
request["Name"] = d.Get("rule_name")
if v, ok := d.GetOk("rule_type"); ok {
request["RuleType"] = v
}
if v, ok := d.GetOk("stat_express"); ok {
request["StatExpress"] = v
}
if v, ok := d.GetOk("status"); ok {
request["Status"] = v
}
if v, ok := d.GetOk("target"); ok {
request["Target"] = v
}
if v, ok := d.GetOk("warn_level"); ok {
request["WarnLevel"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-03"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_sddp_rule", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["Id"]))
return resourceAlicloudSddpRuleUpdate(d, meta)
}
func resourceAlicloudSddpRuleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sddpService := SddpService{client}
object, err := sddpService.DescribeSddpRule(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_sddp_rule sddpService.DescribeSddpRule Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
if v, ok := object["Category"]; ok {
err = d.Set("category", formatInt(v))
if err != nil {
return WrapError(err)
}
}
err = d.Set("content", object["Content"])
if err != nil {
return WrapError(err)
}
err = d.Set("content_category", object["ContentCategory"])
if err != nil {
return WrapError(err)
}
if v, ok := object["CustomType"]; ok {
err = d.Set("custom_type", formatInt(v))
if err != nil {
return WrapError(err)
}
}
err = d.Set("description", object["Description"])
if err != nil {
return WrapError(err)
}
err = d.Set("product_code", object["ProductCode"])
if err != nil {
return WrapError(err)
}
if v, ok := object["ProductId"]; ok {
v = formatInt(v)
err = d.Set("product_id", fmt.Sprint(v))
if err != nil {
return WrapError(err)
}
}
if v, ok := object["RiskLevelId"]; ok {
v = formatInt(v)
err = d.Set("risk_level_id", fmt.Sprint(v))
if err != nil {
return WrapError(err)
}
}
if v, ok := object["Name"]; ok {
err = d.Set("rule_name", v.(string))
if err != nil {
return WrapError(err)
}
}
err = d.Set("stat_express", object["StatExpress"])
if err != nil {
return WrapError(err)
}
if v, ok := object["Status"]; ok {
d.Set("status", formatInt(v))
}
err = d.Set("target", object["Target"])
if err != nil {
return WrapError(err)
}
if v, ok := object["WarnLevel"]; ok {
err = d.Set("warn_level", formatInt(v))
if err != nil {
return WrapError(err)
}
}
return nil
}
func resourceAlicloudSddpRuleUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"Id": d.Id(),
}
if !d.IsNewResource() && d.HasChange("lang") {
update = true
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
}
if !d.IsNewResource() && d.HasChange("status") {
update = true
_, new := d.GetChange("status")
if new != nil {
request["Status"] = new.(int)
}
}
if update {
action := "ModifyRuleStatus"
conn, err := client.NewSddpClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-03"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("status")
d.SetPartial("lang")
}
update = false
modifyRuleReq := map[string]interface{}{
"Id": d.Id(),
}
modifyRuleReq["Category"] = d.Get("category")
modifyRuleReq["Content"] = d.Get("content")
modifyRuleReq["CustomType"] = 1
modifyRuleReq["Name"] = d.Get("rule_name")
if !d.IsNewResource() && d.HasChange("content_category") {
update = true
}
if v, ok := d.GetOk("content_category"); ok {
modifyRuleReq["ContentCategory"] = v
}
if !d.IsNewResource() && d.HasChange("description") {
update = true
}
if v, ok := d.GetOk("description"); ok {
modifyRuleReq["Description"] = v
}
if v, ok := d.GetOk("lang"); ok {
modifyRuleReq["Lang"] = v
}
if !d.IsNewResource() && d.HasChange("product_code") {
update = true
}
if v, ok := d.GetOk("product_code"); ok {
modifyRuleReq["ProductCode"] = v
}
if !d.IsNewResource() && d.HasChange("product_id") {
update = true
}
if v, ok := d.GetOk("product_id"); ok {
modifyRuleReq["ProductId"] = v
}
if !d.IsNewResource() && d.HasChange("risk_level_id") {
update = true
}
if v, ok := d.GetOk("risk_level_id"); ok {
modifyRuleReq["RiskLevelId"] = v
}
if !d.IsNewResource() && d.HasChange("rule_type") {
update = true
}
if v, ok := d.GetOk("rule_type"); ok {
modifyRuleReq["RuleType"] = v
}
if !d.IsNewResource() && d.HasChange("stat_express") {
update = true
}
if v, ok := d.GetOk("stat_express"); ok {
modifyRuleReq["StatExpress"] = v
}
if !d.IsNewResource() && d.HasChange("target") {
update = true
}
if v, ok := d.GetOk("target"); ok {
modifyRuleReq["Target"] = v
}
if !d.IsNewResource() && d.HasChange("warn_level") {
update = true
}
if v, ok := d.GetOk("warn_level"); ok {
modifyRuleReq["WarnLevel"] = v
}
if update {
action := "ModifyRule"
conn, err := client.NewSddpClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-03"), StringPointer("AK"), nil, modifyRuleReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyRuleReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("category")
d.SetPartial("content")
d.SetPartial("custom_type")
d.SetPartial("rule_name")
d.SetPartial("content_category")
d.SetPartial("description")
d.SetPartial("lang")
d.SetPartial("product_code")
d.SetPartial("product_id")
d.SetPartial("risk_level_id")
d.SetPartial("rule_type")
d.SetPartial("stat_express")
d.SetPartial("target")
d.SetPartial("warn_level")
}
d.Partial(false)
return resourceAlicloudSddpRuleRead(d, meta)
}
func resourceAlicloudSddpRuleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteRule"
var response map[string]interface{}
conn, err := client.NewSddpClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"Id": d.Id(),
}
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-03"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudSecurityCenterGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSecurityCenterGroupCreate,
Read: resourceAlicloudSecurityCenterGroupRead,
Update: resourceAlicloudSecurityCenterGroupUpdate,
Delete: resourceAlicloudSecurityCenterGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"group_name": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudSecurityCenterGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateOrUpdateAssetGroup"
request := make(map[string]interface{})
conn, err := client.NewSasClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("group_id"); ok {
request["GroupId"] = v
}
if v, ok := d.GetOk("group_name"); ok {
request["GroupName"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-03"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_security_center_group", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["GroupId"]))
return resourceAlicloudSecurityCenterGroupRead(d, meta)
}
func resourceAlicloudSecurityCenterGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sasService := SasService{client}
describeAllGroupsObject, err := sasService.DescribeAllGroups(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("group_name", describeAllGroupsObject["GroupName"])
d.Set("group_id", describeAllGroupsObject["GroupId"])
return nil
}
func resourceAlicloudSecurityCenterGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
request := map[string]interface{}{
"GroupId": d.Id(),
}
if v, ok := d.GetOk("group_name"); ok {
request["GroupName"] = v
}
action := "CreateOrUpdateAssetGroup"
conn, err := client.NewSasClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-03"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return resourceAlicloudSecurityCenterGroupRead(d, meta)
}
func resourceAlicloudSecurityCenterGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteGroup"
var response map[string]interface{}
conn, err := client.NewSasClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"GroupId": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-03"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudSecurityCenterServiceLinkedRole() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSecurityCenterServiceLinkedRoleCreate,
Read: resourceAlicloudSecurityCenterServiceLinkedRoleRead,
Delete: resourceAlicloudSecurityCenterServiceLinkedRoleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"status": {
Type: schema.TypeBool,
Computed: true,
},
},
}
}
func resourceAlicloudSecurityCenterServiceLinkedRoleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateServiceLinkedRole"
request := make(map[string]interface{})
conn, err := client.NewSasClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-03"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_security_center_service_linked_role", action, AlibabaCloudSdkGoERROR)
}
d.SetId("AliyunServiceRolePolicyForSas")
sasService := SasService{client}
stateConf := BuildStateConf([]string{}, []string{"true"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, sasService.SecurityCenterServiceLinkedRoleStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudSecurityCenterServiceLinkedRoleRead(d, meta)
}
func resourceAlicloudSecurityCenterServiceLinkedRoleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
sasService := SasService{client}
object, err := sasService.DescribeSecurityCenterServiceLinkedRole(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_security_center_service_linked_role sasService.DescribeSecurityCenterServiceLinkedRole Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("product_name", d.Id())
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudSecurityCenterServiceLinkedRoleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteServiceLinkedRole"
var response map[string]interface{}
conn, err := client.NewResourcemanagerClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"RoleName": d.Id(),
}
wait := incrementalWait(3*time.Second, 0*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), request, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist.Role"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliyunSecurityGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunSecurityGroupCreate,
Read: resourceAliyunSecurityGroupRead,
Update: resourceAliyunSecurityGroupUpdate,
Delete: resourceAliyunSecurityGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 128),
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
},
"security_group_type": {
Type: schema.TypeString,
Optional: true,
Default: "normal",
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"normal", "enterprise"}, false),
},
"inner_access": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
Deprecated: "Field 'inner_access' has been deprecated from provider version 1.55.3. Use 'inner_access_policy' replaces it.",
},
"inner_access_policy": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"inner_access"},
ValidateFunc: validation.StringInSlice([]string{"Accept", "Drop"}, false),
// The InnerAccessPolicy attribute of enterprise level security group can't be modified.
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("security_group_type").(string) == "enterprise"
},
},
"tags": tagsSchema(),
},
}
}
func resourceAliyunSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := ecs.CreateCreateSecurityGroupRequest()
request.RegionId = client.RegionId
if v := d.Get("name").(string); v != "" {
request.SecurityGroupName = v
}
if v := d.Get("description").(string); v != "" {
request.Description = v
}
request.SecurityGroupType = d.Get("security_group_type").(string)
if v := d.Get("vpc_id").(string); v != "" {
request.VpcId = v
}
request.ResourceGroupId = d.Get("resource_group_id").(string)
request.ClientToken = buildClientToken(request.GetActionName())
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.CreateSecurityGroup(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_security_group", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ecs.CreateSecurityGroupResponse)
d.SetId(response.SecurityGroupId)
return resourceAliyunSecurityGroupUpdate(d, meta)
}
func resourceAliyunSecurityGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
object, err := ecsService.DescribeSecurityGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_security_group ecsService.DescribeSecurityGroup Failed!!! %s", err)
d.SetId("")
return nil
}
}
d.Set("name", object.SecurityGroupName)
d.Set("description", object.Description)
d.Set("vpc_id", object.VpcId)
d.Set("inner_access", object.InnerAccessPolicy == string(GroupInnerAccept))
d.Set("inner_access_policy", object.InnerAccessPolicy)
request := ecs.CreateDescribeSecurityGroupsRequest()
request.RegionId = client.RegionId
request.SecurityGroupId = d.Id()
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeSecurityGroups(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ecs.DescribeSecurityGroupsResponse)
if len(response.SecurityGroups.SecurityGroup) < 1 {
return WrapErrorf(Error(GetNotFoundMessage("SecurityGroup", d.Id())), NotFoundMsg, ProviderERROR)
}
d.Set("security_group_type", response.SecurityGroups.SecurityGroup[0].SecurityGroupType)
d.Set("resource_group_id", response.SecurityGroups.SecurityGroup[0].ResourceGroupId)
tags, err := ecsService.ListTagResources(d.Id(), "securitygroup")
if err != nil {
return WrapError(err)
} else {
d.Set("tags", tagsToMap(tags))
}
return nil
}
func resourceAliyunSecurityGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
d.Partial(true)
if !d.IsNewResource() && d.HasChange("resource_group_id") {
action := "JoinResourceGroup"
request := map[string]interface{}{
"ResourceType": "securitygroup",
"ResourceId": d.Id(),
"RegionId": client.RegionId,
"ResourceGroupId": d.Get("resource_group_id"),
}
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetPartial("resource_group_id")
}
if err := setTags(client, TagResourceSecurityGroup, d); err != nil {
return WrapError(err)
} else {
d.SetPartial("tags")
}
if d.HasChange("inner_access_policy") || d.HasChange("inner_access") || d.IsNewResource() && d.Get("security_group_type").(string) != "enterprise" {
policy := GroupInnerAccept
if v, ok := d.GetOk("inner_access_policy"); ok && v.(string) != "" {
policy = GroupInnerAccessPolicy(v.(string))
} else if v, ok := d.GetOkExists("inner_access"); ok && !v.(bool) {
policy = GroupInnerDrop
}
request := ecs.CreateModifySecurityGroupPolicyRequest()
request.RegionId = client.RegionId
request.SecurityGroupId = d.Id()
request.InnerAccessPolicy = string(policy)
request.ClientToken = buildClientToken(request.GetActionName())
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ModifySecurityGroupPolicy(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("inner_access")
d.SetPartial("inner_access_policy")
}
if d.IsNewResource() {
d.Partial(false)
return resourceAliyunSecurityGroupRead(d, meta)
}
update := false
request := ecs.CreateModifySecurityGroupAttributeRequest()
request.RegionId = client.RegionId
request.SecurityGroupId = d.Id()
if d.HasChange("name") {
request.SecurityGroupName = d.Get("name").(string)
update = true
}
if d.HasChange("description") {
request.Description = d.Get("description").(string)
update = true
}
if update {
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ModifySecurityGroupAttribute(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("name")
d.SetPartial("description")
}
d.Partial(false)
return resourceAliyunSecurityGroupRead(d, meta)
}
func resourceAliyunSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
request := ecs.CreateDeleteSecurityGroupRequest()
request.RegionId = client.RegionId
request.SecurityGroupId = d.Id()
err := resource.Retry(6*time.Minute, func() *resource.RetryError {
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DeleteSecurityGroup(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"DependencyViolation"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultTimeoutMsg, d.Id(), request.GetActionName(), ProviderERROR)
}
return WrapError(ecsService.WaitForSecurityGroup(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"fmt"
"log"
"strconv"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliyunSecurityGroupRule() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunSecurityGroupRuleCreate,
Read: resourceAliyunSecurityGroupRuleRead,
Update: resourceAliyunSecurityGroupRuleUpdate,
Delete: resourceAliyunSecurityGroupRuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ingress", "egress"}, false),
Description: "Type of rule, ingress (inbound) or egress (outbound).",
},
"ip_protocol": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"tcp", "udp", "icmp", "gre", "all"}, false),
},
"nic_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"internet", "intranet"}, false),
},
"policy": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: GroupRulePolicyAccept,
ValidateFunc: validation.StringInSlice([]string{"accept", "drop"}, false),
},
"port_range": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: AllPortRange,
DiffSuppressFunc: ecsSecurityGroupRulePortRangeDiffSuppressFunc,
},
"priority": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Default: 1,
ValidateFunc: validation.IntBetween(1, 100),
},
"security_group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"cidr_ip": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"source_security_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ConflictsWith: []string{"cidr_ip"},
},
"source_group_owner_account": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"prefix_list_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
DiffSuppressFunc: ecsSecurityGroupRulePreFixListIdDiffSuppressFunc,
},
},
}
}
func resourceAliyunSecurityGroupRuleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
direction := d.Get("type").(string)
sgId := d.Get("security_group_id").(string)
ptl := d.Get("ip_protocol").(string)
port := d.Get("port_range").(string)
if port == "" {
return WrapError(fmt.Errorf("'port_range': required field is not set or invalid."))
}
nicType := d.Get("nic_type").(string)
policy := d.Get("policy").(string)
priority := d.Get("priority").(int)
_, cidrExist := d.GetOk("cidr_ip")
_, sourceSecurityGroupIdExist := d.GetOk("source_security_group_id")
_, prefixListIdExist := d.GetOk("prefix_list_id")
if !cidrExist && !sourceSecurityGroupIdExist && !prefixListIdExist {
return WrapError(fmt.Errorf("you must specify one of the following field: cidr_ip, source_security_group_id, prefix_list_id"))
}
request, err := buildAliyunSGRuleRequest(d, meta)
if err != nil {
return WrapError(err)
}
if direction == string(DirectionIngress) {
request.ApiName = "AuthorizeSecurityGroup"
_, err = client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ProcessCommonRequest(request)
})
} else {
request.ApiName = "AuthorizeSecurityGroupEgress"
_, err = client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ProcessCommonRequest(request)
})
}
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_security_group_rule", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
var cidr_ip string
if ip, ok := d.GetOk("cidr_ip"); ok {
cidr_ip = ip.(string)
} else {
cidr_ip = d.Get("source_security_group_id").(string)
}
d.SetId(sgId + ":" + direction + ":" + ptl + ":" + port + ":" + nicType + ":" + cidr_ip + ":" + policy + ":" + strconv.Itoa(priority))
return resourceAliyunSecurityGroupRuleRead(d, meta)
}
func resourceAliyunSecurityGroupRuleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
parts := strings.Split(d.Id(), ":")
policy := parseSecurityRuleId(d, meta, 6)
strPriority := parseSecurityRuleId(d, meta, 7)
var priority int
if policy == "" || strPriority == "" {
policy = d.Get("policy").(string)
priority = d.Get("priority").(int)
d.SetId(d.Id() + ":" + policy + ":" + strconv.Itoa(priority))
} else {
prior, err := strconv.Atoi(strPriority)
if err != nil {
return WrapError(err)
}
priority = prior
}
sgId := parts[0]
direction := parts[1]
// wait the rule exist
var object ecs.Permission
wait := incrementalWait(3*time.Second, 5*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
obj, err := ecsService.DescribeSecurityGroupRule(d.Id())
if err != nil && d.IsNewResource() {
wait()
return resource.RetryableError(err)
} else {
object = obj
return resource.NonRetryableError(err)
}
})
if err != nil {
if NotFoundError(err) && !d.IsNewResource() {
log.Printf("[DEBUG] Resource alicloud_security_group_rule ecsService.DescribeSecurityGroupRule Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("type", object.Direction)
d.Set("ip_protocol", strings.ToLower(string(object.IpProtocol)))
d.Set("nic_type", object.NicType)
d.Set("policy", strings.ToLower(string(object.Policy)))
d.Set("port_range", object.PortRange)
d.Set("description", object.Description)
if pri, err := strconv.Atoi(object.Priority); err != nil {
return WrapError(err)
} else {
d.Set("priority", pri)
}
d.Set("security_group_id", sgId)
//support source and desc by type
if direction == string(DirectionIngress) {
d.Set("cidr_ip", object.SourceCidrIp)
d.Set("source_security_group_id", object.SourceGroupId)
d.Set("source_group_owner_account", object.SourceGroupOwnerAccount)
d.Set("prefix_list_id", object.SourcePrefixListId)
} else {
d.Set("cidr_ip", object.DestCidrIp)
d.Set("source_security_group_id", object.DestGroupId)
d.Set("source_group_owner_account", object.DestGroupOwnerAccount)
d.Set("prefix_list_id", object.DestPrefixListId)
}
return nil
}
func resourceAliyunSecurityGroupRuleUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
policy := parseSecurityRuleId(d, meta, 6)
strPriority := parseSecurityRuleId(d, meta, 7)
var priority int
if policy == "" || strPriority == "" {
policy = d.Get("policy").(string)
priority = d.Get("priority").(int)
d.SetId(d.Id() + ":" + policy + ":" + strconv.Itoa(priority))
} else {
prior, err := strconv.Atoi(strPriority)
if err != nil {
return WrapError(err)
}
priority = prior
}
request, err := buildAliyunSGRuleRequest(d, meta)
if err != nil {
return WrapError(err)
}
direction := d.Get("type").(string)
if direction == string(DirectionIngress) {
request.ApiName = "ModifySecurityGroupRule"
_, err = client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ProcessCommonRequest(request)
})
} else {
request.ApiName = "ModifySecurityGroupEgressRule"
_, err = client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ProcessCommonRequest(request)
})
}
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ProcessCommonRequest(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.Headers, request)
return resourceAliyunSecurityGroupRuleRead(d, meta)
}
func deleteSecurityGroupRule(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ruleType := d.Get("type").(string)
request, err := buildAliyunSGRuleRequest(d, meta)
if err != nil {
return WrapError(err)
}
if ruleType == string(DirectionIngress) {
request.ApiName = "RevokeSecurityGroup"
_, err = client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ProcessCommonRequest(request)
})
} else {
request.ApiName = "RevokeSecurityGroupEgress"
_, err = client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ProcessCommonRequest(request)
})
}
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return nil
}
func resourceAliyunSecurityGroupRuleDelete(d *schema.ResourceData, meta interface{}) error {
policy := parseSecurityRuleId(d, meta, 6)
strPriority := parseSecurityRuleId(d, meta, 7)
var priority int
if policy == "" || strPriority == "" {
policy = d.Get("policy").(string)
priority = d.Get("priority").(int)
d.SetId(d.Id() + ":" + policy + ":" + strconv.Itoa(priority))
} else {
prior, err := strconv.Atoi(strPriority)
if err != nil {
return WrapError(err)
}
priority = prior
}
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
err := deleteSecurityGroupRule(d, meta)
if err != nil {
if NotFoundError(err) || IsExpectedErrors(err, []string{"InvalidSecurityGroupId.NotFound"}) {
return nil
}
return resource.RetryableError(err)
}
return nil
})
if err != nil {
return WrapError(err)
}
return nil
}
func buildAliyunSGRuleRequest(d *schema.ResourceData, meta interface{}) (*requests.CommonRequest, error) {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
// Get product code from the built request
ruleReq := ecs.CreateModifySecurityGroupRuleRequest()
request, err := client.NewCommonRequest(ruleReq.GetProduct(), ruleReq.GetLocationServiceCode(), strings.ToUpper(string(Https)), connectivity.ApiVersion20140526)
if err != nil {
return request, WrapError(err)
}
direction := d.Get("type").(string)
port_range := d.Get("port_range").(string)
request.QueryParams["PortRange"] = port_range
if v, ok := d.GetOk("ip_protocol"); ok {
request.QueryParams["IpProtocol"] = v.(string)
if v.(string) == string(Tcp) || v.(string) == string(Udp) {
if port_range == AllPortRange {
return nil, fmt.Errorf("'tcp' and 'udp' can support port range: [1, 65535]. Please correct it and try again.")
}
} else if port_range != AllPortRange {
return nil, fmt.Errorf("'icmp', 'gre' and 'all' only support port range '-1/-1'. Please correct it and try again.")
}
}
if v, ok := d.GetOk("policy"); ok {
request.QueryParams["Policy"] = v.(string)
}
if v, ok := d.GetOk("priority"); ok {
request.QueryParams["Priority"] = strconv.Itoa(v.(int))
}
if v, ok := d.GetOk("cidr_ip"); ok {
if direction == string(DirectionIngress) {
request.QueryParams["SourceCidrIp"] = v.(string)
} else {
request.QueryParams["DestCidrIp"] = v.(string)
}
}
if v, ok := d.GetOk("prefix_list_id"); ok {
if direction == string(DirectionIngress) {
request.QueryParams["SourcePrefixListId"] = v.(string)
} else {
request.QueryParams["DestPrefixListId"] = v.(string)
}
}
var targetGroupId string
if v, ok := d.GetOk("source_security_group_id"); ok {
targetGroupId = v.(string)
if direction == string(DirectionIngress) {
request.QueryParams["SourceGroupId"] = targetGroupId
} else {
request.QueryParams["DestGroupId"] = targetGroupId
}
}
if v, ok := d.GetOk("source_group_owner_account"); ok {
if direction == string(DirectionIngress) {
request.QueryParams["SourceGroupOwnerAccount"] = v.(string)
} else {
request.QueryParams["DestGroupOwnerAccount"] = v.(string)
}
}
sgId := d.Get("security_group_id").(string)
group, err := ecsService.DescribeSecurityGroup(sgId)
if err != nil {
return nil, WrapError(err)
}
if v, ok := d.GetOk("nic_type"); ok {
if group.VpcId != "" || targetGroupId != "" {
if GroupRuleNicType(v.(string)) != GroupRuleIntranet {
return nil, fmt.Errorf("When security group in the vpc or authorizing permission for source/destination security group, " +
"the nic_type must be 'intranet'.")
}
}
request.QueryParams["NicType"] = v.(string)
}
request.QueryParams["SecurityGroupId"] = sgId
description := d.Get("description").(string)
request.QueryParams["Description"] = description
return request, nil
}
func parseSecurityRuleId(d *schema.ResourceData, meta interface{}, index int) (result string) {
parts := strings.Split(d.Id(), ":")
defer func() {
if e := recover(); e != nil {
log.Printf("Panicing %s\r\n", e)
result = ""
}
}()
return parts[index]
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudServiceMeshServiceMesh() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudServiceMeshServiceMeshCreate,
Read: resourceAlicloudServiceMeshServiceMeshRead,
Update: resourceAlicloudServiceMeshServiceMeshUpdate,
Delete: resourceAlicloudServiceMeshServiceMeshDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
Delete: schema.DefaultTimeout(5 * time.Minute),
Update: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"force": {
Type: schema.TypeBool,
Optional: true,
},
"load_balancer": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"api_server_public_eip": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"pilot_public_eip": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"api_server_loadbalancer_id": {
Type: schema.TypeString,
Computed: true,
},
"pilot_public_loadbalancer_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
ForceNew: true,
},
"mesh_config": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"access_log": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enabled": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
},
},
},
"audit": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enabled": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"project": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
},
},
},
"customized_zipkin": {
Type: schema.TypeBool,
Optional: true,
},
"kiali": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enabled": {
Type: schema.TypeBool,
Optional: true,
},
},
},
},
"opa": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enabled": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"limit_cpu": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"limit_memory": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"log_level": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"request_cpu": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"request_memory": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
},
},
},
"outbound_traffic_policy": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"ALLOW_ANY", "REGISTRY_ONLY"}, false),
},
"pilot": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"http10_enabled": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"trace_sampling": {
Type: schema.TypeFloat,
Optional: true,
},
},
},
},
"proxy": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"limit_cpu": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"limit_memory": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"request_cpu": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"request_memory": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
},
},
},
"sidecar_injector": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"auto_injection_policy_enabled": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"enable_namespaces_by_default": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"limit_cpu": {
Type: schema.TypeString,
Optional: true,
},
"limit_memory": {
Type: schema.TypeString,
Optional: true,
},
"request_cpu": {
Type: schema.TypeString,
Optional: true,
},
"request_memory": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"telemetry": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"tracing": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"enable_locality_lb": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
},
},
},
"network": {
Type: schema.TypeSet,
Required: true,
MaxItems: 1,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"vpc_id": {
Type: schema.TypeString,
Required: true,
},
"vswitche_list": {
Type: schema.TypeList,
Required: true,
MaxItems: 1,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"service_mesh_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"edition": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Default", "Pro"}, false),
},
"version": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"v1.9.7.31-g24cdcb43-aliyun", "v1.8.6.52-g60741c97-aliyun"}, false),
},
},
}
}
func resourceAlicloudServiceMeshServiceMeshCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateServiceMesh"
request := make(map[string]interface{})
conn, err := client.NewServicemeshClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("version"); ok {
request["IstioVersion"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("service_mesh_name"); ok {
request["Name"] = v
}
if v, ok := d.GetOk("edition"); ok {
request["Edition"] = v
}
if v, ok := d.GetOk("network"); ok {
for _, networkMap := range v.(*schema.Set).List() {
if networkArg, ok := networkMap.(map[string]interface{}); ok {
if v, ok := networkArg["vpc_id"]; ok {
request["VpcId"] = v
}
if v, ok := networkArg["vswitche_list"]; ok {
request["VSwitches"] = convertListToJsonString(v.([]interface{}))
}
}
}
}
if v, ok := d.GetOk("load_balancer"); ok {
for _, loadBalancerMap := range v.(*schema.Set).List() {
if loadBalancerArg, ok := loadBalancerMap.(map[string]interface{}); ok {
if v, ok := loadBalancerArg["api_server_public_eip"]; ok {
request["ApiServerPublicEip"] = v
}
if v, ok := loadBalancerArg["pilot_public_eip"]; ok {
request["PilotPublicEip"] = v
}
}
}
}
if v, ok := d.GetOk("mesh_config"); ok {
for _, meshConfigMap := range v.(*schema.Set).List() {
if meshConfigArg, ok := meshConfigMap.(map[string]interface{}); ok {
if v, ok := meshConfigArg["customized_zipkin"]; ok {
request["CustomizedZipkin"] = v
}
if v, ok := meshConfigArg["tracing"]; ok {
request["Tracing"] = v
}
if v, ok := meshConfigArg["telemetry"]; ok {
request["Telemetry"] = v
}
if v, ok := meshConfigArg["enable_locality_lb"]; ok {
request["EnableLocalityLB"] = v
}
if pilot, ok := meshConfigArg["pilot"]; ok {
for _, pilotMap := range pilot.(*schema.Set).List() {
if pilotArg, ok := pilotMap.(map[string]interface{}); ok {
if v, ok := pilotArg["trace_sampling"]; ok {
request["TraceSampling"] = v
}
}
}
}
if AccessLog, ok := meshConfigArg["access_log"]; ok {
for _, AccessLogMap := range AccessLog.(*schema.Set).List() {
if AccessLogArg, ok := AccessLogMap.(map[string]interface{}); ok {
if v, ok := AccessLogArg["enabled"]; ok {
request["AccessLogEnabled"] = v
}
}
}
}
if proxy, ok := meshConfigArg["proxy"]; ok {
for _, proxyMap := range proxy.(*schema.Set).List() {
if proxyArg, ok := proxyMap.(map[string]interface{}); ok {
if v, ok := proxyArg["request_memory"]; ok {
request["ProxyRequestMemory"] = v
}
if v, ok := proxyArg["request_cpu"]; ok {
request["ProxyRequestCPU"] = v
}
if v, ok := proxyArg["limit_memory"]; ok {
request["ProxyLimitMemory"] = v
}
if v, ok := proxyArg["limit_cpu"]; ok {
request["ProxyLimitCPU"] = v
}
}
}
}
if opa, ok := meshConfigArg["opa"]; ok {
for _, opaMap := range opa.(*schema.Set).List() {
if opaArg, ok := opaMap.(map[string]interface{}); ok {
if v, ok := opaArg["enabled"]; ok {
request["OpaEnabled"] = v
}
if v, ok := opaArg["log_level"]; ok {
request["OPALogLevel"] = v
}
if v, ok := opaArg["request_cpu"]; ok {
request["OPARequestCPU"] = v
}
if v, ok := opaArg["request_memory"]; ok {
request["OPARequestMemory"] = v
}
if v, ok := opaArg["limit_cpu"]; ok {
request["OPALimitCPU"] = v
}
if v, ok := opaArg["limit_memory"]; ok {
request["OPALimitMemory"] = v
}
}
}
}
if audit, ok := meshConfigArg["audit"]; ok {
for _, auditMap := range audit.(*schema.Set).List() {
if auditArg, ok := auditMap.(map[string]interface{}); ok {
if v, ok := auditArg["enabled"]; ok {
request["EnableAudit"] = v
}
if v, ok := auditArg["project"]; ok {
request["AuditProject"] = v
}
if v, ok := auditArg["enabled"]; ok {
request["OpaEnabled"] = v
}
}
}
}
if kiali, ok := meshConfigArg["kiali"]; ok {
for _, kialiMap := range kiali.(*schema.Set).List() {
if kialiArg, ok := kialiMap.(map[string]interface{}); ok {
if v, ok := kialiArg["enabled"]; ok {
request["KialiEnabled"] = v
}
}
}
}
}
}
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ERR404", "InvalidActiveState.ACK"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_service_mesh_service_mesh", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["ServiceMeshId"]))
servicemeshService := ServicemeshService{client}
stateConf := BuildStateConf([]string{}, []string{"running"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, servicemeshService.ServiceMeshServiceMeshStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudServiceMeshServiceMeshUpdate(d, meta)
}
func resourceAlicloudServiceMeshServiceMeshRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
servicemeshService := ServicemeshService{client}
object, err := servicemeshService.DescribeServiceMeshServiceMesh(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_service_mesh_service_mesh servicemeshService.DescribeServiceMeshServiceMesh Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("service_mesh_name", object["ServiceMeshInfo"].(map[string]interface{})["Name"])
d.Set("edition", object["ServiceMeshInfo"].(map[string]interface{})["Profile"])
if spec, ok := object["Spec"]; ok {
if specArg, ok := spec.(map[string]interface{}); ok && len(specArg) > 0 {
loadBalancerSli := make([]map[string]interface{}, 0)
if loadBalancer, ok := specArg["LoadBalancer"]; ok {
if loadBalancerArg, ok := loadBalancer.(map[string]interface{}); ok && len(loadBalancerArg) > 0 {
loadBalancerMap := make(map[string]interface{})
loadBalancerMap["pilot_public_eip"] = loadBalancerArg["PilotPublicEip"]
loadBalancerMap["pilot_public_loadbalancer_id"] = loadBalancerArg["PilotPublicLoadbalancerId"]
loadBalancerMap["api_server_loadbalancer_id"] = loadBalancerArg["ApiServerLoadbalancerId"]
loadBalancerMap["api_server_public_eip"] = loadBalancerArg["ApiServerPublicEip"]
loadBalancerSli = append(loadBalancerSli, loadBalancerMap)
}
}
d.Set("load_balancer", loadBalancerSli)
meshConfigSli := make([]map[string]interface{}, 0)
if meshConfig, ok := specArg["MeshConfig"]; ok {
meshConfigMap := make(map[string]interface{})
if meshConfigArg, ok := meshConfig.(map[string]interface{}); ok && len(meshConfigArg) > 0 {
accessLogSli := make([]map[string]interface{}, 0)
if accessLog, ok := meshConfigArg["AccessLog"]; ok {
if accessLogArg, ok := accessLog.(map[string]interface{}); ok && len(accessLogArg) > 0 {
accessLogMap := make(map[string]interface{})
accessLogMap["enabled"] = accessLogArg["Enabled"]
accessLogSli = append(accessLogSli, accessLogMap)
}
}
meshConfigMap["access_log"] = accessLogSli
auditSli := make([]map[string]interface{}, 0)
if audit, ok := meshConfigArg["Audit"]; ok {
if auditArg, ok := audit.(map[string]interface{}); ok && len(auditArg) > 0 {
auditMap := make(map[string]interface{})
auditMap["enabled"] = auditArg["Enabled"]
auditMap["project"] = auditArg["Project"]
auditSli = append(auditSli, auditMap)
meshConfigMap["audit"] = auditSli
}
}
meshConfigMap["customized_zipkin"] = meshConfigArg["CustomizedZipkin"]
meshConfigMap["enable_locality_lb"] = meshConfigArg["EnableLocalityLB"]
kialiSli := make([]map[string]interface{}, 0)
if kiali, ok := meshConfigArg["Kiali"]; ok {
if kialiArg, ok := kiali.(map[string]interface{}); ok && len(kialiArg) > 0 {
kialiMap := make(map[string]interface{})
kialiMap["enabled"] = kialiArg["Enabled"]
kialiSli = append(kialiSli, kialiMap)
}
}
meshConfigMap["kiali"] = kialiSli
opaSli := make([]map[string]interface{}, 0)
if opa, ok := meshConfigArg["OPA"]; ok {
opaMap := make(map[string]interface{})
if opaArg, ok := opa.(map[string]interface{}); ok && len(opaArg) > 0 {
opaMap["enabled"] = opaArg["Enabled"]
opaMap["limit_cpu"] = opaArg["LimitCPU"]
opaMap["limit_memory"] = opaArg["LimitMemory"]
opaMap["log_level"] = opaArg["LogLevel"]
opaMap["request_cpu"] = opaArg["RequestCPU"]
opaMap["request_memory"] = opaArg["RequestMemory"]
}
opaSli = append(opaSli, opaMap)
}
meshConfigMap["opa"] = opaSli
meshConfigMap["outbound_traffic_policy"] = meshConfigArg["OutboundTrafficPolicy"]
pilotSli := make([]map[string]interface{}, 0)
if pilot := meshConfigArg["Pilot"]; ok {
if pilotArg, ok := pilot.(map[string]interface{}); ok && len(pilotArg) > 0 {
pilotMap := make(map[string]interface{})
pilotMap["http10_enabled"] = pilotArg["Http10Enabled"]
pilotMap["trace_sampling"] = pilotArg["TraceSampling"]
pilotSli = append(pilotSli, pilotMap)
}
}
meshConfigMap["pilot"] = pilotSli
proxySli := make([]map[string]interface{}, 0)
if proxy, ok := meshConfigArg["Proxy"]; ok {
if proxyArg, ok := proxy.(map[string]interface{}); ok && len(proxyArg) > 0 {
proxyMap := make(map[string]interface{})
proxyMap["limit_cpu"] = proxyArg["LimitCPU"]
proxyMap["limit_memory"] = proxyArg["LimitMemory"]
proxyMap["request_cpu"] = proxyArg["RequestCPU"]
proxyMap["request_memory"] = proxyArg["RequestMemory"]
proxySli = append(proxySli, proxyMap)
}
}
meshConfigMap["proxy"] = proxySli
sidecarInjectorSli := make([]map[string]interface{}, 0)
if sidecarInjector, ok := meshConfigArg["SidecarInjector"]; ok {
if sidecarInjectorArg, ok := sidecarInjector.(map[string]interface{}); ok && len(sidecarInjectorArg) > 0 {
sidecarInjectorMap := make(map[string]interface{})
sidecarInjectorMap["auto_injection_policy_enabled"] = sidecarInjectorArg["AutoInjectionPolicyEnabled"]
sidecarInjectorMap["enable_namespaces_by_default"] = sidecarInjectorArg["EnableNamespacesByDefault"]
sidecarInjectorMap["limit_cpu"] = sidecarInjectorArg["LimitCPU"]
sidecarInjectorMap["limit_memory"] = sidecarInjectorArg["LimitMemory"]
sidecarInjectorMap["request_cpu"] = sidecarInjectorArg["RequestCPU"]
sidecarInjectorMap["request_memory"] = sidecarInjectorArg["RequestMemory"]
sidecarInjectorSli = append(sidecarInjectorSli, sidecarInjectorMap)
}
}
meshConfigMap["sidecar_injector"] = sidecarInjectorSli
meshConfigMap["telemetry"] = meshConfigArg["Telemetry"]
meshConfigMap["tracing"] = meshConfigArg["Tracing"]
meshConfigSli = append(meshConfigSli, meshConfigMap)
}
}
d.Set("mesh_config", meshConfigSli)
networkSli := make([]map[string]interface{}, 0)
if network, ok := specArg["Network"]; ok {
if networkArg, ok := network.(map[string]interface{}); ok && len(networkArg) > 0 {
networkMap := make(map[string]interface{})
networkMap["vswitche_list"] = networkArg["VSwitches"]
networkMap["vpc_id"] = networkArg["VpcId"]
networkSli = append(networkSli, networkMap)
}
}
d.Set("network", networkSli)
}
}
d.Set("status", object["ServiceMeshInfo"].(map[string]interface{})["State"])
d.Set("version", object["ServiceMeshInfo"].(map[string]interface{})["Version"])
return nil
}
func resourceAlicloudServiceMeshServiceMeshUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
servicemeshService := ServicemeshService{client}
var response map[string]interface{}
d.Partial(true)
update := false
updateMeshFeatureReq := map[string]interface{}{
"ServiceMeshId": d.Id(),
}
if d.HasChange("mesh_config") {
update = true
}
if v, ok := d.GetOk("mesh_config"); ok {
for _, meshConfigMap := range v.(*schema.Set).List() {
if meshConfigArg, ok := meshConfigMap.(map[string]interface{}); ok {
if v, ok := meshConfigArg["customized_zipkin"]; ok {
updateMeshFeatureReq["CustomizedZipkin"] = v
}
if v, ok := meshConfigArg["outbound_traffic_policy"]; ok {
updateMeshFeatureReq["OutboundTrafficPolicy"] = v
}
if proxy, ok := meshConfigArg["proxy"]; ok {
for _, proxyMap := range proxy.(*schema.Set).List() {
if proxyArg, ok := proxyMap.(map[string]interface{}); ok {
if v, ok := proxyArg["request_memory"]; ok {
updateMeshFeatureReq["ProxyRequestMemory"] = v
}
if v, ok := proxyArg["request_cpu"]; ok {
updateMeshFeatureReq["ProxyRequestCPU"] = v
}
if v, ok := proxyArg["limit_memory"]; ok {
updateMeshFeatureReq["ProxyLimitMemory"] = v
}
if v, ok := proxyArg["limit_cpu"]; ok {
updateMeshFeatureReq["ProxyLimitCPU"] = v
}
}
}
}
if AccessLog, ok := meshConfigArg["access_log"]; ok {
for _, AccessLogMap := range AccessLog.(*schema.Set).List() {
if AccessLogArg, ok := AccessLogMap.(map[string]interface{}); ok {
if v, ok := AccessLogArg["enabled"]; ok {
updateMeshFeatureReq["AccessLogEnabled"] = v
}
}
}
}
if sidecarInjector, ok := meshConfigArg["sidecar_injector"]; ok && !d.IsNewResource() {
for _, sidecarInjectorMap := range sidecarInjector.(*schema.Set).List() {
if sidecarInjectorArg, ok := sidecarInjectorMap.(map[string]interface{}); ok {
if v, ok := sidecarInjectorArg["auto_injection_policy_enabled"]; ok {
updateMeshFeatureReq["AutoInjectionPolicyEnabled"] = v
}
if v, ok := sidecarInjectorArg["enable_namespaces_by_default"]; ok {
updateMeshFeatureReq["EnableNamespacesByDefault"] = v
}
if v, ok := sidecarInjectorArg["limit_cpu"]; ok {
updateMeshFeatureReq["SidecarInjectorLimitCPU"] = v
}
if v, ok := sidecarInjectorArg["limit_memory"]; ok {
updateMeshFeatureReq["SidecarInjectorLimitMemory"] = v
}
if v, ok := sidecarInjectorArg["request_cpu"]; ok {
updateMeshFeatureReq["SidecarInjectorRequestCPU"] = v
}
if v, ok := sidecarInjectorArg["request_memory"]; ok {
updateMeshFeatureReq["SidecarInjectorRequestMemory"] = v
}
}
}
}
if AccessLog, ok := meshConfigArg["mesh_config"]; ok {
for _, AccessLogMap := range AccessLog.(*schema.Set).List() {
if AccessLogArg, ok := AccessLogMap.(map[string]interface{}); ok {
if v, ok := AccessLogArg["enabled"]; ok {
updateMeshFeatureReq["AccessLogEnabled"] = v
}
}
}
}
if v, ok := meshConfigArg["tracing"]; ok {
updateMeshFeatureReq["Tracing"] = v
}
if v, ok := meshConfigArg["telemetry"]; ok {
updateMeshFeatureReq["Telemetry"] = v
}
if pilot, ok := meshConfigArg["pilot"]; ok {
for _, pilotMap := range pilot.(*schema.Set).List() {
if pilotArg, ok := pilotMap.(map[string]interface{}); ok {
if v, ok := pilotArg["trace_sampling"]; ok {
updateMeshFeatureReq["TraceSampling"] = v
}
if v, ok := pilotArg["http10_enabled"]; ok {
updateMeshFeatureReq["Http10Enabled"] = v
}
}
}
}
if opa, ok := meshConfigArg["opa"]; ok {
for _, opaMap := range opa.(*schema.Set).List() {
if opaArg, ok := opaMap.(map[string]interface{}); ok {
if v, ok := opaArg["enabled"]; ok {
updateMeshFeatureReq["OpaEnabled"] = v
}
if v, ok := opaArg["log_level"]; ok {
updateMeshFeatureReq["OPALogLevel"] = v
}
if v, ok := opaArg["request_cpu"]; ok {
updateMeshFeatureReq["OPARequestCPU"] = v
}
if v, ok := opaArg["request_memory"]; ok {
updateMeshFeatureReq["OPARequestMemory"] = v
}
if v, ok := opaArg["limit_cpu"]; ok {
updateMeshFeatureReq["OPALimitCPU"] = v
}
if v, ok := opaArg["limit_memory"]; ok {
updateMeshFeatureReq["OPALimitMemory"] = v
}
}
}
}
if audit, ok := meshConfigArg["audit"]; ok {
for _, auditMap := range audit.(*schema.Set).List() {
if auditArg, ok := auditMap.(map[string]interface{}); ok {
if v, ok := auditArg["enabled"]; ok {
updateMeshFeatureReq["EnableAudit"] = v
}
if v, ok := auditArg["project"]; ok {
updateMeshFeatureReq["AuditProject"] = v
}
}
}
}
if kiali, ok := meshConfigArg["kiali"]; ok {
for _, kialiMap := range kiali.(*schema.Set).List() {
if kialiArg, ok := kialiMap.(map[string]interface{}); ok {
if v, ok := kialiArg["enabled"]; ok {
updateMeshFeatureReq["KialiEnabled"] = v
}
}
}
}
}
}
}
if update {
action := "UpdateMeshFeature"
conn, err := client.NewServicemeshClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-11"), StringPointer("AK"), nil, updateMeshFeatureReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, updateMeshFeatureReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, servicemeshService.ServiceMeshServiceMeshStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.Partial(false)
return resourceAlicloudServiceMeshServiceMeshRead(d, meta)
}
func resourceAlicloudServiceMeshServiceMeshDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
servicemeshService := ServicemeshService{client}
action := "DeleteServiceMesh"
var response map[string]interface{}
conn, err := client.NewServicemeshClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ServiceMeshId": d.Id(),
}
if v, ok := d.GetOkExists("force"); ok {
request["Force"] = v
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-11"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ErrorPermitted.ClustersNotEmpty", "RelatedResourceReused"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ServiceMesh.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, servicemeshService.ServiceMeshServiceMeshStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudSimpleApplicationServerCustomImage() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSimpleApplicationServerCustomImageCreate,
Read: resourceAlicloudSimpleApplicationServerCustomImageRead,
Update: resourceAlicloudSimpleApplicationServerCustomImageUpdate,
Delete: resourceAlicloudSimpleApplicationServerCustomImageDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"custom_image_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile("^[0-9a-zA-Z\u4E00-\u9FA5][\u4E00-\u9FA5A-Za-z0-9:_-]{2,128}$"), "The name must be `2` to `128` characters in length. It must start with a letter or a number. It can contain letters, digits, colons (:), underscores (_) and hyphens (-)."),
},
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Share", "UnShare"}, false),
},
"system_snapshot_id": {
Type: schema.TypeString,
Required: true,
},
},
}
}
func resourceAlicloudSimpleApplicationServerCustomImageCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateCustomImage"
request := make(map[string]interface{})
conn, err := client.NewSwasClient()
if err != nil {
return WrapError(err)
}
request["ImageName"] = d.Get("custom_image_name")
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["InstanceId"] = d.Get("instance_id")
request["RegionId"] = client.RegionId
request["SystemSnapshotId"] = d.Get("system_snapshot_id")
request["ClientToken"] = buildClientToken("CreateCustomImage")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_simple_application_server_custom_image", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["ImageId"]))
return resourceAlicloudSimpleApplicationServerCustomImageUpdate(d, meta)
}
func resourceAlicloudSimpleApplicationServerCustomImageRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
swasOpenService := SwasOpenService{client}
object, err := swasOpenService.DescribeSimpleApplicationServerCustomImage(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_simple_application_server_custom_image swasOpenService.DescribeSimpleApplicationServerCustomImage Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("custom_image_name", object["ImageName"])
d.Set("description", object["Description"])
return nil
}
func resourceAlicloudSimpleApplicationServerCustomImageUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"ImageId": d.Id(),
}
if d.HasChange("status") {
update = true
if v, ok := d.GetOk("status"); ok {
request["Operation"] = v
}
}
if update {
action := "ModifyImageShareStatus"
conn, err := client.NewSwasClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("ModifyImageShareStatus")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudSimpleApplicationServerCustomImageRead(d, meta)
}
func resourceAlicloudSimpleApplicationServerCustomImageDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
if v := d.Get("status"); v.(string) == "Share" {
var response map[string]interface{}
request := map[string]interface{}{
"ImageId": d.Id(),
"Operation": "UnShare",
}
action := "ModifyImageShareStatus"
conn, err := client.NewSwasClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("ModifyImageShareStatus")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
action := "DeleteCustomImage"
var response map[string]interface{}
conn, err := client.NewSwasClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"ImageId": d.Id(),
}
request["RegionId"] = client.RegionId
request["ClientToken"] = buildClientToken("DeleteCustomImage")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudSimpleApplicationServerFirewallRule() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSimpleApplicationServerFirewallRuleCreate,
Read: resourceAlicloudSimpleApplicationServerFirewallRuleRead,
Delete: resourceAlicloudSimpleApplicationServerFirewallRuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"firewall_rule_id": {
Type: schema.TypeString,
Computed: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"port": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"remark": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"rule_protocol": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Tcp", "TcpAndUdp", "Udp"}, false),
},
},
}
}
func resourceAlicloudSimpleApplicationServerFirewallRuleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateFirewallRule"
request := make(map[string]interface{})
conn, err := client.NewSwasClient()
if err != nil {
return WrapError(err)
}
request["InstanceId"] = d.Get("instance_id")
request["Port"] = d.Get("port")
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("remark"); ok {
request["Remark"] = v
}
request["RuleProtocol"] = d.Get("rule_protocol")
request["ClientToken"] = buildClientToken("CreateFirewallRule")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_simple_application_server_firewall_rule", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["InstanceId"], ":", response["FirewallId"]))
return resourceAlicloudSimpleApplicationServerFirewallRuleRead(d, meta)
}
func resourceAlicloudSimpleApplicationServerFirewallRuleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
swasOpenService := SwasOpenService{client}
object, err := swasOpenService.DescribeSimpleApplicationServerFirewallRule(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_simple_application_server_firewall_rule swasOpenService.DescribeSimpleApplicationServerFirewallRule Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("firewall_rule_id", parts[1])
d.Set("instance_id", parts[0])
d.Set("port", object["Port"])
d.Set("remark", object["Remark"])
d.Set("rule_protocol", convertSimpleApplicationServerFirewallRuleRuleProtocolResponse(object["RuleProtocol"].(string)))
return nil
}
func resourceAlicloudSimpleApplicationServerFirewallRuleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteFirewallRule"
var response map[string]interface{}
conn, err := client.NewSwasClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"RuleId": parts[1],
"InstanceId": parts[0],
}
request["RegionId"] = client.RegionId
request["ClientToken"] = buildClientToken("DeleteFirewallRule")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func convertSimpleApplicationServerFirewallRuleRuleProtocolResponse(source string) string {
switch source {
case "TCP":
return "Tcp"
case "UDP":
return "Udp"
case "TCP+UDP":
return "TcpAndUdp"
}
return source
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudSimpleApplicationServerInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSimpleApplicationServerInstanceCreate,
Read: resourceAlicloudSimpleApplicationServerInstanceRead,
Update: resourceAlicloudSimpleApplicationServerInstanceUpdate,
Delete: resourceAlicloudSimpleApplicationServerInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
Update: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"auto_renew": {
Type: schema.TypeBool,
Optional: true,
},
"auto_renew_period": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{1, 12, 24, 3, 36, 6}),
},
"data_disk_size": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(0, 16380),
},
"image_id": {
Type: schema.TypeString,
Required: true,
},
"instance_name": {
Type: schema.TypeString,
Optional: true,
},
"password": {
Type: schema.TypeString,
Optional: true,
},
"payment_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Subscription"}, false),
},
"period": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntInSlice([]int{1, 12, 24, 3, 36, 6}),
},
"plan_id": {
Type: schema.TypeString,
Required: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Resetting", "Running", "Stopped", "Upgrading"}, false),
},
},
}
}
func resourceAlicloudSimpleApplicationServerInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateInstances"
request := make(map[string]interface{})
conn, err := client.NewSwasClient()
if err != nil {
return WrapError(err)
}
request["Amount"] = 1
if v, ok := d.GetOkExists("auto_renew"); ok {
request["AutoRenew"] = v
}
if v, ok := d.GetOk("auto_renew_period"); ok {
request["AutoRenewPeriod"] = v
}
if v, ok := d.GetOk("data_disk_size"); ok {
request["DataDiskSize"] = v
}
request["ImageId"] = d.Get("image_id")
if v, ok := d.GetOk("payment_type"); ok {
request["ChargeType"] = convertSimpleApplicationServerInstancePaymentTypeRequest(v.(string))
}
request["Period"] = d.Get("period")
request["PlanId"] = d.Get("plan_id")
request["RegionId"] = client.RegionId
request["ClientToken"] = buildClientToken("CreateInstances")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_simple_application_server_instance", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["InstanceIds"].([]interface{})[0]))
swasOpenService := SwasOpenService{client}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, swasOpenService.SimpleApplicationServerInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudSimpleApplicationServerInstanceUpdate(d, meta)
}
func resourceAlicloudSimpleApplicationServerInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
swasOpenService := SwasOpenService{client}
object, err := swasOpenService.DescribeSimpleApplicationServerInstance(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_simple_application_server_instance swasOpenService.DescribeSimpleApplicationServerInstance Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("image_id", object["ImageId"])
d.Set("instance_name", object["InstanceName"])
d.Set("payment_type", convertSimpleApplicationServerInstancePaymentTypeResponse(object["ChargeType"]))
d.Set("plan_id", object["PlanId"])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudSimpleApplicationServerInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
swasOpenService := SwasOpenService{client}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"InstanceId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("image_id") {
update = true
}
request["ImageId"] = d.Get("image_id")
request["RegionId"] = client.RegionId
if update {
action := "ResetSystem"
conn, err := client.NewSwasClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("ResetSystem")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectInstanceStatus"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, swasOpenService.SimpleApplicationServerInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("image_id")
}
update = false
upgradeInstanceReq := map[string]interface{}{
"InstanceId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("plan_id") {
update = true
}
upgradeInstanceReq["PlanId"] = d.Get("plan_id")
upgradeInstanceReq["RegionId"] = client.RegionId
if update {
action := "UpgradeInstance"
conn, err := client.NewSwasClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("UpgradeInstance")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, upgradeInstanceReq, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectInstanceStatus"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, upgradeInstanceReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, swasOpenService.SimpleApplicationServerInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("plan_id")
}
update = false
updateInstanceAttributeReq := map[string]interface{}{
"InstanceId": d.Id(),
}
updateInstanceAttributeReq["RegionId"] = client.RegionId
if d.HasChange("instance_name") {
update = true
if v, ok := d.GetOk("instance_name"); ok {
updateInstanceAttributeReq["InstanceName"] = v
}
}
if d.HasChange("password") {
update = true
if v, ok := d.GetOk("password"); ok {
updateInstanceAttributeReq["Password"] = v
}
}
if update {
action := "UpdateInstanceAttribute"
conn, err := client.NewSwasClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("UpdateInstanceAttribute")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, updateInstanceAttributeReq, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectInstanceStatus"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, updateInstanceAttributeReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, swasOpenService.SimpleApplicationServerInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("instance_name")
d.SetPartial("password")
}
if d.HasChange("status") {
object, err := swasOpenService.DescribeSimpleApplicationServerInstance(d.Id())
if err != nil {
return WrapError(err)
}
target := d.Get("status").(string)
if object["Status"].(string) != target {
if target == "Resetting" {
request := map[string]interface{}{
"InstanceId": d.Id(),
}
request["RegionId"] = client.RegionId
action := "RebootInstance"
conn, err := client.NewSwasClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("RebootInstance")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectInstanceStatus"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, swasOpenService.SimpleApplicationServerInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if target == "Running" {
request := map[string]interface{}{
"InstanceId": d.Id(),
}
request["RegionId"] = client.RegionId
action := "StartInstance"
conn, err := client.NewSwasClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("StartInstance")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectInstanceStatus"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, swasOpenService.SimpleApplicationServerInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if target == "Stopped" {
request := map[string]interface{}{
"InstanceId": d.Id(),
}
request["RegionId"] = client.RegionId
action := "StopInstance"
conn, err := client.NewSwasClient()
if err != nil {
return WrapError(err)
}
request["ClientToken"] = buildClientToken("StopInstance")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectInstanceStatus", "Throttling.User"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Stopped"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, swasOpenService.SimpleApplicationServerInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.SetPartial("status")
}
}
d.Partial(false)
return resourceAlicloudSimpleApplicationServerInstanceRead(d, meta)
}
func resourceAlicloudSimpleApplicationServerInstanceDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudSimpleApplicationServerInstance. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
func convertSimpleApplicationServerInstancePaymentTypeRequest(source interface{}) interface{} {
switch source {
case "Subscription":
return "PrePaid"
}
return source
}
func convertSimpleApplicationServerInstancePaymentTypeResponse(source interface{}) interface{} {
switch source {
case "PrePaid":
return "Subscription"
}
return source
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudSimpleApplicationServerSnapshot() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSimpleApplicationServerSnapshotCreate,
Read: resourceAlicloudSimpleApplicationServerSnapshotRead,
Delete: resourceAlicloudSimpleApplicationServerSnapshotDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(20 * time.Minute),
},
Schema: map[string]*schema.Schema{
"disk_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"snapshot_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile("^[a-zA-Z\u4E00-\u9FA5][\u4E00-\u9FA5A-Za-z0-9:._-]{2,50}$"), "The name must be 2 to 50 characters in length. It must start with a letter and cannot start with `http://` or `https://`. It can contain letters, digits, colons (:), underscores (_), periods (.),and hyphens (-)."),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudSimpleApplicationServerSnapshotCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateSnapshot"
request := make(map[string]interface{})
conn, err := client.NewSwasClient()
if err != nil {
return WrapError(err)
}
request["DiskId"] = d.Get("disk_id")
request["RegionId"] = client.RegionId
request["SnapshotName"] = d.Get("snapshot_name")
request["ClientToken"] = buildClientToken("CreateSnapshot")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_simple_application_server_snapshot", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["SnapshotId"]))
swasOpenService := SwasOpenService{client}
stateConf := BuildStateConf([]string{}, []string{"Accomplished"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, swasOpenService.SimpleApplicationServerSnapshotStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudSimpleApplicationServerSnapshotRead(d, meta)
}
func resourceAlicloudSimpleApplicationServerSnapshotRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
swasOpenService := SwasOpenService{client}
object, err := swasOpenService.DescribeSimpleApplicationServerSnapshot(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_simple_application_server_snapshot swasOpenService.DescribeSimpleApplicationServerSnapshot Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("disk_id", object["SourceDiskId"])
d.Set("snapshot_name", object["SnapshotName"])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudSimpleApplicationServerSnapshotDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteSnapshot"
var response map[string]interface{}
conn, err := client.NewSwasClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"SnapshotId": d.Id(),
}
request["RegionId"] = client.RegionId
request["ClientToken"] = buildClientToken("DeleteSnapshot")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"strings"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"time"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudSlbAcl() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSlbAclCreate,
Read: resourceAlicloudSlbAclRead,
Update: resourceAlicloudSlbAclUpdate,
Delete: resourceAlicloudSlbAclDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"ip_version": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "ipv4",
ValidateFunc: validation.StringInSlice([]string{"ipv4", "ipv6"}, false),
},
"entry_list": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"entry": {
Type: schema.TypeString,
Required: true,
},
"comment": {
Type: schema.TypeString,
Optional: true,
},
},
},
MaxItems: 300,
MinItems: 0,
},
"tags": tagsSchema(),
},
}
}
func resourceAlicloudSlbAclCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateAccessControlList"
request := make(map[string]interface{})
conn, err := client.NewSlbClient()
if err != nil {
return WrapError(err)
}
request["RegionId"] = client.RegionId
if v := d.Get("resource_group_id").(string); v != "" {
request["ResourceGroupId"] = v
}
request["AclName"] = strings.TrimSpace(d.Get("name").(string))
if v, ok := d.GetOk("address_ip_version"); ok {
request["AddressIPVersion"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_slb_acl", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["AclId"]))
return resourceAlicloudSlbAclUpdate(d, meta)
}
func resourceAlicloudSlbAclRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
tags, err := slbService.DescribeTags(d.Id(), nil, TagResourceAcl)
if err != nil {
return WrapError(err)
}
d.Set("tags", slbService.tagsToMap(tags))
object, err := slbService.DescribeSlbAcl(d.Id())
if err != nil {
if IsExpectedErrors(err, []string{"AclNotExist"}) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", object["AclName"])
d.Set("resource_group_id", object["ResourceGroupId"])
d.Set("ip_version", object["AddressIPVersion"])
if aclEntrys, ok := object["AclEntrys"]; ok {
if v, ok := aclEntrys.(map[string]interface{})["AclEntry"].([]interface{}); ok {
aclEntry := make([]map[string]interface{}, 0)
for _, val := range v {
item := val.(map[string]interface{})
temp := map[string]interface{}{
"comment": item["AclEntryComment"],
"entry": item["AclEntryIP"],
}
aclEntry = append(aclEntry, temp)
}
if err := d.Set("entry_list", aclEntry); err != nil {
return WrapError(err)
}
}
}
return nil
}
func resourceAlicloudSlbAclUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
var response map[string]interface{}
d.Partial(true)
if d.HasChange("tags") {
if err := slbService.setInstanceTags(d, TagResourceAcl); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
if !d.IsNewResource() && d.HasChange("name") {
request := map[string]interface{}{
"AclId": d.Id(),
}
if v, ok := d.GetOk("name"); ok {
request["AclName"] = v
}
request["RegionId"] = client.RegionId
action := "SetAccessControlListAttribute"
conn, err := client.NewSlbClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("name")
}
if d.HasChange("entry_list") {
o, n := d.GetChange("entry_list")
oe := o.(*schema.Set)
ne := n.(*schema.Set)
remove := oe.Difference(ne).List()
add := ne.Difference(oe).List()
if len(remove) > 0 {
removeList := SplitSlice(remove, 50)
for _, item := range removeList {
removedRequest := map[string]interface{}{
"AclId": d.Id(),
"RegionId": client.RegionId,
}
aclEntries, err := slbService.convertAclEntriesToString(item)
if err != nil {
return WrapError(err)
}
removedRequest["AclEntrys"] = aclEntries
action := "RemoveAccessControlListEntry"
conn, err := client.NewSlbClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, removedRequest, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, removedRequest)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
}
if len(add) > 0 {
addList := SplitSlice(add, 50)
for _, item := range addList {
addedRequest := map[string]interface{}{
"AclId": d.Id(),
"RegionId": client.RegionId,
}
aclEntries, err := slbService.convertAclEntriesToString(item)
if err != nil {
return WrapError(err)
}
addedRequest["AclEntrys"] = aclEntries
action := "AddAccessControlListEntry"
conn, err := client.NewSlbClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, addedRequest, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, addedRequest)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
}
d.SetPartial("entry_list")
}
d.Partial(false)
return resourceAlicloudSlbAclRead(d, meta)
}
func resourceAlicloudSlbAclDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteAccessControlList"
var response map[string]interface{}
conn, err := client.NewSlbClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"AclId": d.Id(),
"RegionId": client.RegionId,
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"AclNotExist"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/slb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliyunSlbAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunSlbAttachmentCreate,
Read: resourceAliyunSlbAttachmentRead,
Update: resourceAliyunSlbAttachmentUpdate,
Delete: resourceAliyunSlbAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"load_balancer_id": {
Type: schema.TypeString,
Required: true,
},
"instance_ids": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Required: true,
MaxItems: 20,
MinItems: 1,
},
"weight": {
Type: schema.TypeInt,
Optional: true,
Default: 100,
ValidateFunc: validation.IntBetween(0, 100),
},
"server_type": {
Type: schema.TypeString,
Optional: true,
Default: "ecs",
ValidateFunc: validation.StringInSlice([]string{"eni", "ecs"}, false),
},
"backend_servers": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"delete_protection_validation": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func resourceAliyunSlbAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
object, err := slbService.DescribeSlb(d.Get("load_balancer_id").(string))
if err != nil {
return WrapError(err)
}
d.SetId(object.LoadBalancerId)
return resourceAliyunSlbAttachmentUpdate(d, meta)
}
func resourceAliyunSlbAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
object, err := slbService.DescribeSlb(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
servers := object.BackendServers.BackendServer
instanceIds := make([]string, 0, len(servers))
var weight int
var serverType string
if len(servers) > 0 {
weight = servers[0].Weight
serverType = servers[0].Type
for _, e := range servers {
instanceIds = append(instanceIds, e.ServerId)
}
}
d.Set("load_balancer_id", object.LoadBalancerId)
d.Set("instance_ids", instanceIds)
d.Set("weight", weight)
d.Set("server_type", serverType)
d.Set("backend_servers", strings.Join(instanceIds, ","))
return nil
}
func resourceAliyunSlbAttachmentUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
update := false
weight := d.Get("weight").(int)
oldServerType, serverType := d.GetChange("server_type")
if d.HasChange("server_type") {
update = true
d.SetPartial("server_type")
}
if d.HasChange("weight") {
update = true
d.SetPartial("weight")
}
if d.HasChange("instance_ids") {
o, n := d.GetChange("instance_ids")
os := o.(*schema.Set)
ns := n.(*schema.Set)
remove := os.Difference(ns).List()
add := ns.Difference(os).List()
if len(add) > 0 {
request := slb.CreateAddBackendServersRequest()
request.RegionId = client.RegionId
request.LoadBalancerId = d.Id()
request.BackendServers = expandBackendServersToString(ns.Difference(os).List(), weight, serverType.(string))
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.AddBackendServers(request)
})
if err != nil {
if IsExpectedErrors(err, SlbIsBusy) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
if len(remove) > 0 {
request := slb.CreateRemoveBackendServersRequest()
request.RegionId = client.RegionId
request.LoadBalancerId = d.Id()
request.BackendServers = expandBackendServersToString(os.Difference(ns).List(), weight, oldServerType.(string))
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.RemoveBackendServers(request)
})
if err != nil {
if IsExpectedErrors(err, SlbIsBusy) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
if len(add) < 1 && len(remove) < 1 {
update = true
}
d.SetPartial("instance_ids")
}
if update {
request := slb.CreateSetBackendServersRequest()
request.RegionId = client.RegionId
request.LoadBalancerId = d.Id()
request.BackendServers = expandBackendServersToString(d.Get("instance_ids").(*schema.Set).List(), weight, serverType.(string))
if err := resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.SetBackendServers(request)
})
if err != nil {
if IsExpectedErrors(err, SlbIsBusy) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
return resourceAliyunSlbAttachmentRead(d, meta)
}
func resourceAliyunSlbAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
if d.Get("delete_protection_validation").(bool) {
lbInstance, err := slbService.DescribeSlb(d.Id())
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
if lbInstance.DeleteProtection == "on" {
return WrapError(fmt.Errorf("Current SLB Instance %s has enabled DeleteProtection. Please set delete_protection_validation to false to delete the resource.", d.Id()))
}
}
instanceSet := d.Get("instance_ids").(*schema.Set)
weight := d.Get("weight").(int)
serverType := d.Get("server_type").(string)
if len(instanceSet.List()) > 0 {
request := slb.CreateRemoveBackendServersRequest()
request.RegionId = client.RegionId
request.LoadBalancerId = d.Id()
request.BackendServers = expandBackendServersToString(d.Get("instance_ids").(*schema.Set).List(), weight, serverType)
if err := resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.RemoveBackendServers(request)
})
if err != nil {
if IsExpectedErrors(err, SlbIsBusy) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
return WrapError(slbService.WaitSlbAttribute(d.Id(), instanceSet, DefaultTimeout))
}
package alicloud
import (
"fmt"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/slb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliyunSlbBackendServer() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunSlbBackendServersCreate,
Read: resourceAliyunSlbBackendServersRead,
Update: resourceAliyunSlbBackendServersUpdate,
Delete: resourceAliyunSlbBackendServersDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"load_balancer_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"backend_servers": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"server_id": {
Type: schema.TypeString,
Required: true,
},
"weight": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(0, 100),
},
"type": {
Type: schema.TypeString,
Optional: true,
Default: string(ECS),
ValidateFunc: validation.StringInSlice([]string{"eni", "ecs"}, false),
},
"server_ip": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"delete_protection_validation": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func resourceAliyunSlbBackendServersCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := slb.CreateAddBackendServersRequest()
request.RegionId = client.RegionId
request.LoadBalancerId = d.Get("load_balancer_id").(string)
if v, ok := d.GetOk("backend_servers"); ok {
request.BackendServers = expandBackendServersInfoToString(v.(*schema.Set).List())
}
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.AddBackendServers(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_slb_backend_servers", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*slb.AddBackendServersResponse)
d.SetId(response.LoadBalancerId)
return resourceAliyunSlbBackendServersRead(d, meta)
}
func resourceAliyunSlbBackendServersRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
resource_id := d.Id()
object, err := slbService.DescribeSlb(resource_id)
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("load_balancer_id", object.LoadBalancerId)
servers := make([]map[string]interface{}, 0)
for _, server := range object.BackendServers.BackendServer {
s := map[string]interface{}{
"server_id": server.ServerId,
"weight": server.Weight,
"type": server.Type,
"server_ip": server.ServerIp,
}
servers = append(servers, s)
}
if err := d.Set("backend_servers", servers); err != nil {
return WrapError(err)
}
return nil
}
func resourceAliyunSlbBackendServersUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
d.Partial(true)
step := 20
var removeSet, addSet, updateSet *schema.Set
if d.HasChange("backend_servers") {
o, n := d.GetChange("backend_servers")
os := o.(*schema.Set)
ns := n.(*schema.Set)
remove := os.Difference(ns).List()
add := ns.Difference(os).List()
oldIds := getIdSetFromServers(remove)
newIds := getIdSetFromServers(add)
updateSet = oldIds.Intersection(newIds)
addSet = newIds.Difference(oldIds)
removeSet = oldIds.Difference(newIds)
if removeSet.Len() > 0 {
rmservers := make([]interface{}, 0)
for _, rmserver := range remove {
rms := rmserver.(map[string]interface{})
if removeSet.Contains(rms["server_id"]) {
rmsm := map[string]interface{}{
"server_id": rms["server_id"],
"weight": rms["weight"],
"type": rms["type"],
}
rmservers = append(rmservers, rmsm)
}
}
request := slb.CreateRemoveBackendServersRequest()
request.RegionId = client.RegionId
request.LoadBalancerId = d.Id()
segs := len(rmservers)/step + 1
for i := 0; i < segs; i++ {
start := i * step
end := (i + 1) * step
if end >= len(rmservers) {
end = len(rmservers)
}
request.BackendServers = expandBackendServersInfoToString(rmservers[start:end])
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.RemoveBackendServers(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("backend_servers")
}
}
if addSet.Len() > 0 {
addservers := make([]interface{}, 0)
for _, addserver := range add {
adds := addserver.(map[string]interface{})
if addSet.Contains(adds["server_id"]) {
addsm := map[string]interface{}{
"server_id": adds["server_id"],
"weight": adds["weight"],
"type": adds["type"],
}
addservers = append(addservers, addsm)
}
}
request := slb.CreateAddBackendServersRequest()
request.RegionId = client.RegionId
request.LoadBalancerId = d.Id()
segs := len(addservers)/step + 1
for i := 0; i < segs; i++ {
start := i * step
end := (i + 1) * step
if end >= len(addservers) {
end = len(addservers)
}
request.BackendServers = expandBackendServersInfoToString(addservers[start:end])
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.AddBackendServers(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("backend_servers")
}
}
servers := make([]interface{}, 0)
for _, server := range d.Get("backend_servers").(*schema.Set).List() {
s := server.(map[string]interface{})
if updateSet.Contains(s["server_id"]) {
sm := map[string]interface{}{
"server_id": s["server_id"],
"weight": s["weight"],
"type": s["type"],
}
servers = append(servers, sm)
}
}
if len(servers) > 0 {
segs := len(servers)/step + 1
for i := 0; i < segs; i++ {
start := i * step
end := (i + 1) * step
if end >= len(servers) {
end = len(servers)
}
request := slb.CreateSetBackendServersRequest()
request.RegionId = client.RegionId
request.LoadBalancerId = d.Id()
request.BackendServers = expandBackendServersInfoToString(servers[start:end])
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.SetBackendServers(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("backend_servers")
}
}
}
d.Partial(false)
return resourceAliyunSlbBackendServersRead(d, meta)
}
func resourceAliyunSlbBackendServersDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
instanceSet := d.Get("backend_servers").(*schema.Set)
step := 20
if len(instanceSet.List()) > 0 {
slbService := SlbService{client}
if d.Get("delete_protection_validation").(bool) {
lbInstance, err := slbService.DescribeSlb(d.Id())
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
if lbInstance.DeleteProtection == "on" {
return WrapError(fmt.Errorf("Current backend servers' SLB Instance %s has enabled DeleteProtection. Please set delete_protection_validation to false to delete the resource.", d.Id()))
}
}
servers := make([]interface{}, 0)
for _, rmserver := range instanceSet.List() {
rms := rmserver.(map[string]interface{})
rmsm := map[string]interface{}{
"server_id": rms["server_id"],
"weight": rms["weight"],
"type": rms["type"],
}
servers = append(servers, rmsm)
}
request := slb.CreateRemoveBackendServersRequest()
request.RegionId = client.RegionId
request.LoadBalancerId = d.Id()
segs := len(servers)/step + 1
for i := 0; i < segs; i++ {
start := i * step
end := (i + 1) * step
if end >= len(servers) {
end = len(servers)
}
request.BackendServers = expandBackendServersWithTypeToString(servers[start:end])
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.RemoveBackendServers(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"RspoolVipExist", "ObtainIpFail"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudSlbCaCertificate() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSlbCaCertificateCreate,
Read: resourceAlicloudSlbCaCertificateRead,
Update: resourceAlicloudSlbCaCertificateUpdate,
Delete: resourceAlicloudSlbCaCertificateDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Delete: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"ca_certificate": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ca_certificate_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"name"},
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Field 'name' has been deprecated from provider version 1.123.1. New field 'ca_certificate_name' instead",
ConflictsWith: []string{"ca_certificate_name"},
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"tags": tagsSchema(),
},
}
}
func resourceAlicloudSlbCaCertificateCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "UploadCACertificate"
request := make(map[string]interface{})
conn, err := client.NewSlbClient()
if err != nil {
return WrapError(err)
}
request["CACertificate"] = d.Get("ca_certificate")
if v, ok := d.GetOk("ca_certificate_name"); ok {
request["CACertificateName"] = v
} else if v, ok := d.GetOk("name"); ok {
request["CACertificateName"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_slb_ca_certificate", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["CACertificateId"]))
return resourceAlicloudSlbCaCertificateUpdate(d, meta)
}
func resourceAlicloudSlbCaCertificateRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
object, err := slbService.DescribeSlbCaCertificate(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_slb_ca_certificate slbService.DescribeSlbCaCertificate Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("ca_certificate_name", object["CACertificateName"])
d.Set("name", object["CACertificateName"])
d.Set("resource_group_id", object["ResourceGroupId"])
if v, ok := object["Tags"].(map[string]interface{}); ok {
d.Set("tags", tagsToMap(v["Tag"]))
}
return nil
}
func resourceAlicloudSlbCaCertificateUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
conn, err := client.NewSlbClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
d.Partial(true)
if d.HasChange("tags") {
if err := slbService.SetResourceTags(d, "certificate"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
update := false
request := map[string]interface{}{
"CACertificateId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("ca_certificate_name") {
update = true
request["CACertificateName"] = d.Get("ca_certificate_name")
} else if !d.IsNewResource() && d.HasChange("name") {
update = true
request["CACertificateName"] = d.Get("name")
}
request["RegionId"] = client.RegionId
if update {
action := "SetCACertificateName"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("name")
d.SetPartial("ca_certificate_name")
}
d.Partial(false)
return resourceAlicloudSlbCaCertificateRead(d, meta)
}
func resourceAlicloudSlbCaCertificateDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteCACertificate"
var response map[string]interface{}
conn, err := client.NewSlbClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"CACertificateId": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"BackendServer.configuring", "OperationBusy", "ServiceIsConfiguring", "ServiceIsStopping", "SystemBusy"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"CACertificateId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/slb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudSlbDomainExtension() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunSlbDomainExtensionCreate,
Read: resourceAliyunSlbDomainExtensionRead,
Update: resourceAliyunSlbDomainExtensionUpdate,
Delete: resourceAliyunSlbDomainExtensionDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"load_balancer_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"frontend_port": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(1, 65535),
Required: true,
ForceNew: true,
},
"domain": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"server_certificate_id": {
Type: schema.TypeString,
Required: true,
},
"delete_protection_validation": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func resourceAliyunSlbDomainExtensionCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := slb.CreateCreateDomainExtensionRequest()
request.LoadBalancerId = d.Get("load_balancer_id").(string)
request.ListenerPort = requests.NewInteger(d.Get("frontend_port").(int))
request.Domain = d.Get("domain").(string)
request.ServerCertificateId = d.Get("server_certificate_id").(string)
var response *slb.CreateDomainExtensionResponse
err := resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.CreateDomainExtension(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"DomainExtensionProcessing"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response = raw.(*slb.CreateDomainExtensionResponse)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_slb_domain_extension", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetId(response.DomainExtensionId)
return resourceAliyunSlbDomainExtensionRead(d, meta)
}
func resourceAliyunSlbDomainExtensionRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
domainExtension, err := slbService.DescribeDomainExtensionAttribute(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("id", domainExtension.DomainExtensionId)
d.Set("load_balancer_id", domainExtension.LoadBalancerId)
d.Set("domain", domainExtension.Domain)
d.Set("server_certificate_id", domainExtension.ServerCertificateId)
d.Set("frontend_port", domainExtension.ListenerPort)
return nil
}
func resourceAliyunSlbDomainExtensionUpdate(d *schema.ResourceData, meta interface{}) error {
if d.HasChange("server_certificate_id") {
request := slb.CreateSetDomainExtensionAttributeRequest()
request.DomainExtensionId = d.Id()
request.ServerCertificateId = d.Get("server_certificate_id").(string)
client := meta.(*connectivity.AliyunClient)
err := resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.SetDomainExtensionAttribute(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"BackendServer.configuring", "DomainExtensionProcessing"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_slb_domain_extension", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("server_certificate_id")
}
return resourceAliyunSlbDomainExtensionRead(d, meta)
}
func resourceAliyunSlbDomainExtensionDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
if d.Get("delete_protection_validation").(bool) {
lbId := d.Get("load_balancer_id").(string)
lbInstance, err := slbService.DescribeSlb(lbId)
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
if lbInstance.DeleteProtection == "on" {
return WrapError(fmt.Errorf("Current domain extension's SLB Instance %s has enabled DeleteProtection. Please set delete_protection_validation to false to delete the resource.", lbId))
}
}
request := slb.CreateDeleteDomainExtensionRequest()
request.DomainExtensionId = d.Id()
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DeleteDomainExtension(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"DomainExtensionProcessing", "InternalError"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidParameter.DomainExtensionId"}) {
return nil
}
return WrapErrorf(err, DataDefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(slbService.WaitForSlbDomainExtension(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"fmt"
"regexp"
"strconv"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/slb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliyunSlbListener() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunSlbListenerCreate,
Read: resourceAliyunSlbListenerRead,
Update: resourceAliyunSlbListenerUpdate,
Delete: resourceAliyunSlbListenerDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"load_balancer_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"frontend_port": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(1, 65535),
Required: true,
ForceNew: true,
},
"lb_port": {
Type: schema.TypeInt,
Optional: true,
Deprecated: "Field 'lb_port' has been deprecated, and using 'frontend_port' to replace.",
},
"backend_port": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(1, 65535),
Optional: true,
ForceNew: true,
},
"instance_port": {
Type: schema.TypeInt,
Optional: true,
Deprecated: "Field 'instance_port' has been deprecated, and using 'backend_port' to replace.",
},
"lb_protocol": {
Type: schema.TypeString,
Optional: true,
Deprecated: "Field 'lb_protocol' has been deprecated, and using 'protocol' to replace.",
},
"protocol": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"http", "https", "tcp", "udp"}, false),
Required: true,
ForceNew: true,
},
"bandwidth": {
Type: schema.TypeInt,
ValidateFunc: validation.Any(
validation.IntBetween(1, 1000),
validation.IntInSlice([]int{-1})),
Optional: true,
},
"scheduler": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"wrr", "wlc", "rr", "sch", "tch", "qch"}, false),
Optional: true,
Default: WRRScheduler,
},
"server_group_id": {
Type: schema.TypeString,
Optional: true,
},
"master_slave_server_group_id": {
Type: schema.TypeString,
Optional: true,
},
"acl_status": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"on", "off"}, false),
Optional: true,
Default: OffFlag,
},
"acl_type": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"black", "white"}, false),
Optional: true,
DiffSuppressFunc: slbAclDiffSuppressFunc,
},
"acl_id": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: slbAclDiffSuppressFunc,
},
//http & https
"sticky_session": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"on", "off"}, false),
Optional: true,
Default: OffFlag,
DiffSuppressFunc: httpHttpsDiffSuppressFunc,
},
//http & https
"sticky_session_type": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{
string(InsertStickySessionType),
string(ServerStickySessionType)}, false),
Optional: true,
DiffSuppressFunc: stickySessionTypeDiffSuppressFunc,
},
//http & https
"cookie_timeout": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(1, 86400),
Optional: true,
DiffSuppressFunc: cookieTimeoutDiffSuppressFunc,
},
//http & https
"cookie": {
Type: schema.TypeString,
ValidateFunc: validation.StringLenBetween(1, 200),
Optional: true,
DiffSuppressFunc: cookieDiffSuppressFunc,
},
//tcp & udp
"persistence_timeout": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(1, 3600),
Optional: true,
Default: 0,
DiffSuppressFunc: tcpUdpDiffSuppressFunc,
},
//http & https
"health_check": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"on", "off"}, false),
Optional: true,
Default: OnFlag,
DiffSuppressFunc: httpHttpsDiffSuppressFunc,
},
//http & https
"health_check_method": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"head", "get"}, false),
Optional: true,
Computed: true,
},
//tcp
"health_check_type": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{
string(TCPHealthCheckType),
string(HTTPHealthCheckType)}, false),
Optional: true,
Default: TCPHealthCheckType,
DiffSuppressFunc: healthCheckTypeDiffSuppressFunc,
},
//http & https & tcp
"health_check_domain": {
Type: schema.TypeString,
ValidateFunc: validation.StringDoesNotMatch(regexp.MustCompile(`^\$_ip$`), "value '$_ip' has been deprecated, and empty string will replace it"),
Optional: true,
DiffSuppressFunc: httpHttpsTcpDiffSuppressFunc,
},
//http & https & tcp
"health_check_uri": {
Type: schema.TypeString,
ValidateFunc: validation.StringLenBetween(1, 80),
Optional: true,
Default: "/",
DiffSuppressFunc: httpHttpsTcpDiffSuppressFunc,
},
"health_check_connect_port": {
Type: schema.TypeInt,
ValidateFunc: validation.Any(
validation.IntBetween(1, 65535),
validation.IntInSlice([]int{-520})),
Optional: true,
Computed: true,
DiffSuppressFunc: healthCheckDiffSuppressFunc,
},
"healthy_threshold": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(1, 10),
Optional: true,
Default: 3,
DiffSuppressFunc: healthCheckDiffSuppressFunc,
},
"unhealthy_threshold": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(1, 10),
Optional: true,
Default: 3,
DiffSuppressFunc: healthCheckDiffSuppressFunc,
},
"health_check_timeout": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(1, 300),
Optional: true,
Default: 5,
DiffSuppressFunc: healthCheckDiffSuppressFunc,
},
"health_check_interval": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(1, 50),
Optional: true,
Default: 2,
DiffSuppressFunc: healthCheckDiffSuppressFunc,
},
//http & https & tcp
"health_check_http_code": {
Type: schema.TypeString,
ValidateFunc: validateAllowedSplitStringValue([]string{
string(HTTP_2XX), string(HTTP_3XX), string(HTTP_4XX), string(HTTP_5XX)}, ","),
Optional: true,
Computed: true,
DiffSuppressFunc: httpHttpsTcpDiffSuppressFunc,
},
//https
"ssl_certificate_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
DiffSuppressFunc: sslCertificateIdDiffSuppressFunc,
Deprecated: "Field 'ssl_certificate_id' has been deprecated from 1.59.0 and using 'server_certificate_id' instead.",
},
"server_certificate_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
DiffSuppressFunc: sslCertificateIdDiffSuppressFunc,
},
"ca_certificate_id": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: sslCertificateIdDiffSuppressFunc,
},
//http, https
"gzip": {
Type: schema.TypeBool,
Optional: true,
Default: true,
DiffSuppressFunc: httpHttpsDiffSuppressFunc,
},
"x_forwarded_for": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
// At present, retrive client ip can not be modified, and it default to true.
"retrive_client_ip": {
Type: schema.TypeBool,
Computed: true,
},
"retrive_slb_ip": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"retrive_slb_id": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"retrive_slb_proto": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
},
MaxItems: 1,
},
//tcp
"established_timeout": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(10, 900),
Optional: true,
Default: 900,
DiffSuppressFunc: establishedTimeoutDiffSuppressFunc,
},
//http & https
"idle_timeout": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(1, 60),
Optional: true,
Default: 15,
DiffSuppressFunc: httpHttpsDiffSuppressFunc,
},
//http & https
"request_timeout": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(1, 180),
Optional: true,
Default: 60,
DiffSuppressFunc: httpHttpsDiffSuppressFunc,
},
//https
"enable_http2": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"on", "off"}, false),
Optional: true,
Default: OnFlag,
DiffSuppressFunc: httpsDiffSuppressFunc,
},
//https
"tls_cipher_policy": {
Type: schema.TypeString,
Default: "tls_cipher_policy_1_0",
ValidateFunc: validation.StringInSlice([]string{"tls_cipher_policy_1_0", "tls_cipher_policy_1_1", "tls_cipher_policy_1_2", "tls_cipher_policy_1_2_strict"}, false),
Optional: true,
DiffSuppressFunc: httpsDiffSuppressFunc,
},
"forward_port": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(1, 65535),
Optional: true,
ForceNew: true,
DiffSuppressFunc: forwardPortDiffSuppressFunc,
},
"listener_forward": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"on", "off"}, false),
Optional: true,
ForceNew: true,
Computed: true,
DiffSuppressFunc: httpDiffSuppressFunc,
},
"delete_protection_validation": {
Type: schema.TypeBool,
Optional: true,
},
},
}
}
func resourceAliyunSlbListenerCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
httpForward := false
protocol := d.Get("protocol").(string)
lbId := d.Get("load_balancer_id").(string)
frontend := d.Get("frontend_port").(int)
if listenerForward, ok := d.GetOk("listener_forward"); ok && listenerForward.(string) == string(OnFlag) {
httpForward = true
}
request, err := buildListenerCommonArgs(d, meta)
if err != nil {
return WrapError(err)
}
request.ApiName = fmt.Sprintf("CreateLoadBalancer%sListener", strings.ToUpper(protocol))
if Protocol(protocol) == Http || Protocol(protocol) == Https {
if httpForward {
reqHttp, err := buildHttpForwardArgs(d, request)
if err != nil {
return WrapError(err)
}
request = reqHttp
} else {
reqHttp, err := buildHttpListenerArgs(d, request)
if err != nil {
return WrapError(err)
}
request = reqHttp
}
if Protocol(protocol) == Https {
scId := d.Get("server_certificate_id").(string)
if scId == "" {
scId = d.Get("ssl_certificate_id").(string)
}
if scId == "" {
return WrapError(Error(`'server_certificate_id': required field is not set when the protocol is 'https'.`))
}
request.QueryParams["ServerCertificateId"] = scId
if caId, ok := d.GetOk("ca_certificate_id"); ok && caId.(string) != "" {
request.QueryParams["CACertificateId"] = caId.(string)
}
}
}
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.ProcessCommonRequest(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_slb_listener", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request, request.QueryParams)
d.SetId(lbId + ":" + protocol + ":" + strconv.Itoa(frontend))
if err := slbService.WaitForSlbListener(d.Id(), Stopped, DefaultTimeout); err != nil {
return WrapError(err)
}
startLoadBalancerListenerRequest := slb.CreateStartLoadBalancerListenerRequest()
startLoadBalancerListenerRequest.RegionId = client.RegionId
startLoadBalancerListenerRequest.LoadBalancerId = lbId
startLoadBalancerListenerRequest.ListenerPort = requests.NewInteger(frontend)
startLoadBalancerListenerRequest.ListenerProtocol = protocol
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.StartLoadBalancerListener(startLoadBalancerListenerRequest)
})
if err != nil {
if IsExpectedErrors(err, []string{"ServiceIsConfiguring"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(startLoadBalancerListenerRequest.GetActionName(), raw, startLoadBalancerListenerRequest.RpcRequest, startLoadBalancerListenerRequest)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_slb_listener", startLoadBalancerListenerRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
if err = slbService.WaitForSlbListener(d.Id(), Running, DefaultTimeout); err != nil {
return WrapError(err)
}
if httpForward {
return resourceAliyunSlbListenerRead(d, meta)
}
return resourceAliyunSlbListenerUpdate(d, meta)
}
func resourceAliyunSlbListenerRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
lb_id, protocol, port, err := parseListenerId(d, meta)
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("protocol", protocol)
d.Set("load_balancer_id", lb_id)
d.Set("frontend_port", port)
d.SetId(lb_id + ":" + protocol + ":" + strconv.Itoa(port))
return resource.Retry(5*time.Minute, func() *resource.RetryError {
object, err := slbService.DescribeSlbListener(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
if IsExpectedErrors(err, SlbIsBusy) {
return resource.RetryableError(WrapError(err))
}
return resource.NonRetryableError(WrapError(err))
}
if port, ok := object["ListenerPort"]; ok && port.(float64) > 0 {
readListener(d, object)
} else {
d.SetId("")
}
return nil
})
}
func resourceAliyunSlbListenerUpdate(d *schema.ResourceData, meta interface{}) error {
proto := d.Get("protocol").(string)
lb_id := d.Get("load_balancer_id").(string)
frontend := d.Get("frontend_port").(int)
d.SetId(lb_id + ":" + proto + ":" + strconv.Itoa(frontend))
client := meta.(*connectivity.AliyunClient)
protocol := Protocol(d.Get("protocol").(string))
commonRequest, err := buildListenerCommonArgs(d, meta)
if err != nil {
return WrapError(err)
}
commonRequest.ApiName = fmt.Sprintf("SetLoadBalancer%sListenerAttribute", strings.ToUpper(string(protocol)))
update := false
if d.HasChange("description") {
update = true
}
if d.HasChange("scheduler") {
commonRequest.QueryParams["Scheduler"] = d.Get("scheduler").(string)
update = true
}
if d.HasChange("server_group_id") {
serverGroupId := d.Get("server_group_id").(string)
if serverGroupId != "" {
commonRequest.QueryParams["VServerGroup"] = string(OnFlag)
commonRequest.QueryParams["VServerGroupId"] = d.Get("server_group_id").(string)
} else {
commonRequest.QueryParams["VServerGroup"] = string(OffFlag)
}
update = true
}
if d.HasChange("master_slave_server_group_id") {
serverGroupId := d.Get("master_slave_server_group_id").(string)
if serverGroupId != "" {
commonRequest.QueryParams["MasterSlaveServerGroup"] = string(OnFlag)
commonRequest.QueryParams["MasterSlaveServerGroupId"] = d.Get("master_slave_server_group_id").(string)
} else {
commonRequest.QueryParams["MasterSlaveServerGroup"] = string(OffFlag)
}
update = true
}
if d.HasChange("bandwidth") {
commonRequest.QueryParams["Bandwidth"] = strconv.Itoa(d.Get("bandwidth").(int))
update = true
}
if d.HasChange("acl_status") {
commonRequest.QueryParams["AclStatus"] = d.Get("acl_status").(string)
update = true
}
if d.HasChange("acl_type") {
commonRequest.QueryParams["AclType"] = d.Get("acl_type").(string)
update = true
}
if d.HasChange("acl_id") {
commonRequest.QueryParams["AclId"] = d.Get("acl_id").(string)
update = true
}
httpArgs, err := buildHttpListenerArgs(d, commonRequest)
if (protocol == Https || protocol == Http) && err != nil {
return WrapError(err)
}
// http https
if d.HasChange("sticky_session") {
update = true
}
if d.HasChange("sticky_session_type") {
update = true
}
if d.HasChange("cookie_timeout") {
update = true
}
if d.HasChange("cookie") {
update = true
}
if d.HasChange("health_check") {
update = true
}
d.SetPartial("gzip")
if d.Get("gzip").(bool) {
httpArgs.QueryParams["Gzip"] = string(OnFlag)
} else {
httpArgs.QueryParams["Gzip"] = string(OffFlag)
}
d.SetPartial("x_forwarded_for")
if len(d.Get("x_forwarded_for").([]interface{})) > 0 && (d.Get("protocol").(string) == "http" || d.Get("protocol").(string) == "https") {
xff := d.Get("x_forwarded_for").([]interface{})[0].(map[string]interface{})
if xff["retrive_slb_ip"].(bool) {
httpArgs.QueryParams["XForwardedFor_SLBIP"] = string(OnFlag)
} else {
httpArgs.QueryParams["XForwardedFor_SLBIP"] = string(OffFlag)
}
if xff["retrive_slb_id"].(bool) {
httpArgs.QueryParams["XForwardedFor_SLBID"] = string(OnFlag)
} else {
httpArgs.QueryParams["XForwardedFor_SLBID"] = string(OffFlag)
}
if xff["retrive_slb_proto"].(bool) {
httpArgs.QueryParams["XForwardedFor_proto"] = string(OnFlag)
} else {
httpArgs.QueryParams["XForwardedFor_proto"] = string(OffFlag)
}
}
if d.HasChange("gzip") || d.HasChange("x_forwarded_for") {
update = true
}
// http https
if d.HasChange("idle_timeout") {
update = true
}
// http https
if d.HasChange("request_timeout") {
update = true
}
// http https
if d.HasChange("health_check_method") {
update = true
}
// http https tcp udp and health_check=on
if d.HasChange("unhealthy_threshold") {
commonRequest.QueryParams["UnhealthyThreshold"] = string(requests.NewInteger(d.Get("unhealthy_threshold").(int)))
update = true
}
if d.HasChange("healthy_threshold") {
commonRequest.QueryParams["HealthyThreshold"] = string(requests.NewInteger(d.Get("healthy_threshold").(int)))
update = true
}
if d.HasChange("health_check_timeout") {
commonRequest.QueryParams["HealthCheckConnectTimeout"] = string(requests.NewInteger(d.Get("health_check_timeout").(int)))
update = true
}
if d.HasChange("health_check_interval") {
commonRequest.QueryParams["HealthCheckInterval"] = string(requests.NewInteger(d.Get("health_check_interval").(int)))
update = true
}
if d.HasChange("health_check_connect_port") {
if port, ok := d.GetOk("health_check_connect_port"); ok {
httpArgs.QueryParams["HealthCheckConnectPort"] = string(requests.NewInteger(port.(int)))
commonRequest.QueryParams["HealthCheckConnectPort"] = string(requests.NewInteger(port.(int)))
update = true
}
}
// tcp and udp
if d.HasChange("persistence_timeout") {
commonRequest.QueryParams["PersistenceTimeout"] = string(requests.NewInteger(d.Get("persistence_timeout").(int)))
update = true
}
tcpArgs := commonRequest
udpArgs := commonRequest
// http https tcp
if d.HasChange("health_check_domain") {
update = true
}
// todo: depends on Api fixing the default value
if domain, ok := d.GetOk("health_check_domain"); ok {
httpArgs.QueryParams["HealthCheckDomain"] = domain.(string)
tcpArgs.QueryParams["HealthCheckDomain"] = domain.(string)
}
if d.HasChange("health_check_uri") {
tcpArgs.QueryParams["HealthCheckURI"] = d.Get("health_check_uri").(string)
update = true
}
if d.HasChange("health_check_http_code") {
tcpArgs.QueryParams["HealthCheckHttpCode"] = getHealthCheckHttpCodeValue(d)
update = true
}
// tcp
if d.HasChange("health_check_type") {
tcpArgs.QueryParams["HealthCheckType"] = d.Get("health_check_type").(string)
update = true
}
// tcp
if d.HasChange("established_timeout") {
tcpArgs.QueryParams["EstablishedTimeout"] = string(requests.NewInteger(d.Get("established_timeout").(int)))
update = true
}
// https
httpsArgs := httpArgs
if protocol == Https {
scId := d.Get("server_certificate_id").(string)
if scId == "" {
scId = d.Get("ssl_certificate_id").(string)
}
if scId == "" {
return WrapError(Error("'server_certificate_id': required field is not set when the protocol is 'https'."))
}
httpsArgs.QueryParams["ServerCertificateId"] = scId
if d.HasChange("ssl_certificate_id") || d.HasChange("server_certificate_id") {
update = true
}
if d.HasChange("enable_http2") {
httpsArgs.QueryParams["EnableHttp2"] = d.Get("enable_http2").(string)
update = true
}
if d.HasChange("tls_cipher_policy") {
// spec changes check, can not be updated when load balancer instance is "Shared-Performance".
slbService := SlbService{client}
object, err := slbService.DescribeSlb(d.Get("load_balancer_id").(string))
if err != nil {
return WrapError(err)
}
spec := object.LoadBalancerSpec
if spec == "" {
if !d.IsNewResource() || string("tls_cipher_policy_1_0") != d.Get("tls_cipher_policy").(string) {
return WrapError(Error("Currently the param \"tls_cipher_policy\" can not be updated when load balancer instance is \"Shared-Performance\"."))
}
} else {
httpsArgs.QueryParams["TLSCipherPolicy"] = d.Get("tls_cipher_policy").(string)
update = true
}
}
if d.HasChange("ca_certificate_id") {
httpsArgs.QueryParams["CACertificateId"] = d.Get("ca_certificate_id").(string)
update = true
}
}
if update {
var request *requests.CommonRequest
switch protocol {
case Https:
request = httpsArgs
case Tcp:
request = tcpArgs
case Udp:
request = udpArgs
default:
request = httpArgs
}
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.ProcessCommonRequest(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request, request.QueryParams)
}
d.Partial(false)
return resourceAliyunSlbListenerRead(d, meta)
}
func resourceAliyunSlbListenerDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
lbId, protocol, port, err := parseListenerId(d, meta)
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
if v, ok := d.GetOkExists("delete_protection_validation"); ok && v.(bool) {
lbInstance, err := slbService.DescribeSlb(lbId)
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
if lbInstance.DeleteProtection == "on" {
return WrapError(fmt.Errorf("Current listener's SLB Instance %s has enabled DeleteProtection. Please set delete_protection_validation to false to delete the listener resource.", lbId))
}
}
request := slb.CreateDeleteLoadBalancerListenerRequest()
request.RegionId = client.RegionId
request.LoadBalancerId = lbId
request.ListenerPort = requests.NewInteger(port)
request.ListenerProtocol = protocol
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DeleteLoadBalancerListener(request)
})
if err != nil {
if IsExpectedErrors(err, SlbIsBusy) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(slbService.WaitForSlbListener(d.Id(), Deleted, DefaultTimeoutMedium))
}
func buildListenerCommonArgs(d *schema.ResourceData, meta interface{}) (*requests.CommonRequest, error) {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
request, err := slbService.BuildSlbCommonRequest()
if err != nil {
return request, WrapError(err)
}
request.RegionId = client.RegionId
request.QueryParams["LoadBalancerId"] = d.Get("load_balancer_id").(string)
request.QueryParams["ListenerPort"] = string(requests.NewInteger(d.Get("frontend_port").(int)))
if backendServerPort, ok := d.GetOk("backend_port"); ok {
request.QueryParams["BackendServerPort"] = string(requests.NewInteger(backendServerPort.(int)))
}
if bandWidth, ok := d.GetOk("bandwidth"); ok {
request.QueryParams["Bandwidth"] = string(requests.NewInteger(bandWidth.(int)))
}
if groupId, ok := d.GetOk("server_group_id"); ok && groupId.(string) != "" {
request.QueryParams["VServerGroupId"] = groupId.(string)
}
if groupId, ok := d.GetOk("master_slave_server_group_id"); ok && groupId.(string) != "" {
request.QueryParams["MasterSlaveServerGroupId"] = groupId.(string)
}
// acl status
if aclStatus, ok := d.GetOk("acl_status"); ok && aclStatus.(string) != "" {
request.QueryParams["AclStatus"] = aclStatus.(string)
}
// acl type
if aclType, ok := d.GetOk("acl_type"); ok && aclType.(string) != "" {
request.QueryParams["AclType"] = aclType.(string)
}
// acl id
if aclId, ok := d.GetOk("acl_id"); ok && aclId.(string) != "" {
request.QueryParams["AclId"] = aclId.(string)
}
// description
if description, ok := d.GetOk("description"); ok && description.(string) != "" {
request.QueryParams["Description"] = description.(string)
}
// scheduler
if scheduler, ok := d.GetOk("scheduler"); ok && scheduler.(string) != "" {
request.QueryParams["Scheduler"] = scheduler.(string)
}
return request, nil
}
func buildHttpListenerArgs(d *schema.ResourceData, req *requests.CommonRequest) (*requests.CommonRequest, error) {
stickySession := d.Get("sticky_session").(string)
healthCheck := d.Get("health_check").(string)
req.QueryParams["StickySession"] = stickySession
req.QueryParams["HealthCheck"] = healthCheck
req.QueryParams["RequestTimeout"] = string(requests.NewInteger(d.Get("request_timeout").(int)))
req.QueryParams["IdleTimeout"] = string(requests.NewInteger(d.Get("idle_timeout").(int)))
if stickySession == string(OnFlag) {
sessionType, ok := d.GetOk("sticky_session_type")
if !ok || sessionType.(string) == "" {
return req, WrapError(Error("'sticky_session_type': required field is not set when the StickySession is %s.", OnFlag))
} else {
req.QueryParams["StickySessionType"] = sessionType.(string)
}
if sessionType.(string) == string(InsertStickySessionType) {
if timeout, ok := d.GetOk("cookie_timeout"); !ok || timeout == 0 {
return req, WrapError(Error("'cookie_timeout': required field is not set when the StickySession is %s and StickySessionType is %s.",
OnFlag, InsertStickySessionType))
} else {
req.QueryParams["CookieTimeout"] = string(requests.NewInteger(timeout.(int)))
}
} else {
if cookie, ok := d.GetOk("cookie"); !ok || cookie.(string) == "" {
return req, WrapError(fmt.Errorf("'cookie': required field is not set when the StickySession is %s and StickySessionType is %s.",
OnFlag, ServerStickySessionType))
} else {
req.QueryParams["Cookie"] = cookie.(string)
}
}
}
if healthCheck == string(OnFlag) {
req.QueryParams["HealthCheckURI"] = d.Get("health_check_uri").(string)
if port, ok := d.GetOk("health_check_connect_port"); ok {
req.QueryParams["HealthCheckConnectPort"] = string(requests.NewInteger(port.(int)))
}
req.QueryParams["HealthyThreshold"] = string(requests.NewInteger(d.Get("healthy_threshold").(int)))
req.QueryParams["UnhealthyThreshold"] = string(requests.NewInteger(d.Get("unhealthy_threshold").(int)))
req.QueryParams["HealthCheckTimeout"] = string(requests.NewInteger(d.Get("health_check_timeout").(int)))
req.QueryParams["HealthCheckInterval"] = string(requests.NewInteger(d.Get("health_check_interval").(int)))
req.QueryParams["HealthCheckHttpCode"] = getHealthCheckHttpCodeValue(d)
if d.Get("protocol").(string) == "http" || d.Get("protocol").(string) == "https" {
if healthCheckMethod, ok := d.GetOk("health_check_method"); ok && healthCheckMethod.(string) != "" {
req.QueryParams["HealthCheckMethod"] = healthCheckMethod.(string)
}
}
}
return req, nil
}
func buildHttpForwardArgs(d *schema.ResourceData, req *requests.CommonRequest) (*requests.CommonRequest, error) {
stickySession := string(OffFlag)
healthCheck := string(OffFlag)
listenerForward := string(OnFlag)
req.QueryParams["StickySession"] = stickySession
req.QueryParams["HealthCheck"] = healthCheck
req.QueryParams["ListenerForward"] = listenerForward
/**
if the user do not fill backend_port, give 80 to pass the SDK parameter check.
*/
if backEndServerPort, ok := d.GetOk("backend_port"); ok {
req.QueryParams[""] = string(requests.NewInteger(backEndServerPort.(int)))
} else {
req.QueryParams["BackendServerPort"] = string("80")
}
if forwardPort, ok := d.GetOk("forward_port"); ok {
req.QueryParams["ForwardPort"] = string(requests.NewInteger(forwardPort.(int)))
}
return req, nil
}
func parseListenerId(d *schema.ResourceData, meta interface{}) (string, string, int, error) {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
parts, err := ParseSlbListenerId(d.Id())
if err != nil {
return "", "", 0, WrapError(err)
}
protocol := ""
port := 0
if len(parts) == 3 {
protocol = parts[1]
port, err = strconv.Atoi(parts[2])
} else {
if v, ok := d.GetOk("protocol"); ok && v.(string) != "" {
protocol = v.(string)
}
port, err = strconv.Atoi(parts[1])
}
if err != nil {
return "", "", 0, WrapError(err)
}
loadBalancer, err := slbService.DescribeSlb(parts[0])
if err != nil {
return "", "", 0, WrapError(err)
}
if protocol != "" {
for _, portAndProtocol := range loadBalancer.ListenerPortsAndProtocol.ListenerPortAndProtocol {
if portAndProtocol.ListenerPort == port && portAndProtocol.ListenerProtocol == protocol {
return loadBalancer.LoadBalancerId, portAndProtocol.ListenerProtocol, port, nil
}
}
} else {
if len(loadBalancer.ListenerPortsAndProtocol.ListenerPortAndProtocol) > 1 {
return "", "", 0, WrapError(Error("More than one listener was with with the same id: %s, please specify protocol.", d.Id()))
}
for _, portAndProtocol := range loadBalancer.ListenerPortsAndProtocol.ListenerPortAndProtocol {
if portAndProtocol.ListenerPort == port {
return loadBalancer.LoadBalancerId, portAndProtocol.ListenerProtocol, port, nil
}
}
}
return "", "", 0, GetNotFoundErrorFromString(GetNotFoundMessage("Listener", d.Id()))
}
func readListener(d *schema.ResourceData, listener map[string]interface{}) {
if val, ok := listener["BackendServerPort"]; ok {
d.Set("backend_port", val.(float64))
}
if val, ok := listener["ListenerPort"]; ok {
d.Set("frontend_port", val.(float64))
}
if val, ok := listener["Bandwidth"]; ok {
d.Set("bandwidth", val.(float64))
}
if val, ok := listener["Scheduler"]; ok {
d.Set("scheduler", val.(string))
}
if val, ok := listener["VServerGroupId"]; ok {
d.Set("server_group_id", val.(string))
}
if val, ok := listener["MasterSlaveServerGroupId"]; ok {
d.Set("master_slave_server_group_id", val.(string))
}
if val, ok := listener["AclStatus"]; ok {
d.Set("acl_status", val.(string))
}
if val, ok := listener["AclType"]; ok {
d.Set("acl_type", val.(string))
}
if val, ok := listener["AclId"]; ok {
d.Set("acl_id", val.(string))
}
if val, ok := listener["HealthCheck"]; ok {
d.Set("health_check", val.(string))
}
if val, ok := listener["StickySession"]; ok {
d.Set("sticky_session", val.(string))
}
if val, ok := listener["StickySessionType"]; ok {
d.Set("sticky_session_type", val.(string))
}
if val, ok := listener["CookieTimeout"]; ok {
d.Set("cookie_timeout", val.(float64))
}
if val, ok := listener["Cookie"]; ok {
d.Set("cookie", val.(string))
}
if val, ok := listener["PersistenceTimeout"]; ok {
d.Set("persistence_timeout", val.(float64))
}
if val, ok := listener["HealthCheckType"]; ok {
d.Set("health_check_type", val.(string))
}
if val, ok := listener["EstablishedTimeout"]; ok {
d.Set("established_timeout", val.(float64))
}
if val, ok := listener["HealthCheckDomain"]; ok {
d.Set("health_check_domain", val.(string))
}
if val, ok := listener["HealthCheckMethod"]; ok {
d.Set("health_check_method", val.(string))
}
if val, ok := listener["HealthCheckConnectPort"]; ok {
d.Set("health_check_connect_port", val.(float64))
}
if val, ok := listener["HealthCheckURI"]; ok {
d.Set("health_check_uri", val.(string))
}
if val, ok := listener["HealthyThreshold"]; ok {
d.Set("healthy_threshold", val.(float64))
}
if val, ok := listener["UnhealthyThreshold"]; ok {
d.Set("unhealthy_threshold", val.(float64))
}
if val, ok := listener["HealthCheckTimeout"]; ok {
d.Set("health_check_timeout", val.(float64))
}
if val, ok := listener["HealthCheckConnectTimeout"]; ok {
d.Set("health_check_timeout", val.(float64))
}
if val, ok := listener["HealthCheckInterval"]; ok {
d.Set("health_check_interval", val.(float64))
}
if val, ok := listener["HealthCheckHttpCode"]; ok {
d.Set("health_check_http_code", val.(string))
}
if val, ok := listener["ServerCertificateId"]; ok {
d.Set("ssl_certificate_id", val.(string))
d.Set("server_certificate_id", val.(string))
}
if val, ok := listener["CACertificateId"]; ok {
d.Set("ca_certificate_id", val.(string))
}
if val, ok := listener["EnableHttp2"]; ok {
d.Set("enable_http2", val.(string))
}
if val, ok := listener["TLSCipherPolicy"]; ok {
d.Set("tls_cipher_policy", val.(string))
}
if val, ok := listener["IdleTimeout"]; ok {
d.Set("idle_timeout", val.(float64))
}
if val, ok := listener["RequestTimeout"]; ok {
d.Set("request_timeout", val.(float64))
}
if val, ok := listener["Gzip"]; ok {
d.Set("gzip", val.(string) == string(OnFlag))
}
if val, ok := listener["ListenerForward"]; ok {
d.Set("listener_forward", val.(string))
}
if val, ok := listener["ForwardPort"]; ok {
d.Set("forward_port", val.(float64))
}
xff := make(map[string]interface{})
if val, ok := listener["XForwardedFor"]; ok {
xff["retrive_client_ip"] = val.(string) == string(OnFlag)
}
if val, ok := listener["XForwardedFor_SLBIP"]; ok {
xff["retrive_slb_ip"] = val.(string) == string(OnFlag)
}
if val, ok := listener["XForwardedFor_SLBID"]; ok {
xff["retrive_slb_id"] = val.(string) == string(OnFlag)
}
if val, ok := listener["XForwardedFor_proto"]; ok {
xff["retrive_slb_proto"] = val.(string) == string(OnFlag)
}
if len(xff) > 0 {
d.Set("x_forwarded_for", []map[string]interface{}{xff})
}
if val, ok := listener["Description"]; ok {
d.Set("description", val.(string))
}
return
}
func getHealthCheckHttpCodeValue(d *schema.ResourceData) string {
if v, ok := d.GetOk("health_check_http_code"); ok && v.(string) != "" {
return v.(string)
}
// After the version 1.144.0, removes health_check_http_code Default and using Computed instead.
return string(HTTP_2XX)
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudSlbLoadBalancer() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSlbLoadBalancerCreate,
Read: resourceAlicloudSlbLoadBalancerRead,
Update: resourceAlicloudSlbLoadBalancerUpdate,
Delete: resourceAlicloudSlbLoadBalancerDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
Delete: schema.DefaultTimeout(9 * time.Minute),
},
Schema: map[string]*schema.Schema{
"internet": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Computed: true,
Removed: "Field 'internet' has been removed from provider version 1.124. Use 'address_type' replaces it.",
},
"address": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("address_type"); ok && v.(string) == "internet" {
return true
}
return false
},
},
"address_ip_version": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ipv4", "ipv6"}, false),
Default: "ipv4",
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("address_type"); ok && v.(string) == "intranet" {
return true
}
return false
},
},
"address_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"internet", "intranet"}, false),
},
"bandwidth": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
ValidateFunc: validation.IntBetween(1, 1000),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if d.Get("internet_charge_type").(string) == "PayByTraffic" {
return true
}
return false
},
},
"delete_protection": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"off", "on"}, false),
Default: "off",
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("payment_type"); ok && v.(string) == "Subscription" {
return true
}
if v, ok := d.GetOk("instance_charge_type"); ok && v.(string) == "PrePaid" {
return true
}
return false
},
},
"internet_charge_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"PayByBandwidth", "PayByTraffic"}, true),
Default: "PayByTraffic",
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("address_type"); ok && v.(string) == "intranet" {
return true
}
return false
},
},
"load_balancer_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"name"},
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Field 'name' has been deprecated from provider version 1.123.1. New field 'load_balancer_name' instead",
ConflictsWith: []string{"load_balancer_name"},
},
"load_balancer_spec": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"slb.s1.small", "slb.s2.medium", "slb.s2.small", "slb.s3.large", "slb.s3.medium", "slb.s3.small", "slb.s4.large"}, false),
ConflictsWith: []string{"specification"},
},
"specification": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"slb.s1.small", "slb.s2.medium", "slb.s2.small", "slb.s3.large", "slb.s3.medium", "slb.s3.small", "slb.s4.large"}, false),
Deprecated: "Field 'specification' has been deprecated from provider version 1.123.1. New field 'load_balancer_spec' instead",
ConflictsWith: []string{"load_balancer_spec"},
},
"master_zone_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"modification_protection_reason": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("modification_protection_status"); ok && v.(string) == "NonProtection" {
return true
}
return false
},
},
"modification_protection_status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"ConsoleProtection", "NonProtection"}, false),
},
"period": {
Type: schema.TypeInt,
Optional: true,
DiffSuppressFunc: PostPaidDiffSuppressFunc,
ValidateFunc: validation.Any(validation.IntBetween(1, 9), validation.IntInSlice([]int{12, 24, 36})),
},
"payment_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo", "Subscription"}, false),
ConflictsWith: []string{"instance_charge_type"},
},
"instance_charge_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"PostPaid", "PrePaid"}, false),
ConflictsWith: []string{"payment_type"},
Deprecated: "Field 'instance_charge_type' has been deprecated from provider version 1.124. Use 'payment_type' replaces it.",
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"slave_zone_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"active", "inactive"}, false),
},
"tags": tagsSchema(),
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("address_type"); ok && v.(string) == "internet" {
return true
}
return false
},
},
},
}
}
func resourceAlicloudSlbLoadBalancerCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
var response map[string]interface{}
action := "CreateLoadBalancer"
request := make(map[string]interface{})
conn, err := client.NewSlbClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("address"); ok {
request["Address"] = v
}
if v, ok := d.GetOk("address_ip_version"); ok {
request["AddressIPVersion"] = v
}
if v, ok := d.GetOk("address_type"); ok {
request["AddressType"] = v
}
if v, ok := d.GetOk("bandwidth"); ok {
request["Bandwidth"] = v
}
if v, ok := d.GetOk("delete_protection"); ok {
request["DeleteProtection"] = v
}
if v, ok := d.GetOk("internet_charge_type"); ok {
request["InternetChargeType"] = convertSlbLoadBalancerInternetChargeTypeRequest(v.(string))
}
if v, ok := d.GetOk("load_balancer_name"); ok {
request["LoadBalancerName"] = v
} else if v, ok := d.GetOk("name"); ok {
request["LoadBalancerName"] = v
}
if v, ok := d.GetOk("load_balancer_spec"); ok {
request["LoadBalancerSpec"] = v
} else if v, ok := d.GetOk("specification"); ok {
request["LoadBalancerSpec"] = v
}
if v, ok := d.GetOk("master_zone_id"); ok {
request["MasterZoneId"] = v
}
if v, ok := d.GetOk("modification_protection_reason"); ok {
request["ModificationProtectionReason"] = v
}
if v, ok := d.GetOk("modification_protection_status"); ok {
request["ModificationProtectionStatus"] = v
}
if v, ok := d.GetOk("payment_type"); ok {
request["PayType"] = convertSlbLoadBalancerPaymentTypeRequest(v.(string))
} else if v, ok := d.GetOk("instance_charge_type"); ok {
request["PayType"] = convertSlbLoadBalancerInstanceChargeTypeRequest(v.(string))
}
if v, ok := request["PayType"]; ok && v.(string) == "PrePay" {
period := 1
if v, ok := d.GetOk("period"); ok {
period = v.(int)
}
request["Duration"] = period
request["PricingCycle"] = string(Month)
if period > 9 {
request["Duration"] = period / 12
request["PricingCycle"] = string(Year)
}
request["AutoPay"] = true
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("slave_zone_id"); ok {
request["SlaveZoneId"] = v
}
vswitchId := Trim(d.Get("vswitch_id").(string))
if vswitchId != "" {
vpcService := VpcService{client}
vsw, err := vpcService.DescribeVSwitchWithTeadsl(vswitchId)
if err != nil {
return WrapError(err)
}
request["VpcId"] = vsw["VpcId"]
request["VSwitchId"] = vswitchId
}
request["ClientToken"] = buildClientToken("CreateLoadBalancer")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"OperationFailed.TokenIsProcessing"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_slb_load_balancer", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["LoadBalancerId"]))
stateConf := BuildStateConf([]string{}, []string{"active"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, slbService.SlbLoadBalancerStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudSlbLoadBalancerUpdate(d, meta)
}
func resourceAlicloudSlbLoadBalancerRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
object, err := slbService.DescribeSlbLoadBalancer(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_slb_load_balancer slbService.DescribeSlbLoadBalancer Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("address", object["Address"])
d.Set("address_ip_version", object["AddressIPVersion"])
d.Set("address_type", object["AddressType"])
d.Set("bandwidth", formatInt(object["Bandwidth"]))
d.Set("delete_protection", object["DeleteProtection"])
d.Set("internet_charge_type", convertSlbLoadBalancerInternetChargeTypeResponse(object["InternetChargeType"]))
d.Set("load_balancer_name", object["LoadBalancerName"])
d.Set("name", object["LoadBalancerName"])
d.Set("load_balancer_spec", object["LoadBalancerSpec"])
d.Set("specification", object["LoadBalancerSpec"])
d.Set("master_zone_id", object["MasterZoneId"])
d.Set("modification_protection_reason", object["ModificationProtectionReason"])
d.Set("modification_protection_status", object["ModificationProtectionStatus"])
d.Set("payment_type", convertSlbLoadBalancerPaymentTypeResponse(object["PayType"]))
d.Set("instance_charge_type", convertSlbLoadBalancerInstanceChargeTypeResponse(object["PayType"]))
d.Set("resource_group_id", object["ResourceGroupId"])
d.Set("slave_zone_id", object["SlaveZoneId"])
d.Set("status", object["LoadBalancerStatus"])
d.Set("vswitch_id", object["VSwitchId"])
listTagResourcesObject, err := slbService.ListTagResources(d.Id(), "instance")
if err != nil {
return WrapError(err)
}
d.Set("tags", tagsToMap(listTagResourcesObject))
return nil
}
func resourceAlicloudSlbLoadBalancerUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
var response map[string]interface{}
d.Partial(true)
if d.HasChange("tags") {
if err := slbService.SetResourceTags(d, "instance"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
if d.HasChange("status") {
request := map[string]interface{}{
"LoadBalancerId": d.Id(),
}
request["LoadBalancerStatus"] = d.Get("status")
action := "SetLoadBalancerStatus"
conn, err := client.NewSlbClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("status")
}
if !d.IsNewResource() && d.HasChange("delete_protection") {
request := map[string]interface{}{
"LoadBalancerId": d.Id(),
}
request["DeleteProtection"] = d.Get("delete_protection")
request["RegionId"] = client.RegionId
action := "SetLoadBalancerDeleteProtection"
conn, err := client.NewSlbClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("delete_protection")
}
update := false
request := map[string]interface{}{
"LoadBalancerId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("load_balancer_name") {
update = true
request["LoadBalancerName"] = d.Get("load_balancer_name")
} else if !d.IsNewResource() && d.HasChange("name") {
update = true
request["LoadBalancerName"] = d.Get("name")
}
request["RegionId"] = client.RegionId
if update {
action := "SetLoadBalancerName"
conn, err := client.NewSlbClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("name")
d.SetPartial("load_balancer_name")
}
update = false
modifyLoadBalancerInstanceSpecReq := map[string]interface{}{
"LoadBalancerId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("load_balancer_spec") {
update = true
modifyLoadBalancerInstanceSpecReq["LoadBalancerSpec"] = d.Get("load_balancer_spec")
} else if !d.IsNewResource() && d.HasChange("specification") {
update = true
modifyLoadBalancerInstanceSpecReq["LoadBalancerSpec"] = d.Get("specification")
}
modifyLoadBalancerInstanceSpecReq["RegionId"] = client.RegionId
if update {
action := "ModifyLoadBalancerInstanceSpec"
conn, err := client.NewSlbClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, modifyLoadBalancerInstanceSpecReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, modifyLoadBalancerInstanceSpecReq)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("specification")
d.SetPartial("load_balancer_spec")
}
update = false
setLoadBalancerModificationProtectionReq := map[string]interface{}{
"LoadBalancerId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("modification_protection_status") {
update = true
}
setLoadBalancerModificationProtectionReq["ModificationProtectionStatus"] = d.Get("modification_protection_status")
setLoadBalancerModificationProtectionReq["RegionId"] = client.RegionId
if !d.IsNewResource() && d.HasChange("modification_protection_reason") {
update = true
setLoadBalancerModificationProtectionReq["ModificationProtectionReason"] = d.Get("modification_protection_reason")
}
if update {
action := "SetLoadBalancerModificationProtection"
conn, err := client.NewSlbClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, setLoadBalancerModificationProtectionReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, setLoadBalancerModificationProtectionReq)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("modification_protection_status")
d.SetPartial("modification_protection_reason")
}
update = false
modifyLoadBalancerInternetSpecReq := map[string]interface{}{
"LoadBalancerId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("bandwidth") {
update = true
modifyLoadBalancerInternetSpecReq["Bandwidth"] = d.Get("bandwidth")
}
if !d.IsNewResource() && d.HasChange("internet_charge_type") {
update = true
modifyLoadBalancerInternetSpecReq["InternetChargeType"] = d.Get("internet_charge_type")
}
modifyLoadBalancerInternetSpecReq["RegionId"] = client.RegionId
if update {
action := "ModifyLoadBalancerInternetSpec"
conn, err := client.NewSlbClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, modifyLoadBalancerInternetSpecReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, modifyLoadBalancerInternetSpecReq)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("bandwidth")
d.SetPartial("internet_charge_type")
}
update = false
modifyLoadBalancerPayTypeReq := map[string]interface{}{
"LoadBalancerId": d.Id(),
}
modifyLoadBalancerPayTypeReq["RegionId"] = client.RegionId
if !d.IsNewResource() && d.HasChange("payment_type") {
update = true
modifyLoadBalancerPayTypeReq["PayType"] = convertSlbLoadBalancerPaymentTypeRequest(d.Get("payment_type").(string))
}
if !d.IsNewResource() && d.HasChange("instance_charge_type") {
update = true
modifyLoadBalancerPayTypeReq["PayType"] = convertSlbLoadBalancerInstanceChargeTypeRequest(d.Get("instance_charge_type").(string))
}
if v, ok := modifyLoadBalancerPayTypeReq["PayType"]; ok && v.(string) == "PrePay" {
period := 1
if v, ok := d.GetOk("period"); ok {
period = v.(int)
}
modifyLoadBalancerPayTypeReq["Duration"] = period
modifyLoadBalancerPayTypeReq["PricingCycle"] = string(Month)
if period > 9 {
modifyLoadBalancerPayTypeReq["Duration"] = period / 12
modifyLoadBalancerPayTypeReq["PricingCycle"] = string(Year)
}
modifyLoadBalancerPayTypeReq["AutoPay"] = true
}
if update {
action := "ModifyLoadBalancerPayType"
conn, err := client.NewSlbClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, modifyLoadBalancerPayTypeReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, modifyLoadBalancerPayTypeReq)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("instance_charge_type")
d.SetPartial("payment_type")
}
d.Partial(false)
return resourceAlicloudSlbLoadBalancerRead(d, meta)
}
func resourceAlicloudSlbLoadBalancerDelete(d *schema.ResourceData, meta interface{}) error {
if d.Get("payment_type").(string) == "Subscription" || d.Get("instance_charge_type").(string) == "Prepaid" {
log.Printf("[WARN] Cannot destroy Subscription resource: alicloud_slb_load_balancer. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
action := "DeleteLoadBalancer"
var response map[string]interface{}
conn, err := client.NewSlbClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"LoadBalancerId": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidLoadBalancerId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, slbService.SlbLoadBalancerStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
func convertSlbLoadBalancerInternetChargeTypeRequest(source interface{}) interface{} {
switch source {
case "PayByBandwidth":
return "paybybandwidth"
case "PayByTraffic":
return "paybytraffic"
}
return source
}
func convertSlbLoadBalancerPaymentTypeRequest(source interface{}) interface{} {
switch source {
case "PayAsYouGo":
return "PayOnDemand"
case "Subscription":
return "PrePay"
}
return source
}
func convertSlbLoadBalancerInstanceChargeTypeRequest(source interface{}) interface{} {
switch source {
case "PostPaid":
return "PayOnDemand"
case "PrePaid":
return "PrePay"
}
return source
}
func convertSlbLoadBalancerInternetChargeTypeResponse(source interface{}) interface{} {
switch source {
case "paybybandwidth":
return "PayByBandwidth"
case "paybytraffic":
return "PayByTraffic"
}
return source
}
func convertSlbLoadBalancerPaymentTypeResponse(source interface{}) interface{} {
switch source {
case "PayOnDemand":
return "PayAsYouGo"
case "PrePay":
return "Subscription"
}
return source
}
func convertSlbLoadBalancerInstanceChargeTypeResponse(source interface{}) interface{} {
switch source {
case "PayOnDemand":
return "PostPaid"
case "PrePay":
return "PrePaid"
}
return source
}
package alicloud
import (
"fmt"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/slb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliyunSlbMasterSlaveServerGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunSlbMasterSlaveServerGroupCreate,
Read: resourceAliyunSlbMasterSlaveServerGroupRead,
Update: resourceAliyunSlbMasterSlaveServerGroupUpdate,
Delete: resourceAliyunSlbMasterSlaveServerGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"load_balancer_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"servers": {
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"server_id": {
Type: schema.TypeString,
Required: true,
},
"port": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(1, 65535),
},
"weight": {
Type: schema.TypeInt,
Optional: true,
Default: 100,
ValidateFunc: validation.IntBetween(0, 100),
},
"type": {
Type: schema.TypeString,
Optional: true,
Default: string(ECS),
ValidateFunc: validation.StringInSlice([]string{"eni", "ecs"}, false),
},
"server_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Master", "Slave"}, false),
},
"is_backup": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{0, 1}),
Removed: "Field 'is_backup' has been removed from provider version 1.63.0.",
},
},
},
MaxItems: 2,
MinItems: 2,
},
"delete_protection_validation": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func resourceAliyunSlbMasterSlaveServerGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := slb.CreateCreateMasterSlaveServerGroupRequest()
request.RegionId = client.RegionId
request.LoadBalancerId = d.Get("load_balancer_id").(string)
if v, ok := d.GetOk("name"); ok {
request.MasterSlaveServerGroupName = v.(string)
}
if v, ok := d.GetOk("servers"); ok {
request.MasterSlaveBackendServers = expandMasterSlaveBackendServersToString(v.(*schema.Set).List())
}
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.CreateMasterSlaveServerGroup(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_slb_master_slave_server_group", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*slb.CreateMasterSlaveServerGroupResponse)
d.SetId(response.MasterSlaveServerGroupId)
return resourceAliyunSlbMasterSlaveServerGroupRead(d, meta)
}
func resourceAliyunSlbMasterSlaveServerGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
object, err := slbService.DescribeSlbMasterSlaveServerGroup(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", object.MasterSlaveServerGroupName)
d.Set("load_balancer_id", object.LoadBalancerId)
servers := make([]map[string]interface{}, 0)
for _, server := range object.MasterSlaveBackendServers.MasterSlaveBackendServer {
s := map[string]interface{}{
"server_id": server.ServerId,
"port": server.Port,
"weight": server.Weight,
"type": server.Type,
"server_type": server.ServerType,
}
servers = append(servers, s)
}
if err := d.Set("servers", servers); err != nil {
return WrapError(err)
}
return nil
}
func resourceAliyunSlbMasterSlaveServerGroupUpdate(d *schema.ResourceData, meta interface{}) error {
return nil
}
func resourceAliyunSlbMasterSlaveServerGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
if d.Get("delete_protection_validation").(bool) {
lbId := d.Get("load_balancer_id").(string)
lbInstance, err := slbService.DescribeSlb(lbId)
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
if lbInstance.DeleteProtection == "on" {
return WrapError(fmt.Errorf("Current master-slave server group's SLB Instance %s has enabled DeleteProtection. Please set delete_protection_validation to false to delete the resource.", lbId))
}
}
request := slb.CreateDeleteMasterSlaveServerGroupRequest()
request.RegionId = client.RegionId
request.MasterSlaveServerGroupId = d.Id()
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DeleteMasterSlaveServerGroup(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"RspoolVipExist"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"The specified MasterSlaveGroupId does not exist", "InvalidParameter"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(slbService.WaitForSlbMasterSlaveServerGroup(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"fmt"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"strconv"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/slb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliyunSlbRule() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunSlbRuleCreate,
Read: resourceAliyunSlbRuleRead,
Update: resourceAliyunSlbRuleUpdate,
Delete: resourceAliyunSlbRuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"load_balancer_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"frontend_port": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(1, 65535),
Required: true,
ForceNew: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
Default: "tf-slb-rule",
},
"listener_sync": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"on", "off"}, false),
Optional: true,
Default: string(OnFlag),
},
"scheduler": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"wrr", "wlc", "rr"}, false),
Optional: true,
Default: WRRScheduler,
DiffSuppressFunc: slbRuleListenerSyncDiffSuppressFunc,
},
"domain": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"url": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"server_group_id": {
Type: schema.TypeString,
Required: true,
},
"cookie": {
Type: schema.TypeString,
ValidateFunc: validation.StringLenBetween(1, 200),
Optional: true,
DiffSuppressFunc: slbRuleCookieDiffSuppressFunc,
},
"cookie_timeout": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(1, 86400),
Optional: true,
DiffSuppressFunc: slbRuleCookieTimeoutDiffSuppressFunc,
},
"health_check": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"on", "off"}, false),
Optional: true,
Default: OnFlag,
DiffSuppressFunc: slbRuleListenerSyncDiffSuppressFunc,
},
"health_check_http_code": {
Type: schema.TypeString,
ValidateFunc: validateAllowedSplitStringValue([]string{
string(HTTP_2XX), string(HTTP_3XX), string(HTTP_4XX), string(HTTP_5XX)}, ","),
Optional: true,
Default: HTTP_2XX,
DiffSuppressFunc: slbRuleHealthCheckDiffSuppressFunc,
},
"health_check_interval": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(1, 50),
Optional: true,
Default: 2,
DiffSuppressFunc: slbRuleHealthCheckDiffSuppressFunc,
},
"health_check_domain": {
Type: schema.TypeString,
ValidateFunc: validation.StringLenBetween(1, 80),
Optional: true,
DiffSuppressFunc: slbRuleHealthCheckDiffSuppressFunc,
},
"health_check_uri": {
Type: schema.TypeString,
ValidateFunc: validation.StringLenBetween(1, 80),
Optional: true,
Default: "/",
DiffSuppressFunc: slbRuleHealthCheckDiffSuppressFunc,
},
"health_check_connect_port": {
Type: schema.TypeInt,
ValidateFunc: validation.Any(
validation.IntBetween(1, 65535),
validation.IntInSlice([]int{-520})),
Optional: true,
Computed: true,
DiffSuppressFunc: slbRuleHealthCheckDiffSuppressFunc,
},
"health_check_timeout": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(1, 300),
Optional: true,
Default: 5,
DiffSuppressFunc: slbRuleHealthCheckDiffSuppressFunc,
},
"healthy_threshold": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(1, 10),
Optional: true,
Default: 3,
DiffSuppressFunc: slbRuleHealthCheckDiffSuppressFunc,
},
"unhealthy_threshold": {
Type: schema.TypeInt,
ValidateFunc: validation.IntBetween(1, 10),
Optional: true,
Default: 3,
DiffSuppressFunc: slbRuleHealthCheckDiffSuppressFunc,
},
//http & https
"sticky_session": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"on", "off"}, false),
Optional: true,
Default: OffFlag,
DiffSuppressFunc: slbRuleListenerSyncDiffSuppressFunc,
},
//http & https
"sticky_session_type": {
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{
string(InsertStickySessionType),
string(ServerStickySessionType)}, false),
Optional: true,
DiffSuppressFunc: slbRuleStickySessionTypeDiffSuppressFunc,
},
"delete_protection_validation": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func resourceAliyunSlbRuleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slb_id := d.Get("load_balancer_id").(string)
port := d.Get("frontend_port").(int)
name := strings.Trim(d.Get("name").(string), " ")
group_id := strings.Trim(d.Get("server_group_id").(string), " ")
var domain, url, rule string
if v, ok := d.GetOk("domain"); ok {
domain = v.(string)
}
if v, ok := d.GetOk("url"); ok {
url = v.(string)
}
if domain == "" && url == "" {
return WrapError(Error("At least one 'domain' or 'url' must be set."))
} else if domain == "" {
rule = fmt.Sprintf("[{'RuleName':'%s','Url':'%s','VServerGroupId':'%s'}]", name, url, group_id)
} else if url == "" {
rule = fmt.Sprintf("[{'RuleName':'%s','Domain':'%s','VServerGroupId':'%s'}]", name, domain, group_id)
} else {
rule = fmt.Sprintf("[{'RuleName':'%s','Domain':'%s','Url':'%s','VServerGroupId':'%s'}]", name, domain, url, group_id)
}
request := slb.CreateCreateRulesRequest()
request.RegionId = client.RegionId
request.LoadBalancerId = slb_id
request.ListenerPort = requests.NewInteger(port)
request.RuleList = rule
var raw interface{}
var err error
if err = resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err = client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.CreateRules(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"BackendServer.configuring", "OperationFailed.ListenerStatusNotSupport"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}); err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_slb_rule", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*slb.CreateRulesResponse)
d.SetId(response.Rules.Rule[0].RuleId)
return resourceAliyunSlbRuleUpdate(d, meta)
}
func resourceAliyunSlbRuleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
object, err := slbService.DescribeSlbRule(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", object.RuleName)
d.Set("load_balancer_id", object.LoadBalancerId)
if port, err := strconv.Atoi(object.ListenerPort); err != nil {
return WrapError(err)
} else {
d.Set("frontend_port", port)
}
d.Set("domain", object.Domain)
d.Set("url", object.Url)
d.Set("server_group_id", object.VServerGroupId)
d.Set("sticky_session", object.StickySession)
d.Set("sticky_session_type", object.StickySessionType)
d.Set("unhealthy_threshold", object.UnhealthyThreshold)
d.Set("healthy_threshold", object.HealthyThreshold)
d.Set("health_check_timeout", object.HealthCheckTimeout)
d.Set("health_check_connect_port", object.HealthCheckConnectPort)
d.Set("health_check_uri", object.HealthCheckURI)
d.Set("health_check", object.HealthCheck)
d.Set("health_check_http_code", object.HealthCheckHttpCode)
d.Set("health_check_interval", object.HealthCheckInterval)
d.Set("scheduler", object.Scheduler)
d.Set("listener_sync", object.ListenerSync)
d.Set("cookie_timeout", object.CookieTimeout)
d.Set("cookie", object.Cookie)
d.Set("health_check_domain", object.HealthCheckDomain)
return nil
}
func resourceAliyunSlbRuleUpdate(d *schema.ResourceData, meta interface{}) error {
update := false
fullUpdate := false
request := slb.CreateSetRuleRequest()
request.RuleId = d.Id()
if listenerSync, ok := d.GetOk("listener_sync"); ok && listenerSync == string(OffFlag) {
if stickySession := d.Get("sticky_session"); stickySession == string(OnFlag) {
if _, ok := d.GetOk("sticky_session_type"); !ok {
return WrapError(Error(`'sticky_session_type': required field is not set when the sticky_session is 'on'.`))
}
}
if stickySessionType := d.Get("sticky_session_type"); stickySessionType == string(InsertStickySessionType) {
if _, ok := d.GetOk("cookie_timeout"); !ok {
return WrapError(Error(`'cookie_timeout': required field is not set when the sticky_session_type is 'insert'.`))
}
}
if stickySessionType := d.Get("sticky_session_type"); stickySessionType == string(ServerStickySessionType) {
if _, ok := d.GetOk("cookie"); !ok {
return WrapError(Error(`'cookie': required field is not set when the sticky_session_type is 'server'.`))
}
}
}
if d.HasChange("server_group_id") {
request.VServerGroupId = d.Get("server_group_id").(string)
update = true
}
if d.HasChange("name") {
request.RuleName = d.Get("name").(string)
update = true
}
fullUpdate = d.HasChange("listener_sync") || d.HasChange("scheduler") || d.HasChange("cookie") || d.HasChange("cookie_timeout") || d.HasChange("health_check") || d.HasChange("health_check_http_code") ||
d.HasChange("health_check_interval") || d.HasChange("health_check_domain") || d.HasChange("health_check_uri") || d.HasChange("health_check_connect_port") || d.HasChange("health_check_timeout") ||
d.HasChange("healthy_threshold") || d.HasChange("unhealthy_threshold") || d.HasChange("sticky_session") || d.HasChange("sticky_session_type")
if fullUpdate {
request.ListenerSync = d.Get("listener_sync").(string)
if listenerSync, ok := d.GetOk("listener_sync"); ok && listenerSync == string(OffFlag) {
request.Scheduler = d.Get("scheduler").(string)
request.HealthCheck = d.Get("health_check").(string)
request.StickySession = d.Get("sticky_session").(string)
if request.HealthCheck == string(OnFlag) {
request.HealthCheckTimeout = requests.NewInteger(d.Get("health_check_timeout").(int))
request.HealthCheckURI = d.Get("health_check_uri").(string)
request.HealthyThreshold = requests.NewInteger(d.Get("healthy_threshold").(int))
request.UnhealthyThreshold = requests.NewInteger(d.Get("unhealthy_threshold").(int))
request.HealthCheckInterval = requests.NewInteger(d.Get("health_check_interval").(int))
request.HealthCheckHttpCode = d.Get("health_check_http_code").(string)
if healthCheckDomain, ok := d.GetOk("health_check_domain"); ok {
request.HealthCheckDomain = healthCheckDomain.(string)
}
if healthCheckConnectPort, ok := d.GetOk("health_check_connect_port"); ok {
request.HealthCheckConnectPort = requests.NewInteger(healthCheckConnectPort.(int))
}
}
if request.StickySession == string(OnFlag) {
request.StickySessionType = d.Get("sticky_session_type").(string)
if request.StickySessionType == string(InsertStickySessionType) {
request.CookieTimeout = requests.NewInteger(d.Get("cookie_timeout").(int))
}
if request.StickySessionType == string(ServerStickySessionType) {
request.Cookie = d.Get("cookie").(string)
}
}
}
}
if update || fullUpdate {
client := meta.(*connectivity.AliyunClient)
request.RegionId = client.RegionId
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.SetRule(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
return resourceAliyunSlbRuleRead(d, meta)
}
func resourceAliyunSlbRuleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
if d.Get("delete_protection_validation").(bool) {
lbId := d.Get("load_balancer_id").(string)
lbInstance, err := slbService.DescribeSlb(lbId)
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
if lbInstance.DeleteProtection == "on" {
return WrapError(fmt.Errorf("Current rule's SLB Instance %s has enabled DeleteProtection. Please set delete_protection_validation to false to delete the rule.", lbId))
}
}
request := slb.CreateDeleteRulesRequest()
request.RegionId = client.RegionId
request.RuleIds = fmt.Sprintf("['%s']", d.Id())
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DeleteRules(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"OperationFailed.ListenerStatusNotSupport"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidRuleId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(slbService.WaitForSlbRule(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/slb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudSlbServerCertificate() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSlbServerCertificateCreate,
Read: resourceAlicloudSlbServerCertificateRead,
Update: resourceAlicloudSlbServerCertificateUpdate,
Delete: resourceAlicloudSlbServerCertificateDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
},
"server_certificate": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
DiffSuppressFunc: slbServerCertificateDiffSuppressFunc,
},
"private_key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
DiffSuppressFunc: slbServerCertificateDiffSuppressFunc,
},
"alicloud_certificate_region_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"alicloud_certifacte_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Deprecated: "Field 'alicloud_certifacte_id' has been deprecated from provider version 1.68.0. Use 'alicloud_certificate_id' replaces it.",
},
"alicloud_certificate_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"alicloud_certifacte_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Deprecated: "Field 'alicloud_certifacte_name' has been deprecated from provider version 1.68.0. Use 'alicloud_certificate_name' replaces it.",
},
"alicloud_certificate_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"tags": tagsSchema(),
},
}
}
func resourceAlicloudSlbServerCertificateCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := slb.CreateUploadServerCertificateRequest()
request.RegionId = client.RegionId
if val, ok := d.GetOk("name"); ok && val != "" {
request.ServerCertificateName = val.(string)
}
if val, ok := d.GetOk("server_certificate"); ok && val != "" {
request.ServerCertificate = val.(string)
}
if val, ok := d.GetOk("private_key"); ok && val != "" {
request.PrivateKey = val.(string)
}
if val, ok := d.GetOk("alicloud_certificate_region_id"); ok && val != "" {
request.AliCloudCertificateRegionId = val.(string)
}
if val, ok := d.GetOk("alicloud_certificate_id"); ok && val != "" {
request.AliCloudCertificateId = val.(string)
}
if val, ok := d.GetOk("alicloud_certificate_name"); ok && val != "" {
request.AliCloudCertificateName = val.(string)
}
if val, ok := d.GetOk("resource_group_id"); ok && val != "" {
request.ResourceGroupId = val.(string)
}
// check server_certificate and private_key
if request.AliCloudCertificateId == "" {
if val := strings.Trim(request.ServerCertificate, " "); val == "" {
return WrapError(Error("UploadServerCertificate got an error, as server_certificate should be not null when alicloud_certificate_id is null."))
}
if val := strings.Trim(request.PrivateKey, " "); val == "" {
return WrapError(Error("UploadServerCertificate got an error, as either private_key or private_file should be not null when alicloud_certificate_id is null."))
}
}
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.UploadServerCertificate(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*slb.UploadServerCertificateResponse)
d.SetId(response.ServerCertificateId)
return resourceAlicloudSlbServerCertificateUpdate(d, meta)
}
func resourceAlicloudSlbServerCertificateRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
tags, err := slbService.DescribeTags(d.Id(), nil, TagResourceCertificate)
if err != nil {
return WrapError(err)
}
d.Set("tags", slbService.tagsToMap(tags))
serverCertificate, err := slbService.DescribeSlbServerCertificate(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
if err := d.Set("name", serverCertificate.ServerCertificateName); err != nil {
return WrapError(err)
}
if serverCertificate.AliCloudCertificateId != "" {
if err := d.Set("alicloud_certificate_id", serverCertificate.AliCloudCertificateId); err != nil {
return WrapError(err)
}
}
if serverCertificate.AliCloudCertificateName != "" {
if err := d.Set("alicloud_certificate_name", serverCertificate.AliCloudCertificateName); err != nil {
return WrapError(err)
}
}
if serverCertificate.ResourceGroupId != "" {
if err := d.Set("resource_group_id", serverCertificate.ResourceGroupId); err != nil {
return WrapError(err)
}
}
return nil
}
func resourceAlicloudSlbServerCertificateUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
if err := slbService.setInstanceTags(d, TagResourceCertificate); err != nil {
return WrapError(err)
}
if d.IsNewResource() {
d.Partial(false)
return resourceAlicloudSlbServerCertificateRead(d, meta)
}
if !d.IsNewResource() && d.HasChange("name") {
request := slb.CreateSetServerCertificateNameRequest()
request.RegionId = client.RegionId
request.ServerCertificateId = d.Id()
request.ServerCertificateName = d.Get("name").(string)
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.SetServerCertificateName(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
return resourceAlicloudSlbServerCertificateRead(d, meta)
}
func resourceAlicloudSlbServerCertificateDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
request := slb.CreateDeleteServerCertificateRequest()
request.RegionId = client.RegionId
request.ServerCertificateId = d.Id()
err := resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DeleteServerCertificate(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"CertificateAndPrivateKeyIsRefered"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ServerCertificateId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(slbService.WaitForSlbServerCertificate(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/slb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliyunSlbServerGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunSlbServerGroupCreate,
Read: resourceAliyunSlbServerGroupRead,
Update: resourceAliyunSlbServerGroupUpdate,
Delete: resourceAliyunSlbServerGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"load_balancer_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
Default: "tf-server-group",
},
"servers": {
Type: schema.TypeSet,
Optional: true,
Computed: true, // The Computed can not be removed and it used to meet scenario when using alicloud_ess_scalinggroup_vserver_groups
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"server_ids": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
MinItems: 1,
},
"port": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(1, 65535),
},
"weight": {
Type: schema.TypeInt,
Optional: true,
Default: 100,
ValidateFunc: validation.IntBetween(1, 100),
},
"type": {
Type: schema.TypeString,
Optional: true,
Default: string(ECS),
ValidateFunc: validation.StringInSlice([]string{"eni", "ecs"}, false),
},
},
},
},
"delete_protection_validation": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}
func resourceAliyunSlbServerGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := slb.CreateCreateVServerGroupRequest()
request.RegionId = client.RegionId
request.LoadBalancerId = d.Get("load_balancer_id").(string)
if v, ok := d.GetOk("name"); ok {
request.VServerGroupName = v.(string)
}
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.CreateVServerGroup(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_slb_server_group", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*slb.CreateVServerGroupResponse)
d.SetId(response.VServerGroupId)
return resourceAliyunSlbServerGroupUpdate(d, meta)
}
func resourceAliyunSlbServerGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
object, err := slbService.DescribeSlbServerGroup(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", object.VServerGroupName)
d.Set("load_balancer_id", object.LoadBalancerId)
servers := make([]map[string]interface{}, 0)
portAndWeight := make(map[string][]string)
for _, server := range object.BackendServers.BackendServer {
key := fmt.Sprintf("%d%s%d%s%s", server.Port, COLON_SEPARATED, server.Weight, COLON_SEPARATED, server.Type)
if v, ok := portAndWeight[key]; !ok {
portAndWeight[key] = []string{server.ServerId}
} else {
v = append(v, server.ServerId)
portAndWeight[key] = v
}
}
for key, value := range portAndWeight {
k := strings.Split(key, COLON_SEPARATED)
p, e := strconv.Atoi(k[0])
if e != nil {
return WrapError(e)
}
w, e := strconv.Atoi(k[1])
if e != nil {
return WrapError(e)
}
t := k[2]
s := map[string]interface{}{
"server_ids": value,
"port": p,
"weight": w,
"type": t,
}
servers = append(servers, s)
}
if err := d.Set("servers", servers); err != nil {
return WrapError(err)
}
return nil
}
func resourceAliyunSlbServerGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
d.Partial(true)
var removeserverSet, addServerSet, updateServerSet *schema.Set
serverUpdate := false
step := 20
if d.HasChange("servers") {
o, n := d.GetChange("servers")
os := o.(*schema.Set)
ns := n.(*schema.Set)
remove := os.Difference(ns).List()
add := ns.Difference(os).List()
oldIdPort := getIdPortSetFromServers(remove)
newIdPort := getIdPortSetFromServers(add)
updateServerSet = oldIdPort.Intersection(newIdPort)
removeserverSet = oldIdPort.Difference(newIdPort)
addServerSet = newIdPort.Difference(oldIdPort)
if removeserverSet.Len() > 0 {
rmservers := make([]interface{}, 0)
for _, rmserver := range remove {
rms := rmserver.(map[string]interface{})
if v, ok := rms["server_ids"]; ok {
server_ids := v.([]interface{})
for _, id := range server_ids {
idPort := fmt.Sprintf("%s:%d", id, rms["port"])
if removeserverSet.Contains(idPort) {
rmsm := map[string]interface{}{
"server_id": id,
"port": rms["port"],
"type": rms["type"],
"weight": rms["weight"],
}
rmservers = append(rmservers, rmsm)
}
}
}
}
request := slb.CreateRemoveVServerGroupBackendServersRequest()
request.RegionId = client.RegionId
request.VServerGroupId = d.Id()
segs := len(rmservers)/step + 1
for i := 0; i < segs; i++ {
start := i * step
end := (i + 1) * step
if end >= len(rmservers) {
end = len(rmservers)
}
request.BackendServers = expandBackendServersWithPortToString(rmservers[start:end])
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.RemoveVServerGroupBackendServers(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("servers")
}
}
if addServerSet.Len() > 0 {
addservers := make([]interface{}, 0)
for _, addserver := range add {
adds := addserver.(map[string]interface{})
if v, ok := adds["server_ids"]; ok {
server_ids := v.([]interface{})
for _, id := range server_ids {
idPort := fmt.Sprintf("%s:%d", id, adds["port"])
if addServerSet.Contains(idPort) {
addsm := map[string]interface{}{
"server_id": id,
"port": adds["port"],
"type": adds["type"],
"weight": adds["weight"],
}
addservers = append(addservers, addsm)
}
}
}
}
request := slb.CreateAddVServerGroupBackendServersRequest()
request.RegionId = client.RegionId
request.VServerGroupId = d.Id()
segs := len(addservers)/step + 1
for i := 0; i < segs; i++ {
start := i * step
end := (i + 1) * step
if end >= len(addservers) {
end = len(addservers)
}
request.BackendServers = expandBackendServersWithPortToString(addservers[start:end])
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.AddVServerGroupBackendServers(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("servers")
}
}
}
name := d.Get("name").(string)
nameUpdate := false
if d.HasChange("name") {
nameUpdate = true
}
if d.HasChange("servers") {
serverUpdate = true
}
if serverUpdate || nameUpdate {
request := slb.CreateSetVServerGroupAttributeRequest()
request.RegionId = client.RegionId
request.VServerGroupId = d.Id()
request.VServerGroupName = name
if serverUpdate {
servers := make([]interface{}, 0)
for _, server := range d.Get("servers").(*schema.Set).List() {
s := server.(map[string]interface{})
if v, ok := s["server_ids"]; ok {
server_ids := v.([]interface{})
for _, id := range server_ids {
idPort := fmt.Sprintf("%s:%d", id, s["port"])
if updateServerSet.Contains(idPort) {
sm := map[string]interface{}{
"server_id": id,
"port": s["port"],
"type": s["type"],
"weight": s["weight"],
}
servers = append(servers, sm)
}
}
}
}
segs := len(servers)/step + 1
for i := 0; i < segs; i++ {
start := i * step
end := (i + 1) * step
if end >= len(servers) {
end = len(servers)
}
request.BackendServers = expandBackendServersWithPortToString(servers[start:end])
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.SetVServerGroupAttribute(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("servers")
d.SetPartial("name")
}
} else {
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.SetVServerGroupAttribute(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("name")
}
}
d.Partial(false)
return resourceAliyunSlbServerGroupRead(d, meta)
}
func resourceAliyunSlbServerGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
if d.Get("delete_protection_validation").(bool) {
lbId := d.Get("load_balancer_id").(string)
lbInstance, err := slbService.DescribeSlb(lbId)
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
if lbInstance.DeleteProtection == "on" {
return WrapError(fmt.Errorf("Current VServerGroup's SLB Instance %s has enabled DeleteProtection. Please set delete_protection_validation to false to delete the group.", lbId))
}
}
request := slb.CreateDeleteVServerGroupRequest()
request.RegionId = client.RegionId
request.VServerGroupId = d.Id()
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DeleteVServerGroup(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"RspoolVipExist"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"The specified VServerGroupId does not exist", "InvalidParameter"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(slbService.WaitForSlbServerGroup(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudSlbTlsCipherPolicy() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSlbTlsCipherPolicyCreate,
Read: resourceAlicloudSlbTlsCipherPolicyRead,
Update: resourceAlicloudSlbTlsCipherPolicyUpdate,
Delete: resourceAlicloudSlbTlsCipherPolicyDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"ciphers": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tls_cipher_policy_name": {
Type: schema.TypeString,
Required: true,
},
"tls_versions": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
}
}
func resourceAlicloudSlbTlsCipherPolicyCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateTLSCipherPolicy"
request := make(map[string]interface{})
conn, err := client.NewSlbClient()
if err != nil {
return WrapError(err)
}
request["Ciphers"] = d.Get("ciphers")
request["RegionId"] = client.RegionId
request["Name"] = d.Get("tls_cipher_policy_name")
request["TLSVersions"] = d.Get("tls_versions")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_slb_tls_cipher_policy", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["TLSCipherPolicyId"]))
return resourceAlicloudSlbTlsCipherPolicyRead(d, meta)
}
func resourceAlicloudSlbTlsCipherPolicyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
slbService := SlbService{client}
object, err := slbService.DescribeSlbTlsCipherPolicy(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_slb_tls_cipher_policy slbService.DescribeSlbTlsCipherPolicy Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("ciphers", object["Ciphers"])
d.Set("status", object["Status"])
d.Set("tls_cipher_policy_name", object["Name"])
d.Set("tls_versions", object["TLSVersions"])
return nil
}
func resourceAlicloudSlbTlsCipherPolicyUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
conn, err := client.NewSlbClient()
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"TLSCipherPolicyId": d.Id(),
}
if d.HasChange("ciphers") {
update = true
}
request["Ciphers"] = d.Get("ciphers")
request["RegionId"] = client.RegionId
if d.HasChange("tls_cipher_policy_name") {
update = true
}
request["Name"] = d.Get("tls_cipher_policy_name")
if d.HasChange("tls_versions") {
update = true
}
request["TLSVersions"] = d.Get("tls_versions")
if update {
action := "SetTLSCipherPolicyAttribute"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudSlbTlsCipherPolicyRead(d, meta)
}
func resourceAlicloudSlbTlsCipherPolicyDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteTLSCipherPolicy"
var response map[string]interface{}
conn, err := client.NewSlbClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"TLSCipherPolicyId": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudSnatEntry() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSnatEntryCreate,
Read: resourceAlicloudSnatEntryRead,
Update: resourceAlicloudSnatEntryUpdate,
Delete: resourceAlicloudSnatEntryDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(2 * time.Minute),
Delete: schema.DefaultTimeout(2 * time.Minute),
Update: schema.DefaultTimeout(2 * time.Minute),
},
Schema: map[string]*schema.Schema{
"snat_entry_id": {
Type: schema.TypeString,
Computed: true,
},
"snat_entry_name": {
Type: schema.TypeString,
Optional: true,
},
"snat_ip": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"snat_table_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"source_cidr": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
ConflictsWith: strings.Fields("source_vswitch_id"),
},
"source_vswitch_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
ConflictsWith: strings.Fields("source_cidr"),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudSnatEntryCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
action := "CreateSnatEntry"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("snat_entry_name"); ok {
request["SnatEntryName"] = v
}
request["SnatIp"] = d.Get("snat_ip")
request["SnatTableId"] = d.Get("snat_table_id")
if v, ok := d.GetOk("source_cidr"); ok {
request["SourceCIDR"] = v
}
if v, ok := d.GetOk("source_vswitch_id"); ok {
request["SourceVSwitchId"] = v
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("CreateSnatEntry")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"EIP_NOT_IN_GATEWAY", "InternalError", "OperationFailed.Throttling", "OperationUnsupported.EipInBinding", "OperationUnsupported.EipNatBWPCheck", "OperationConflict"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_snat_entry", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["SnatTableId"], ":", response["SnatEntryId"]))
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, vpcService.SnatEntryStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudSnatEntryUpdate(d, meta)
}
func resourceAlicloudSnatEntryRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
// compatible with previous id which in under 1.37.0
if strings.HasPrefix(d.Id(), "snat-") {
d.SetId(fmt.Sprintf("%s%s%s", d.Get("snat_table_id").(string), COLON_SEPARATED, d.Id()))
}
object, err := vpcService.DescribeSnatEntry(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_snat_entry vpcService.DescribeSnatEntry Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("snat_entry_id", parts[1])
d.Set("snat_table_id", parts[0])
d.Set("snat_entry_name", object["SnatEntryName"])
d.Set("snat_ip", object["SnatIp"])
d.Set("source_cidr", object["SourceCIDR"])
d.Set("source_vswitch_id", object["SourceVSwitchId"])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudSnatEntryUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
// compatible with previous id which in under 1.37.0
if strings.HasPrefix(d.Id(), "snat-") {
d.SetId(fmt.Sprintf("%s%s%s", d.Get("snat_table_id").(string), COLON_SEPARATED, d.Id()))
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
if !d.IsNewResource() && d.HasChange("snat_entry_name") {
request := map[string]interface{}{
"SnatEntryId": parts[1],
"SnatTableId": parts[0],
}
request["RegionId"] = client.RegionId
request["SnatEntryName"] = d.Get("snat_entry_name")
action := "ModifySnatEntry"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("ModifySnatEntry")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, vpcService.SnatEntryStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudSnatEntryRead(d, meta)
}
func resourceAlicloudSnatEntryDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
// compatible with previous id which in under 1.37.0
if strings.HasPrefix(d.Id(), "snat-") {
d.SetId(fmt.Sprintf("%s%s%s", d.Get("snat_table_id").(string), COLON_SEPARATED, d.Id()))
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
vpcService := VpcService{client}
action := "DeleteSnatEntry"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"SnatEntryId": parts[1],
"SnatTableId": parts[0],
}
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("DeleteSnatEntry")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IncorretSnatEntryStatus"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidSnatEntryId.NotFound", "InvalidSnatTableId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, vpcService.SnatEntryStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudSslCertificatesServiceCertificate() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudSslCertificatesServiceCertificateCreate,
Read: resourceAlicloudSslCertificatesServiceCertificateRead,
Update: resourceAlicloudSslCertificatesServiceCertificateUpdate,
Delete: resourceAlicloudSslCertificatesServiceCertificateDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"cert": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"certificate_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"name"},
ValidateFunc: validation.StringLenBetween(1, 64),
ForceNew: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
Deprecated: "Field 'name' has been deprecated from provider version 1.129.0 and it will be remove in the future version. Please use the new attribute 'certificate_name' instead.",
ConflictsWith: []string{"certificate_name"},
ValidateFunc: validation.StringLenBetween(1, 64),
},
"key": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"lang": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudSslCertificatesServiceCertificateCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateUserCertificate"
request := make(map[string]interface{})
conn, err := client.NewCasClient()
if err != nil {
return WrapError(err)
}
request["Cert"] = d.Get("cert")
request["Key"] = d.Get("key")
if v, ok := d.GetOk("certificate_name"); ok {
request["Name"] = v
} else if v, ok := d.GetOk("name"); ok {
request["Name"] = v
} else {
return WrapError(fmt.Errorf("Field 'certificate_name' is required"))
}
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-07-13"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ssl_certificates_service_certificate", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["CertId"]))
return resourceAlicloudSslCertificatesServiceCertificateRead(d, meta)
}
func resourceAlicloudSslCertificatesServiceCertificateRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
casService := CasService{client}
object, err := casService.DescribeSslCertificatesServiceCertificate(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ssl_certificates_service_certificate casService.DescribeSslCertificatesServiceCertificate Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("cert", object["Cert"])
d.Set("certificate_name", object["Name"])
d.Set("name", object["Name"])
d.Set("key", object["Key"])
return nil
}
func resourceAlicloudSslCertificatesServiceCertificateUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return resourceAlicloudSslCertificatesServiceCertificateRead(d, meta)
}
func resourceAlicloudSslCertificatesServiceCertificateDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteUserCertificate"
var response map[string]interface{}
conn, err := client.NewCasClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"CertId": d.Id(),
}
if v, ok := d.GetOk("lang"); ok {
request["Lang"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-07-13"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliyunSslVpnClientCert() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunSslVpnClientCertCreate,
Read: resourceAliyunSslVpnClientCertRead,
Update: resourceAliyunSslVpnClientCertUpdate,
Delete: resourceAliyunSslVpnClientCertDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"ssl_vpn_server_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 128),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"ca_cert": {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
},
"client_cert": {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
},
"client_key": {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
},
"client_config": {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
},
},
}
}
func resourceAliyunSslVpnClientCertCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpnGatewayService := VpnGatewayService{client}
request := vpc.CreateCreateSslVpnClientCertRequest()
request.RegionId = string(client.Region)
request.SslVpnServerId = d.Get("ssl_vpn_server_id").(string)
if v := d.Get("name").(string); v != "" {
request.Name = v
}
request.ClientToken = buildClientToken(request.GetActionName())
var response *vpc.CreateSslVpnClientCertResponse
err := resource.Retry(3*time.Minute, func() *resource.RetryError {
args := *request
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.CreateSslVpnClientCert(&args)
})
if err != nil {
if IsExpectedErrors(err, []string{"VpnGateway.Configuring"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*vpc.CreateSslVpnClientCertResponse)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ssl_vpn_client_cert", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetId(response.SslVpnClientCertId)
err = vpnGatewayService.WaitForSslVpnClientCert(d.Id(), Ssl_Cert_Normal, DefaultTimeout)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return resourceAliyunSslVpnClientCertRead(d, meta)
}
func resourceAliyunSslVpnClientCertRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpnGatewayService := VpnGatewayService{client}
object, err := vpnGatewayService.DescribeSslVpnClientCert(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", object.Name)
d.Set("status", object.Status)
d.Set("ssl_vpn_server_id", object.SslVpnServerId)
d.Set("ca_cert", object.CaCert)
d.Set("client_cert", object.ClientCert)
d.Set("client_key", object.ClientKey)
d.Set("client_config", object.ClientConfig)
return nil
}
func resourceAliyunSslVpnClientCertUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := vpc.CreateModifySslVpnClientCertRequest()
request.RegionId = client.RegionId
request.SslVpnClientCertId = d.Id()
request.Name = d.Get("name").(string)
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.ModifySslVpnClientCert(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return resourceAliyunSslVpnClientCertRead(d, meta)
}
func resourceAliyunSslVpnClientCertDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpnGatewayService := VpnGatewayService{client}
request := vpc.CreateDeleteSslVpnClientCertRequest()
request.RegionId = client.RegionId
request.SslVpnClientCertId = d.Id()
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DeleteSslVpnClientCert(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"VpnGateway.Configuring"}) {
return resource.RetryableError(err)
} else {
return resource.NonRetryableError(err)
}
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidSslVpnClientCertId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(vpnGatewayService.WaitForSslVpnClientCert(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliyunSslVpnServer() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunSslVpnServerCreate,
Read: resourceAliyunSslVpnServerRead,
Update: resourceAliyunSslVpnServerUpdate,
Delete: resourceAliyunSslVpnServerDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"vpn_gateway_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 128),
},
"client_ip_pool": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validateCIDRNetworkAddress,
},
"local_subnet": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validateVpnCIDRNetworkAddress,
},
"protocol": {
Type: schema.TypeString,
Optional: true,
Default: VPN_UDP_PROTO,
ValidateFunc: validation.StringInSlice([]string{VPN_UDP_PROTO, VPN_TCP_PROTO}, false),
},
"cipher": {
Type: schema.TypeString,
Optional: true,
Default: SSL_VPN_ENC_AES_128,
ValidateFunc: validation.StringInSlice([]string{SSL_VPN_ENC_AES_128, SSL_VPN_ENC_AES_192, SSL_VPN_ENC_AES_256, SSL_VPN_ENC_NONE}, false),
},
"port": {
Type: schema.TypeInt,
Optional: true,
Default: 1194,
ValidateFunc: validateSslVpnPortValue([]int{22, 2222, 22222, 9000, 9001, 9002, 7505, 80, 443, 53, 68, 123, 4510, 4560, 500, 4500}),
},
"compress": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"connections": {
Type: schema.TypeInt,
Computed: true,
},
"max_connections": {
Type: schema.TypeInt,
Computed: true,
},
"internet_ip": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAliyunSslVpnServerCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpnGatewayService := VpnGatewayService{client}
request := vpc.CreateCreateSslVpnServerRequest()
request.RegionId = string(client.Region)
request.VpnGatewayId = d.Get("vpn_gateway_id").(string)
request.ClientIpPool = d.Get("client_ip_pool").(string)
request.LocalSubnet = d.Get("local_subnet").(string)
request.Name = d.Get("name").(string)
request.Proto = d.Get("protocol").(string)
request.Cipher = d.Get("cipher").(string)
request.Port = requests.NewInteger(d.Get("port").(int))
request.Compress = requests.NewBoolean(d.Get("compress").(bool))
request.ClientToken = buildClientToken(request.GetActionName())
var response *vpc.CreateSslVpnServerResponse
err := resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.CreateSslVpnServer(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"VpnGateway.Configuring"}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*vpc.CreateSslVpnServerResponse)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_ssl_vpn_server", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetId(response.SslVpnServerId)
err = vpnGatewayService.WaitForSslVpnServer(d.Id(), Null, DefaultTimeout)
if err != nil {
return WrapError(err)
}
return resourceAliyunSslVpnServerRead(d, meta)
}
func resourceAliyunSslVpnServerRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpnGatewayService := VpnGatewayService{client}
object, err := vpnGatewayService.DescribeSslVpnServer(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return err
}
d.Set("vpn_gateway_id", object.VpnGatewayId)
d.Set("name", object.Name)
d.Set("local_subnet", object.LocalSubnet)
d.Set("client_ip_pool", object.ClientIpPool)
d.Set("cipher", object.Cipher)
d.Set("protocol", object.Proto)
d.Set("port", object.Port)
d.Set("compress", object.Compress)
d.Set("connections", object.Connections)
d.Set("max_connections", object.MaxConnections)
d.Set("internet_ip", object.InternetIp)
return nil
}
func resourceAliyunSslVpnServerUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := vpc.CreateModifySslVpnServerRequest()
request.RegionId = client.RegionId
request.SslVpnServerId = d.Id()
if d.HasChange("name") {
request.Name = d.Get("name").(string)
}
request.ClientIpPool = d.Get("client_ip_pool").(string)
request.LocalSubnet = d.Get("local_subnet").(string)
if d.HasChange("protocol") {
request.Proto = d.Get("protocol").(string)
}
if d.HasChange("cipher") {
request.Cipher = d.Get("cipher").(string)
}
if d.HasChange("port") {
request.Port = requests.NewInteger(d.Get("port").(int))
}
if d.HasChange("compress") {
request.Compress = requests.NewBoolean(d.Get("compress").(bool))
}
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.ModifySslVpnServer(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"VpnGateway.Configuring"}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return resourceAliyunSslVpnServerRead(d, meta)
}
func resourceAliyunSslVpnServerDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpnGatewayService := VpnGatewayService{client}
request := vpc.CreateDeleteSslVpnServerRequest()
request.RegionId = client.RegionId
request.SslVpnServerId = d.Id()
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DeleteSslVpnServer(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"VpnGateway.Configuring"}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidSslVpnServerId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(vpnGatewayService.WaitForSslVpnServer(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudTsdbInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudTsdbInstanceCreate,
Read: resourceAlicloudTsdbInstanceRead,
Update: resourceAlicloudTsdbInstanceUpdate,
Delete: resourceAlicloudTsdbInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(31 * time.Minute),
Update: schema.DefaultTimeout(31 * time.Minute),
},
Schema: map[string]*schema.Schema{
"app_key": {
Type: schema.TypeString,
Optional: true,
},
"disk_category": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"cloud_efficiency", "cloud_essd", "cloud_ssd"}, false),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return d.Get("engine_type").(string) != "tsdb_influxdb"
},
},
"duration": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"engine_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"tsdb_influxdb", "tsdb_tsdb"}, false),
},
"instance_alias": {
Type: schema.TypeString,
Optional: true,
},
"instance_class": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"influxdata.n1.16xlarge", "influxdata.n1.16xlarge_ha", "influxdata.n1.2xlarge", "influxdata.n1.2xlarge_ha", "influxdata.n1.4xlarge", "influxdata.n1.4xlarge_ha", "influxdata.n1.8xlarge", "influxdata.n1.8xlarge_ha", "influxdata.n1.mxlarge", "influxdata.n1.mxlarge_ha", "influxdata.n1.xlarge", "influxdata.n1.xlarge_ha", "tsdb.12x.standard", "tsdb.1x.basic", "tsdb.24x.standard", "tsdb.3x.basic", "tsdb.48x.large", "tsdb.4x.basic", "tsdb.96x.large", "tsdb.iot.1x.small"}, false),
},
"instance_storage": {
Type: schema.TypeString,
Required: true,
},
"payment_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PayAsYouGo", "Subscription"}, false),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vswitch_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudTsdbInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
hitsdbService := HitsdbService{client}
var response map[string]interface{}
action := "CreateHiTSDBInstance"
request := make(map[string]interface{})
conn, err := client.NewHitsdbClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("app_key"); ok {
request["AppKey"] = v
}
if v, ok := d.GetOk("disk_category"); ok {
request["DiskCategory"] = v
}
if v, ok := d.GetOk("duration"); ok {
request["Duration"] = v
}
if v, ok := d.GetOk("engine_type"); ok {
request["EngineType"] = v
}
if v, ok := d.GetOk("instance_alias"); ok {
request["InstanceAlias"] = v
}
request["InstanceClass"] = d.Get("instance_class")
request["InstanceStorage"] = d.Get("instance_storage")
request["PayType"] = convertTsdbInstancePaymentTypeRequest(d.Get("payment_type").(string))
if request["PayType"].(string) == "PREPAY" {
request["PricingCycle"] = "Month"
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("zone_id"); ok {
request["ZoneId"] = v
}
vswitchId := Trim(d.Get("vswitch_id").(string))
if vswitchId != "" {
vpcService := VpcService{client}
vsw, err := vpcService.DescribeVSwitchWithTeadsl(vswitchId)
if err != nil {
return WrapError(err)
}
request["VPCId"] = vsw["VpcId"]
request["VSwitchId"] = vswitchId
if v, ok := request["ZoneId"].(string); !ok || v == "" {
request["ZoneId"] = vsw["ZoneId"]
}
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("CreateHiTSDBInstance")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_tsdb_instance", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetId(fmt.Sprint(response["InstanceId"]))
stateConf := BuildStateConf([]string{}, []string{"ACTIVATION"}, d.Timeout(schema.TimeoutCreate), 30*time.Second, hitsdbService.TsdbInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudTsdbInstanceRead(d, meta)
}
func resourceAlicloudTsdbInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
hitsdbService := HitsdbService{client}
object, err := hitsdbService.DescribeTsdbInstance(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_tsdb_instance hitsdbService.DescribeTsdbInstance Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("disk_category", object["DiskCategory"])
d.Set("engine_type", object["EngineType"])
d.Set("instance_alias", object["InstanceAlias"])
d.Set("instance_class", object["InstanceClass"])
d.Set("instance_storage", object["InstanceStorage"])
d.Set("payment_type", convertTsdbInstancePaymentTypeResponse(object["PaymentType"].(string)))
d.Set("status", object["Status"])
d.Set("vswitch_id", object["VswitchId"])
d.Set("zone_id", object["ZoneId"])
return nil
}
func resourceAlicloudTsdbInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
hitsdbService := HitsdbService{client}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"InstanceId": d.Id(),
}
if d.HasChange("instance_alias") {
update = true
}
request["InstanceAlias"] = d.Get("instance_alias")
if update {
if _, ok := d.GetOk("app_key"); ok {
request["AppKey"] = d.Get("app_key")
}
action := "RenameHiTSDBInstanceAlias"
conn, err := client.NewHitsdbClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("instance_alias")
}
update = false
modifyHiTSDBInstanceClassReq := map[string]interface{}{
"InstanceId": d.Id(),
}
if d.HasChange("instance_class") {
update = true
}
modifyHiTSDBInstanceClassReq["InstanceClass"] = d.Get("instance_class")
if d.HasChange("instance_storage") {
update = true
}
modifyHiTSDBInstanceClassReq["InstanceStorage"] = d.Get("instance_storage")
if update {
if _, ok := d.GetOk("app_key"); ok {
modifyHiTSDBInstanceClassReq["AppKey"] = d.Get("app_key")
}
action := "ModifyHiTSDBInstanceClass"
conn, err := client.NewHitsdbClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 30*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-01"), StringPointer("AK"), nil, modifyHiTSDBInstanceClassReq, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"OperationDenied.OrderProcessingError"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, modifyHiTSDBInstanceClassReq)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"ACTIVATION"}, d.Timeout(schema.TimeoutUpdate), 30*time.Second, hitsdbService.TsdbInstanceStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("instance_class")
d.SetPartial("instance_storage")
}
d.Partial(false)
return resourceAlicloudTsdbInstanceRead(d, meta)
}
func resourceAlicloudTsdbInstanceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteHiTSDBInstance"
var response map[string]interface{}
conn, err := client.NewHitsdbClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"InstanceId": d.Id(),
}
if v, ok := d.GetOk("app_key"); ok {
request["AppKey"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"Instance.IsNotAvailable", "Instance.IsNotPostPay"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func convertTsdbInstancePaymentTypeRequest(source string) string {
switch source {
case "PayAsYouGo":
return "POSTPAY"
case "Subscription":
return "PREPAY"
}
return source
}
func convertTsdbInstancePaymentTypeResponse(source string) string {
switch source {
case "POSTPAY":
return "PayAsYouGo"
case "PREPAY":
return "Subscription"
}
return source
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudVideoSurveillanceSystemGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudVideoSurveillanceSystemGroupCreate,
Read: resourceAlicloudVideoSurveillanceSystemGroupRead,
Update: resourceAlicloudVideoSurveillanceSystemGroupUpdate,
Delete: resourceAlicloudVideoSurveillanceSystemGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"group_name": {
Type: schema.TypeString,
Required: true,
},
"in_protocol": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"gb28181", "rtmp"}, false),
},
"out_protocol": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"flv", "rtmp", "hls"}, false),
},
"play_domain": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"push_domain": {
Type: schema.TypeString,
Required: true,
},
"callback": {
Type: schema.TypeString,
Optional: true,
},
"enabled": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"capture_image": {
Type: schema.TypeInt,
Computed: true,
},
"capture_interval": {
Type: schema.TypeInt,
Computed: true,
},
"capture_oss_bucket": {
Type: schema.TypeString,
Computed: true,
},
"capture_oss_path": {
Type: schema.TypeString,
Computed: true,
},
"capture_video": {
Type: schema.TypeInt,
Computed: true,
},
"lazy_pull": {
Type: schema.TypeBool,
Computed: true,
},
"status": {
Type: schema.TypeBool,
Computed: true,
},
},
}
}
func resourceAlicloudVideoSurveillanceSystemGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateGroup"
request := make(map[string]interface{})
conn, err := client.NewVsClient()
if err != nil {
return WrapError(err)
}
request["Region"] = client.RegionId
request["InProtocol"] = d.Get("in_protocol")
request["OutProtocol"] = d.Get("out_protocol")
request["PlayDomain"] = d.Get("play_domain")
request["PushDomain"] = d.Get("push_domain")
request["Name"] = d.Get("group_name")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_video_surveillance_system_group", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["Id"]))
return resourceAlicloudVideoSurveillanceSystemGroupUpdate(d, meta)
}
func resourceAlicloudVideoSurveillanceSystemGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vsService := VsService{client}
object, err := vsService.DescribeVideoSurveillanceSystemGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_video_surveillance_system_group vsService.DescribeVideoSurveillanceSystemGroup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("callback", object["Callback"])
d.Set("description", object["Description"])
d.Set("enabled", object["Enabled"])
d.Set("group_name", object["Name"])
d.Set("lazy_pull", object["LazyPull"])
d.Set("in_protocol", object["InProtocol"])
d.Set("out_protocol", object["OutProtocol"])
d.Set("play_domain", object["PlayDomain"])
d.Set("push_domain", object["PushDomain"])
d.Set("capture_oss_bucket", object["CaptureOssBucket"])
d.Set("capture_oss_path", object["CaptureOssPath"])
d.Set("capture_video", object["CaptureVideo"])
d.Set("capture_image", object["CaptureImage"])
d.Set("capture_interval", object["CaptureInterval"])
return nil
}
func resourceAlicloudVideoSurveillanceSystemGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
request := map[string]interface{}{
"Id": d.Id(),
}
if d.HasChange("callback") {
update = true
if v, ok := d.GetOk("callback"); ok {
request["Callback"] = v
}
}
if d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
}
if d.HasChange("enabled") || d.IsNewResource() {
update = true
if v, ok := d.GetOkExists("enabled"); ok {
request["Enabled"] = v
}
}
if d.HasChange("group_name") {
update = true
if v, ok := d.GetOk("group_name"); ok {
request["Name"] = v
}
}
if d.HasChange("in_protocol") {
update = true
if v, ok := d.GetOk("in_protocol"); ok {
request["InProtocol"] = v
}
}
if d.HasChange("out_protocol") {
update = true
if v, ok := d.GetOk("out_protocol"); ok {
request["OutProtocol"] = v
}
}
if update {
action := "ModifyGroup"
conn, err := client.NewVsClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"2001"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudVideoSurveillanceSystemGroupRead(d, meta)
}
func resourceAlicloudVideoSurveillanceSystemGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
conn, err := client.NewVsClient()
action := "DeleteGroup"
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"Id": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudVodDomain() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudVodDomainCreate,
Read: resourceAlicloudVodDomainRead,
Update: resourceAlicloudVodDomainUpdate,
Delete: resourceAlicloudVodDomainDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"domain_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"sources": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"source_content": {
Type: schema.TypeString,
Required: true,
},
"source_port": {
Type: schema.TypeString,
Required: true,
},
"source_priority": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"20", "30"}, false),
},
"source_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"ipaddr", "domain", "oss"}, false),
},
},
},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"gmt_modified": {
Type: schema.TypeString,
Computed: true,
},
"gmt_created": {
Type: schema.TypeString,
Computed: true,
},
"cname": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"weight": {
Type: schema.TypeString,
Computed: true,
},
"ssl_pub": {
Type: schema.TypeString,
Computed: true,
},
"ssl_protocol": {
Type: schema.TypeString,
Computed: true,
},
"cert_name": {
Type: schema.TypeString,
Computed: true,
},
"scope": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"domestic", "overseas", "global"}, false),
Default: "domestic",
},
"top_level_domain": {
Type: schema.TypeString,
Optional: true,
},
"check_url": {
Type: schema.TypeString,
Optional: true,
},
"tags": tagsSchema(),
},
}
}
func resourceAlicloudVodDomainCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AddVodDomain"
request := make(map[string]interface{})
conn, err := client.NewVodClient()
if err != nil {
return WrapError(err)
}
request["DomainName"] = d.Get("domain_name")
if v, ok := d.GetOk("check_url"); ok {
request["CheckUrl"] = v
}
if v, ok := d.GetOk("scope"); ok {
request["Scope"] = v
}
if v, ok := d.GetOk("top_level_domain"); ok {
request["TopLevelDomain"] = v
}
sourcesMaps := make([]map[string]interface{}, 0)
for _, sources := range d.Get("sources").(*schema.Set).List() {
sourcesArg := sources.(map[string]interface{})
sourcesMap := map[string]interface{}{}
sourcesMap["content"] = sourcesArg["source_content"]
sourcesMap["priority"] = sourcesArg["source_priority"]
sourcesMap["type"] = sourcesArg["source_type"]
sourcesMap["port"] = sourcesArg["source_port"]
sourcesMaps = append(sourcesMaps, sourcesMap)
}
if v, err := convertArrayObjectToJsonString(sourcesMaps); err == nil {
request["Sources"] = v
} else {
return WrapError(err)
}
if v, ok := d.GetOk("top_level_domain"); ok {
request["TopLevelDomain"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-03-21"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_vod_domain", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["DomainName"]))
return resourceAlicloudVodDomainUpdate(d, meta)
}
func resourceAlicloudVodDomainRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vodService := VodService{client}
object, err := vodService.DescribeVodDomain(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_vod_domain vodService.DescribeVodDomain Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("domain_name", d.Id())
d.Set("scope", object["Scope"])
d.Set("status", object["DomainStatus"])
d.Set("gmt_modified", object["GmtModified"])
d.Set("gmt_created", object["GmtCreated"])
d.Set("weight", object["Weight"])
d.Set("ssl_pub", object["SSLPub"])
d.Set("ssl_protocol", object["SSLProtocol"])
d.Set("cert_name", object["CertName"])
d.Set("cname", object["Cname"])
if v, ok := object["Sources"].(map[string]interface{})["Source"].([]interface{}); ok {
source := make([]map[string]interface{}, 0)
for _, val := range v {
item := val.(map[string]interface{})
temp := map[string]interface{}{
"source_content": item["Content"],
"source_port": item["Port"],
"source_priority": item["Priority"],
"source_type": item["Type"],
}
source = append(source, temp)
}
if err := d.Set("sources", source); err != nil {
return WrapError(err)
}
}
return nil
}
func resourceAlicloudVodDomainUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vodService := VodService{client}
var response map[string]interface{}
update := false
request := map[string]interface{}{
"DomainName": d.Id(),
}
if d.HasChange("sources") {
update = true
sourcesMaps := make([]map[string]interface{}, 0)
for _, sources := range d.Get("sources").(*schema.Set).List() {
sourcesArg := sources.(map[string]interface{})
sourcesMap := map[string]interface{}{}
sourcesMap["content"] = sourcesArg["source_content"]
sourcesMap["priority"] = sourcesArg["source_priority"]
sourcesMap["type"] = sourcesArg["source_type"]
sourcesMap["port"] = sourcesArg["source_port"]
sourcesMaps = append(sourcesMaps, sourcesMap)
}
if v, err := convertArrayObjectToJsonString(sourcesMaps); err == nil {
request["Sources"] = v
} else {
return WrapError(err)
}
}
if d.HasChange("top_level_domain") {
update = true
if v, ok := d.GetOk("top_level_domain"); ok {
request["TopLevelDomain"] = v
}
}
if update {
action := "UpdateVodDomain"
conn, err := client.NewVodClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-03-21"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"3", "2001"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if err := vodService.SetResourceTags(d, "DOMAIN"); err != nil {
return WrapError(err)
}
stateConf := BuildStateConf([]string{"configuring"}, []string{"online"}, d.Timeout(schema.TimeoutDelete), 5*time.Second, vodService.VodStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudVodDomainRead(d, meta)
}
func resourceAlicloudVodDomainDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vodService := VodService{client}
action := "DeleteVodDomain"
var response map[string]interface{}
conn, err := client.NewVodClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DomainName": d.Id(),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-03-21"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"2001"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"deleting"}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, vodService.VodStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudVpc() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudVpcCreate,
Read: resourceAlicloudVpcRead,
Update: resourceAlicloudVpcUpdate,
Delete: resourceAlicloudVpcDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"cidr_block": {
Type: schema.TypeString,
Optional: true,
Default: "172.16.0.0/12",
ValidateFunc: validateCIDRNetworkAddress,
ConflictsWith: []string{"enable_ipv6"},
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"enable_ipv6": {
Type: schema.TypeBool,
Optional: true,
ConflictsWith: []string{"cidr_block"},
},
"ipv6_cidr_block": {
Type: schema.TypeString,
Computed: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"route_table_id": {
Type: schema.TypeString,
Computed: true,
},
"router_table_id": {
Type: schema.TypeString,
Computed: true,
Deprecated: "Attribute router_table_id has been deprecated and replaced with route_table_id.",
},
"router_id": {
Type: schema.TypeString,
Computed: true,
},
"secondary_cidr_blocks": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
"user_cidrs": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
ForceNew: true,
},
"vpc_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"name"},
ValidateFunc: validateNormalName,
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Field 'name' has been deprecated from provider version 1.119.0. New field 'vpc_name' instead.",
ConflictsWith: []string{"vpc_name"},
ValidateFunc: validateNormalName,
},
},
}
}
func resourceAlicloudVpcCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
action := "CreateVpc"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("cidr_block"); ok {
request["CidrBlock"] = v
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
if v, ok := d.GetOkExists("enable_ipv6"); ok {
request["EnableIpv6"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("user_cidrs"); ok && v != nil {
request["UserCidr"] = convertListToCommaSeparate(v.([]interface{}))
}
if v, ok := d.GetOk("vpc_name"); ok {
request["VpcName"] = v
} else if v, ok := d.GetOk("name"); ok {
request["VpcName"] = v
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("CreateVpc")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"TaskConflict", "Throttling", "UnknownError"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_vpc", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["VpcId"]))
stateConf := BuildStateConf([]string{"Pending"}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, vpcService.VpcStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudVpcUpdate(d, meta)
}
func resourceAlicloudVpcRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeVpc(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_vpc_vpc vpcService.DescribeVpc Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("cidr_block", object["CidrBlock"])
d.Set("description", object["Description"])
d.Set("ipv6_cidr_block", object["Ipv6CidrBlock"])
d.Set("router_id", object["VRouterId"])
err = d.Set("secondary_cidr_blocks", object["SecondaryCidrBlocks"].(map[string]interface{})["SecondaryCidrBlock"])
d.Set("status", object["Status"])
if v, ok := object["Tags"].(map[string]interface{}); ok {
vv := tagsToMap(v["Tag"])
d.Set("tags", vv)
}
err = d.Set("user_cidrs", object["UserCidrs"].(map[string]interface{})["UserCidr"])
d.Set("vpc_name", object["VpcName"])
d.Set("name", object["VpcName"])
describeRouteTableListObject, err := vpcService.DescribeRouteTableList(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("resource_group_id", describeRouteTableListObject["ResourceGroupId"])
d.Set("route_table_id", describeRouteTableListObject["RouteTableId"])
d.Set("router_table_id", describeRouteTableListObject["RouteTableId"])
return nil
}
func resourceAlicloudVpcUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
d.Partial(true)
if err := vpcService.SetInstanceSecondaryCidrBlocks(d); err != nil {
return WrapError(err)
}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if d.HasChange("tags") {
if err := vpcService.SetResourceTags(d, "vpc"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
update := false
moveResourceGroupReq := map[string]interface{}{
"ResourceId": d.Id(),
}
moveResourceGroupReq["RegionId"] = client.RegionId
if !d.IsNewResource() && d.HasChange("resource_group_id") {
update = true
}
moveResourceGroupReq["NewResourceGroupId"] = d.Get("resource_group_id")
moveResourceGroupReq["ResourceType"] = "vpc"
if update {
action := "MoveResourceGroup"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, moveResourceGroupReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, moveResourceGroupReq)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("resource_group_id")
}
update = false
modifyVpcAttributeReq := map[string]interface{}{
"VpcId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("cidr_block") {
update = true
modifyVpcAttributeReq["CidrBlock"] = d.Get("cidr_block")
}
if !d.IsNewResource() && d.HasChange("description") {
update = true
modifyVpcAttributeReq["Description"] = d.Get("description")
}
modifyVpcAttributeReq["RegionId"] = client.RegionId
if !d.IsNewResource() && d.HasChange("vpc_name") {
update = true
modifyVpcAttributeReq["VpcName"] = d.Get("vpc_name")
}
if !d.IsNewResource() && d.HasChange("name") {
update = true
modifyVpcAttributeReq["VpcName"] = d.Get("name")
}
if update {
if _, ok := d.GetOkExists("enable_ipv6"); ok {
modifyVpcAttributeReq["EnableIPv6"] = d.Get("enable_ipv6")
}
action := "ModifyVpcAttribute"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, modifyVpcAttributeReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, modifyVpcAttributeReq)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("cidr_block")
d.SetPartial("description")
d.SetPartial("name")
d.SetPartial("vpc_name")
}
d.Partial(false)
return resourceAlicloudVpcRead(d, meta)
}
func resourceAlicloudVpcDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
action := "DeleteVpc"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"VpcId": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Forbidden.VpcNotFound", "InvalidVpcID.NotFound", "InvalidVpcId.NotFound"}) {
return nil
}
wait()
return resource.RetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"Pending"}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, vpcService.VpcStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudVpcBgpGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudVpcBgpGroupCreate,
Read: resourceAlicloudVpcBgpGroupRead,
Update: resourceAlicloudVpcBgpGroupUpdate,
Delete: resourceAlicloudVpcBgpGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
Delete: schema.DefaultTimeout(5 * time.Minute),
Update: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"auth_key": {
Type: schema.TypeString,
Optional: true,
},
"bgp_group_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.All(validation.StringMatch(regexp.MustCompile(`^[a-zA-Z][A-Za-z0-9._-]{1,127}$`), "The name must be `2` to `128` characters in length and can contain digits, periods (.), underscores (_), and hyphens (-)."), validation.StringDoesNotMatch(regexp.MustCompile(`(^http://.*)|(^https://.*)`), "It cannot begin with \"http://\", \"https://\".")),
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.All(validation.StringLenBetween(2, 256), validation.StringDoesNotMatch(regexp.MustCompile(`(^http://.*)|(^https://.*)`), "It cannot begin with \"http://\", \"https://\".")),
},
"is_fake_asn": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"local_asn": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"peer_asn": {
Type: schema.TypeInt,
Required: true,
},
"router_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudVpcBgpGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateBgpGroup"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("auth_key"); ok {
request["AuthKey"] = v
}
if v, ok := d.GetOk("bgp_group_name"); ok {
request["Name"] = v
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOkExists("is_fake_asn"); ok {
request["IsFakeAsn"] = v
}
if v, ok := d.GetOk("local_asn"); ok {
request["LocalAsn"] = v
}
request["PeerAsn"] = d.Get("peer_asn")
request["RegionId"] = client.RegionId
request["RouterId"] = d.Get("router_id")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("CreateBgpGroup")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_vpc_bgp_group", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["BgpGroupId"]))
vpcService := VpcService{client}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, vpcService.VpcBgpGroupStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudVpcBgpGroupRead(d, meta)
}
func resourceAlicloudVpcBgpGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeVpcBgpGroup(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_vpc_bgp_group vpcService.DescribeVpcBgpGroup Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("auth_key", object["AuthKey"])
d.Set("bgp_group_name", object["Name"])
d.Set("description", object["Description"])
d.Set("local_asn", formatInt(object["LocalAsn"]))
d.Set("peer_asn", formatInt(object["PeerAsn"]))
d.Set("router_id", object["RouterId"])
d.Set("is_fake_asn", object["IsFake"])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudVpcBgpGroupUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
update := false
request := map[string]interface{}{
"BgpGroupId": d.Id(),
}
request["RegionId"] = client.RegionId
if d.HasChange("auth_key") {
update = true
if v, ok := d.GetOk("auth_key"); ok {
request["AuthKey"] = v
}
}
if d.HasChange("bgp_group_name") {
update = true
if v, ok := d.GetOk("bgp_group_name"); ok {
request["Name"] = v
}
}
if d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
}
if d.HasChange("local_asn") {
update = true
if v, ok := d.GetOk("local_asn"); ok {
request["LocalAsn"] = v
}
}
if d.HasChange("peer_asn") {
update = true
request["PeerAsn"] = d.Get("peer_asn")
}
if update {
if v, ok := d.GetOkExists("is_fake_asn"); ok {
request["IsFakeAsn"] = v
}
action := "ModifyBgpGroupAttribute"
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("ModifyBgpGroupAttribute")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, vpcService.VpcBgpGroupStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudVpcBgpGroupRead(d, meta)
}
func resourceAlicloudVpcBgpGroupDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
action := "DeleteBgpGroup"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"BgpGroupId": d.Id(),
}
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("DeleteBgpGroup")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, vpcService.VpcBgpGroupStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudVpcBgpNetwork() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudVpcBgpNetworkCreate,
Read: resourceAlicloudVpcBgpNetworkRead,
Delete: resourceAlicloudVpcBgpNetworkDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
Delete: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"dst_cidr_block": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"router_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudVpcBgpNetworkCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AddBgpNetwork"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request["DstCidrBlock"] = d.Get("dst_cidr_block")
request["RegionId"] = client.RegionId
request["RouterId"] = d.Get("router_id")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("AddBgpNetwork")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_vpc_bgp_network", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["RouterId"], ":", request["DstCidrBlock"]))
vpcService := VpcService{client}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, vpcService.VpcBgpNetworkStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudVpcBgpNetworkRead(d, meta)
}
func resourceAlicloudVpcBgpNetworkRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeVpcBgpNetwork(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_vpc_bgp_network vpcService.DescribeVpcBgpNetwork Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("dst_cidr_block", object["DstCidrBlock"])
d.Set("router_id", object["RouterId"])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudVpcBgpNetworkDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
vpcService := VpcService{client}
action := "DeleteBgpNetwork"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DstCidrBlock": parts[1],
"RouterId": parts[0],
}
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("DeleteBgpNetwork")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, vpcService.VpcBgpNetworkStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudVpcBgpPeer() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudVpcBgpPeerCreate,
Read: resourceAlicloudVpcBgpPeerRead,
Update: resourceAlicloudVpcBgpPeerUpdate,
Delete: resourceAlicloudVpcBgpPeerDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
Delete: schema.DefaultTimeout(5 * time.Minute),
Update: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"bfd_multi_hop": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(1, 255),
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("enable_bfd"); ok && fmt.Sprint(v) == "true" {
return false
}
return true
},
},
"bgp_group_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"enable_bfd": {
Type: schema.TypeBool,
Optional: true,
},
"ip_version": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"peer_ip_address": {
Type: schema.TypeString,
Optional: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudVpcBgpPeerCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateBgpPeer"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("bfd_multi_hop"); ok {
request["BfdMultiHop"] = v
}
request["BgpGroupId"] = d.Get("bgp_group_id")
if v, ok := d.GetOkExists("enable_bfd"); ok {
request["EnableBfd"] = v
}
if v, ok := d.GetOk("ip_version"); ok {
request["IpVersion"] = v
}
if v, ok := d.GetOk("peer_ip_address"); ok {
request["PeerIpAddress"] = v
}
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("CreateBgpPeer")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_vpc_bgp_peer", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["BgpPeerId"]))
vpcService := VpcService{client}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, vpcService.VpcBgpPeerStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudVpcBgpPeerRead(d, meta)
}
func resourceAlicloudVpcBgpPeerRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeVpcBgpPeer(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_vpc_bgp_peer vpcService.DescribeVpcBgpPeer Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
if v, ok := object["BfdMultiHop"]; ok && fmt.Sprint(v) != "0" {
d.Set("bfd_multi_hop", formatInt(v))
}
d.Set("bgp_group_id", object["BgpGroupId"])
d.Set("enable_bfd", object["EnableBfd"])
d.Set("ip_version", object["IpVersion"])
d.Set("peer_ip_address", object["PeerIpAddress"])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudVpcBgpPeerUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
update := false
request := map[string]interface{}{
"BgpPeerId": d.Id(),
}
request["RegionId"] = client.RegionId
if d.HasChange("bfd_multi_hop") {
update = true
if v, ok := d.GetOk("bfd_multi_hop"); ok {
request["BfdMultiHop"] = v
}
}
if d.HasChange("enable_bfd") {
update = true
if v, ok := d.GetOkExists("enable_bfd"); ok {
request["EnableBfd"] = v
}
}
if d.HasChange("peer_ip_address") {
update = true
if v, ok := d.GetOk("peer_ip_address"); ok {
request["PeerIpAddress"] = v
}
}
if update {
action := "ModifyBgpPeerAttribute"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("ModifyBgpPeerAttribute")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, vpcService.VpcBgpPeerStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudVpcBgpPeerRead(d, meta)
}
func resourceAlicloudVpcBgpPeerDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
action := "DeleteBgpPeer"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"BgpPeerId": d.Id(),
}
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("DeleteBgpPeer")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, vpcService.VpcBgpPeerStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudVpcDhcpOptionsSet() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudVpcDhcpOptionsSetCreate,
Read: resourceAlicloudVpcDhcpOptionsSetRead,
Update: resourceAlicloudVpcDhcpOptionsSetUpdate,
Delete: resourceAlicloudVpcDhcpOptionsSetDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(2 * time.Minute),
Delete: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(2 * time.Minute),
},
Schema: map[string]*schema.Schema{
"associate_vpcs": {
Type: schema.TypeSet,
Optional: true,
Deprecated: "Field 'associate_vpcs' has been deprecated from provider version 1.153.0 and it will be removed in the future version. Please use the new resource 'alicloud_vpc_dhcp_options_set_attachment' to attach DhcpOptionsSet and Vpc.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"vpc_id": {
Type: schema.TypeString,
Optional: true,
},
"associate_status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"dhcp_options_set_description": {
Type: schema.TypeString,
Optional: true,
},
"dhcp_options_set_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile("^[a-zA-Z\u4E00-\u9FA5][\u4E00-\u9FA5A-Za-z0-9_-]{2,128}$"), "The name must be 2 to 128 characters in length and can contain letters, Chinese characters, digits, underscores (_), and hyphens (-). It must start with a letter or a Chinese character."),
},
"domain_name": {
Type: schema.TypeString,
Optional: true,
},
"domain_name_servers": {
Type: schema.TypeString,
Optional: true,
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"owner_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudVpcDhcpOptionsSetCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateDhcpOptionsSet"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("dhcp_options_set_description"); ok {
request["DhcpOptionsSetDescription"] = v
}
if v, ok := d.GetOk("dhcp_options_set_name"); ok {
request["DhcpOptionsSetName"] = v
}
if v, ok := d.GetOk("domain_name"); ok {
request["DomainName"] = v
}
if v, ok := d.GetOk("domain_name_servers"); ok {
request["DomainNameServers"] = v
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("CreateDhcpOptionsSet")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_vpc_dhcp_options_set", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["DhcpOptionsSetId"]))
vpcService := VpcService{client}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, vpcService.VpcDhcpOptionsSetStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudVpcDhcpOptionsSetUpdate(d, meta)
}
func resourceAlicloudVpcDhcpOptionsSetRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeVpcDhcpOptionsSet(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_vpc_dhcp_options_set vpcService.DescribeVpcDhcpOptionsSet Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
if associateVpcsList, ok := object["AssociateVpcs"]; ok && associateVpcsList != nil {
associateVpcsMaps := make([]map[string]interface{}, 0)
for _, associateVpcsListItem := range associateVpcsList.([]interface{}) {
if associateVpcsListItemMap, ok := associateVpcsListItem.(map[string]interface{}); ok {
associateVpcsListItemMap["associate_status"] = associateVpcsListItemMap["AssociateStatus"]
associateVpcsListItemMap["vpc_id"] = associateVpcsListItemMap["VpcId"]
associateVpcsMaps = append(associateVpcsMaps, associateVpcsListItemMap)
}
}
d.Set("associate_vpcs", associateVpcsMaps)
}
d.Set("dhcp_options_set_description", object["DhcpOptionsSetDescription"])
d.Set("dhcp_options_set_name", object["DhcpOptionsSetName"])
d.Set("domain_name", object["DhcpOptions"].(map[string]interface{})["DomainName"])
d.Set("domain_name_servers", object["DhcpOptions"].(map[string]interface{})["DomainNameServers"])
d.Set("owner_id", fmt.Sprint(formatInt(object["OwnerId"])))
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudVpcDhcpOptionsSetUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"DhcpOptionsSetId": d.Id(),
}
request["RegionId"] = client.RegionId
if d.HasChange("dhcp_options_set_description") {
update = true
if v, ok := d.GetOk("dhcp_options_set_description"); ok {
request["DhcpOptionsSetDescription"] = v
}
}
if d.HasChange("dhcp_options_set_name") {
update = true
if v, ok := d.GetOk("dhcp_options_set_name"); ok {
request["DhcpOptionsSetName"] = v
}
}
if d.HasChange("domain_name") {
update = true
if v, ok := d.GetOk("domain_name"); ok {
request["DomainName"] = v
}
}
if d.HasChange("domain_name_servers") {
update = true
if v, ok := d.GetOk("domain_name_servers"); ok {
request["DomainNameServers"] = v
}
}
if update {
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
action := "UpdateDhcpOptionsSetAttribute"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("UpdateDhcpOptionsSetAttribute")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, vpcService.VpcDhcpOptionsSetStateRefreshFunc(d.Id(), []string{"InUse"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("dhcp_options_set_description")
d.SetPartial("dhcp_options_set_name")
d.SetPartial("domain_name")
d.SetPartial("domain_name_servers")
}
d.Partial(false)
if d.HasChange("associate_vpcs") {
oldAssociateVpcs, newAssociateVpcs := d.GetChange("associate_vpcs")
oldAssociateVpcsSet := oldAssociateVpcs.(*schema.Set)
newAssociateVpcsSet := newAssociateVpcs.(*schema.Set)
removed := oldAssociateVpcsSet.Difference(newAssociateVpcsSet)
added := newAssociateVpcsSet.Difference(oldAssociateVpcsSet)
if removed.Len() > 0 {
action := "DetachDhcpOptionsSetFromVpc"
detachVpcDhcpOptionsSetRequest := map[string]interface{}{
"DhcpOptionsSetId": d.Id(),
}
detachVpcDhcpOptionsSetRequest["RegionId"] = client.RegionId
if _, ok := d.GetOkExists("dry_run"); ok {
detachVpcDhcpOptionsSetRequest["DryRun"] = d.Get("dry_run")
}
for _, associateVpcs := range removed.List() {
associateVpc := associateVpcs.(map[string]interface{})
detachVpcDhcpOptionsSetRequest["VpcId"] = associateVpc["vpc_id"].(string)
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("DetachDhcpOptionsSetFromVpc")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, detachVpcDhcpOptionsSetRequest, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, detachVpcDhcpOptionsSetRequest)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("associate_vpcs")
}
if added.Len() > 0 {
action := "AttachDhcpOptionsSetToVpc"
attachVpcDhcpOptionsSetRequest := map[string]interface{}{
"DhcpOptionsSetId": d.Id(),
}
attachVpcDhcpOptionsSetRequest["RegionId"] = client.RegionId
if _, ok := d.GetOkExists("dry_run"); ok {
attachVpcDhcpOptionsSetRequest["DryRun"] = d.Get("dry_run")
}
for _, associateVpcs := range added.List() {
associateVpc := associateVpcs.(map[string]interface{})
attachVpcDhcpOptionsSetRequest["VpcId"] = associateVpc["vpc_id"].(string)
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("AttachDhcpOptionsSetToVpc")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, attachVpcDhcpOptionsSetRequest, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, attachVpcDhcpOptionsSetRequest)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("associate_vpcs")
}
}
return resourceAlicloudVpcDhcpOptionsSetRead(d, meta)
}
func resourceAlicloudVpcDhcpOptionsSetDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteDhcpOptionsSet"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DhcpOptionsSetId": d.Id(),
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("DeleteDhcpOptionsSet")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectStatus.DhcpOptionsSet"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDhcpOptionsSetId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudVpcDhcpOptionsSetAttachement() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudVpcDhcpOptionsAttachmentCreate,
Read: resourceAlicloudVpcDhcpOptionsSetAttachmentRead,
Update: resourceAlicloudVpcDhcpOptionsSetAttachmentUpdate,
Delete: resourceAlicloudVpcDhcpOptionsSetAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(2 * time.Minute),
Delete: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"dhcp_options_set_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"vpc_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudVpcDhcpOptionsAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AttachDhcpOptionsSetToVpc"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request["RegionId"] = client.RegionId
request["DhcpOptionsSetId"] = d.Get("dhcp_options_set_id")
request["VpcId"] = d.Get("vpc_id")
request["ClientToken"] = buildClientToken(action)
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_vpc_dhcp_options_set_attachment", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["VpcId"], ":", request["DhcpOptionsSetId"]))
vpcService := VpcService{client}
stateConf := BuildStateConf([]string{"Pending"}, []string{"InUse"}, d.Timeout(schema.TimeoutCreate), 3*time.Second, vpcService.DescribeVpcDhcpOptionsSetAttachmentStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudVpcDhcpOptionsSetAttachmentRead(d, meta)
}
func resourceAlicloudVpcDhcpOptionsSetAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
object, err := vpcService.DescribeVpcDhcpOptionsSetAttachment(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_vpc_dhcp_options_set_attachment vpcService.DescribeVpcDhcpOptionsSetAttachment Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
if associateVpcsList, ok := object["AssociateVpcs"]; ok {
for _, associateVpcsListItem := range associateVpcsList.([]interface{}) {
if associateVpcsListItem != nil {
associateVpcsListItemMap, ok := associateVpcsListItem.(map[string]interface{})
if ok && associateVpcsListItemMap["VpcId"] == parts[0] {
d.Set("vpc_id", associateVpcsListItemMap["VpcId"])
d.Set("dhcp_options_set_id", parts[1])
d.Set("status", associateVpcsListItemMap["AssociateStatus"])
break
}
}
}
}
return nil
}
func resourceAlicloudVpcDhcpOptionsSetAttachmentUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return resourceAlicloudVpcDhcpOptionsSetAttachmentRead(d, meta)
}
func resourceAlicloudVpcDhcpOptionsSetAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DetachDhcpOptionsSetFromVpc"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"DhcpOptionsSetId": parts[1],
}
request["RegionId"] = client.RegionId
request["VpcId"] = d.Get("vpc_id")
request["ClientToken"] = buildClientToken(action)
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectStatus.DhcpOptionsSet"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDhcpOptionsSetId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
vpcService := VpcService{client}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutCreate), 5*time.Second, vpcService.VpcDhcpOptionsSetStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudVpcFlowLog() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudVpcFlowLogCreate,
Read: resourceAlicloudVpcFlowLogRead,
Update: resourceAlicloudVpcFlowLogUpdate,
Delete: resourceAlicloudVpcFlowLogDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
},
"flow_log_name": {
Type: schema.TypeString,
Optional: true,
},
"log_store_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"project_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"resource_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"resource_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"NetworkInterface", "VPC", "VSwitch"}, false),
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Active", "Inactive"}, false),
},
"traffic_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"All", "Allow", "Drop"}, false),
},
},
}
}
func resourceAlicloudVpcFlowLogCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
action := "CreateFlowLog"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("flow_log_name"); ok {
request["FlowLogName"] = v
}
request["LogStoreName"] = d.Get("log_store_name")
request["ProjectName"] = d.Get("project_name")
request["RegionId"] = client.RegionId
request["ResourceId"] = d.Get("resource_id")
request["ResourceType"] = d.Get("resource_type")
request["TrafficType"] = d.Get("traffic_type")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"TaskConflict", "UnknownError"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_vpc_flow_log", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["FlowLogId"]))
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, vpcService.VpcFlowLogStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudVpcFlowLogUpdate(d, meta)
}
func resourceAlicloudVpcFlowLogRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeVpcFlowLog(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_vpc_flow_log vpcService.DescribeVpcFlowLog Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", object["Description"])
d.Set("flow_log_name", object["FlowLogName"])
d.Set("log_store_name", object["LogStoreName"])
d.Set("project_name", object["ProjectName"])
d.Set("resource_id", object["ResourceId"])
d.Set("resource_type", object["ResourceType"])
d.Set("status", object["Status"])
d.Set("traffic_type", object["TrafficType"])
return nil
}
func resourceAlicloudVpcFlowLogUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"FlowLogId": d.Id(),
}
request["RegionId"] = client.RegionId
if !d.IsNewResource() && d.HasChange("description") {
update = true
request["Description"] = d.Get("description")
}
if !d.IsNewResource() && d.HasChange("flow_log_name") {
update = true
request["FlowLogName"] = d.Get("flow_log_name")
}
if update {
action := "ModifyFlowLogAttribute"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("description")
d.SetPartial("flow_log_name")
}
if d.HasChange("status") {
object, err := vpcService.DescribeVpcFlowLog(d.Id())
if err != nil {
return WrapError(err)
}
target := d.Get("status").(string)
if object["Status"].(string) != target {
if target == "Active" {
request := map[string]interface{}{
"FlowLogId": d.Id(),
}
request["RegionId"] = client.RegionId
action := "ActiveFlowLog"
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"TaskConflict", "UnknownError"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, vpcService.VpcFlowLogStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if target == "Inactive" {
request := map[string]interface{}{
"FlowLogId": d.Id(),
}
request["RegionId"] = client.RegionId
action := "DeactiveFlowLog"
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"TaskConflict", "UnknownError"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Inactive"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, vpcService.VpcFlowLogStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.SetPartial("status")
}
}
d.Partial(false)
return resourceAlicloudVpcFlowLogRead(d, meta)
}
func resourceAlicloudVpcFlowLogDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
action := "DeleteFlowLog"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"FlowLogId": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"Instance.IsNotAvailable", "Instance.IsNotPostPay"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, vpcService.VpcFlowLogStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudVpcIpv6EgressRule() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudVpcIpv6EgressRuleCreate,
Read: resourceAlicloudVpcIpv6EgressRuleRead,
Delete: resourceAlicloudVpcIpv6EgressRuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
Delete: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"Ipv6Address"}, false),
},
"ipv6_egress_rule_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile("^[a-zA-Z\u4E00-\u9FA5][\u4E00-\u9FA5A-Za-z0-9_-]{2,128}$"), "The name must be `2` to `128` characters in length, and can contain letters, digits, underscores (_), and hyphens (-). The name must start with a letter but cannot start with `http://` or `https://`."),
},
"ipv6_gateway_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudVpcIpv6EgressRuleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateIpv6EgressOnlyRule"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["InstanceId"] = d.Get("instance_id")
if v, ok := d.GetOk("instance_type"); ok {
request["InstanceType"] = v
}
if v, ok := d.GetOk("ipv6_egress_rule_name"); ok {
request["Name"] = v
}
request["Ipv6GatewayId"] = d.Get("ipv6_gateway_id")
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("CreateIpv6EgressOnlyRule")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_vpc_ipv6_egress_rule", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["Ipv6GatewayId"], ":", response["Ipv6EgressRuleId"]))
vpcService := VpcService{client}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, vpcService.VpcIpv6EgressRuleStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudVpcIpv6EgressRuleRead(d, meta)
}
func resourceAlicloudVpcIpv6EgressRuleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeVpcIpv6EgressRule(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_vpc_ipv6_egress_rule vpcService.DescribeVpcIpv6EgressRule Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("ipv6_gateway_id", parts[0])
d.Set("description", object["Description"])
d.Set("instance_id", object["InstanceId"])
d.Set("instance_type", object["InstanceType"])
d.Set("ipv6_egress_rule_name", object["Name"])
d.Set("status", object["Status"])
return nil
}
func resourceAlicloudVpcIpv6EgressRuleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
vpcService := VpcService{client}
action := "DeleteIpv6EgressOnlyRule"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"Ipv6EgressOnlyRuleId": parts[1],
}
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("DeleteIpv6EgressOnlyRule")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, vpcService.VpcIpv6EgressRuleStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudVpcIpv6Gateway() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudVpcIpv6GatewayCreate,
Read: resourceAlicloudVpcIpv6GatewayRead,
Update: resourceAlicloudVpcIpv6GatewayUpdate,
Delete: resourceAlicloudVpcIpv6GatewayDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(1 * time.Minute),
Delete: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"ipv6_gateway_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile("^[a-zA-Z\u4E00-\u9FA5][\u4E00-\u9FA5A-Za-z0-9_-]{2,128}$"), "The name must be `2` to `128` characters in length, and can contain letters, digits, underscores (_), and hyphens (-). The name must start with a letter but cannot start with `http://` or `https://`."),
},
"spec": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"Large", "Medium", "Small"}, false),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudVpcIpv6GatewayCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateIpv6Gateway"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOk("ipv6_gateway_name"); ok {
request["Name"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("spec"); ok {
request["Spec"] = v
}
request["VpcId"] = d.Get("vpc_id")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("CreateIpv6Gateway")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_vpc_ipv6_gateway", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["Ipv6GatewayId"]))
vpcService := VpcService{client}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, vpcService.VpcIpv6GatewayStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudVpcIpv6GatewayRead(d, meta)
}
func resourceAlicloudVpcIpv6GatewayRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeVpcIpv6Gateway(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_vpc_ipv6_gateway vpcService.DescribeVpcIpv6Gateway Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", object["Description"])
d.Set("ipv6_gateway_name", object["Name"])
d.Set("spec", object["Spec"])
d.Set("status", object["Status"])
d.Set("vpc_id", object["VpcId"])
return nil
}
func resourceAlicloudVpcIpv6GatewayUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"Ipv6GatewayId": d.Id(),
}
request["RegionId"] = client.RegionId
if d.HasChange("spec") {
update = true
}
if v, ok := d.GetOk("spec"); ok {
request["Spec"] = v
}
if update {
action := "ModifyIpv6GatewaySpec"
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("ModifyIpv6GatewaySpec")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, vpcService.VpcIpv6GatewayStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("spec")
}
update = false
modifyIpv6GatewayAttributeReq := map[string]interface{}{
"Ipv6GatewayId": d.Id(),
}
modifyIpv6GatewayAttributeReq["RegionId"] = client.RegionId
if d.HasChange("description") {
update = true
if v, ok := d.GetOk("description"); ok {
modifyIpv6GatewayAttributeReq["Description"] = v
}
}
if d.HasChange("ipv6_gateway_name") {
update = true
if v, ok := d.GetOk("ipv6_gateway_name"); ok {
modifyIpv6GatewayAttributeReq["Name"] = v
}
}
if update {
action := "ModifyIpv6GatewayAttribute"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, modifyIpv6GatewayAttributeReq, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, modifyIpv6GatewayAttributeReq)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, vpcService.VpcIpv6GatewayStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("description")
d.SetPartial("ipv6_gateway_name")
}
d.Partial(false)
return resourceAlicloudVpcIpv6GatewayRead(d, meta)
}
func resourceAlicloudVpcIpv6GatewayDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
action := "DeleteIpv6Gateway"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"Ipv6GatewayId": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, vpcService.VpcIpv6GatewayStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudVpcIpv6InternetBandwidth() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudVpcIpv6InternetBandwidthCreate,
Read: resourceAlicloudVpcIpv6InternetBandwidthRead,
Update: resourceAlicloudVpcIpv6InternetBandwidthUpdate,
Delete: resourceAlicloudVpcIpv6InternetBandwidthDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"bandwidth": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(1, 5000),
},
"internet_charge_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"PayByBandwidth", "PayByTraffic"}, false),
},
"ipv6_address_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ipv6_gateway_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudVpcIpv6InternetBandwidthCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "AllocateIpv6InternetBandwidth"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request["Bandwidth"] = d.Get("bandwidth")
if v, ok := d.GetOk("internet_charge_type"); ok {
request["InternetChargeType"] = v
}
request["Ipv6AddressId"] = d.Get("ipv6_address_id")
request["Ipv6GatewayId"] = d.Get("ipv6_gateway_id")
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("AllocateIpv6InternetBandwidth")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_vpc_ipv6_internet_bandwidth", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["InternetBandwidthId"]))
return resourceAlicloudVpcIpv6InternetBandwidthRead(d, meta)
}
func resourceAlicloudVpcIpv6InternetBandwidthRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeVpcIpv6InternetBandwidth(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_vpc_ipv6_internet_bandwidth vpcService.DescribeVpcIpv6InternetBandwidth Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("ipv6_address_id", object["Ipv6AddressId"])
d.Set("ipv6_gateway_id", object["Ipv6GatewayId"])
if ipv6InternetBandwidth, ok := object["Ipv6InternetBandwidth"]; ok {
if v, ok := ipv6InternetBandwidth.(map[string]interface{}); ok {
d.Set("bandwidth", formatInt(v["Bandwidth"]))
d.Set("internet_charge_type", v["InternetChargeType"])
d.Set("status", v["BusinessStatus"])
}
}
return nil
}
func resourceAlicloudVpcIpv6InternetBandwidthUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
request := map[string]interface{}{
"Ipv6InternetBandwidthId": d.Id(),
}
if d.HasChange("bandwidth") {
request["Bandwidth"] = d.Get("bandwidth")
}
request["RegionId"] = client.RegionId
action := "ModifyIpv6InternetBandwidth"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("ModifyIpv6InternetBandwidth")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return resourceAlicloudVpcIpv6InternetBandwidthRead(d, meta)
}
func resourceAlicloudVpcIpv6InternetBandwidthDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteIpv6InternetBandwidth"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"Ipv6InternetBandwidthId": d.Id(),
}
request["Ipv6AddressId"] = d.Get("ipv6_address_id")
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudVpcNatIp() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudVpcNatIpCreate,
Read: resourceAlicloudVpcNatIpRead,
Update: resourceAlicloudVpcNatIpUpdate,
Delete: resourceAlicloudVpcNatIpDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
Delete: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"dry_run": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"nat_gateway_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"nat_ip": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"nat_ip_id": {
Type: schema.TypeString,
Computed: true,
},
"nat_ip_cidr": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"nat_ip_cidr_id": {
Type: schema.TypeString,
Optional: true,
},
"nat_ip_description": {
Type: schema.TypeString,
Optional: true,
},
"nat_ip_name": {
Type: schema.TypeString,
Optional: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudVpcNatIpCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateNatIp"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["NatGatewayId"] = d.Get("nat_gateway_id")
if v, ok := d.GetOk("nat_ip"); ok {
request["NatIp"] = v
}
if v, ok := d.GetOk("nat_ip_cidr"); ok {
request["NatIpCidr"] = v
}
if v, ok := d.GetOk("nat_ip_cidr_id"); ok {
request["NatIpCidrId"] = v
}
if v, ok := d.GetOk("nat_ip_description"); ok {
request["NatIpDescription"] = v
}
if v, ok := d.GetOk("nat_ip_name"); ok {
request["NatIpName"] = v
}
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("CreateNatIp")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_vpc_nat_ip", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["NatGatewayId"], ":", response["NatIpId"]))
vpcService := VpcService{client}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, vpcService.VpcNatIpStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudVpcNatIpRead(d, meta)
}
func resourceAlicloudVpcNatIpRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeVpcNatIp(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_vpc_nat_ip vpcService.DescribeVpcNatIp Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("nat_gateway_id", object["NatGatewayId"])
d.Set("nat_ip", object["NatIp"])
d.Set("nat_ip_id", object["NatIpId"])
d.Set("nat_ip_cidr", object["NatIpCidr"])
d.Set("nat_ip_description", object["NatIpDescription"])
d.Set("nat_ip_name", object["NatIpName"])
d.Set("status", object["NatIpStatus"])
return nil
}
func resourceAlicloudVpcNatIpUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
update := false
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"RegionId": client.RegionId,
"NatIpId": parts[1],
}
if d.HasChange("nat_ip_description") {
update = true
}
if v, ok := d.GetOk("nat_ip_description"); ok {
request["NatIpDescription"] = v
}
if d.HasChange("nat_ip_name") {
update = true
}
if v, ok := d.GetOk("nat_ip_name"); ok {
request["NatIpName"] = v
}
request["RegionId"] = client.RegionId
if d.HasChange("dry_run") || d.IsNewResource() {
update = true
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
}
if update {
action := "ModifyNatIpAttribute"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("ModifyNatIpAttribute")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudVpcNatIpRead(d, meta)
}
func resourceAlicloudVpcNatIpDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
action := "DeleteNatIp"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"NatIpId": parts[1],
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("DeleteNatIp")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, vpcService.VpcNatIpStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudVpcNatIpCidr() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudVpcNatIpCidrCreate,
Read: resourceAlicloudVpcNatIpCidrRead,
Update: resourceAlicloudVpcNatIpCidrUpdate,
Delete: resourceAlicloudVpcNatIpCidrDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"dry_run": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"nat_gateway_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"nat_ip_cidr": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"nat_ip_cidr_description": {
Type: schema.TypeString,
Optional: true,
},
"nat_ip_cidr_name": {
Type: schema.TypeString,
Optional: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudVpcNatIpCidrCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateNatIpCidr"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["NatGatewayId"] = d.Get("nat_gateway_id")
if v, ok := d.GetOk("nat_ip_cidr"); ok {
request["NatIpCidr"] = v
}
if v, ok := d.GetOk("nat_ip_cidr_description"); ok {
request["NatIpCidrDescription"] = v
}
if v, ok := d.GetOk("nat_ip_cidr_name"); ok {
request["NatIpCidrName"] = v
}
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("CreateNatIpCidr")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_vpc_nat_ip_cidr", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["NatGatewayId"], ":", request["NatIpCidr"]))
return resourceAlicloudVpcNatIpCidrRead(d, meta)
}
func resourceAlicloudVpcNatIpCidrRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeVpcNatIpCidr(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_vpc_nat_ip_cidr vpcService.DescribeVpcNatIpCidr Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("nat_gateway_id", parts[0])
d.Set("nat_ip_cidr", parts[1])
d.Set("nat_ip_cidr_description", object["NatIpCidrDescription"])
d.Set("nat_ip_cidr_name", object["NatIpCidrName"])
d.Set("status", object["NatIpCidrStatus"])
return nil
}
func resourceAlicloudVpcNatIpCidrUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"NatGatewayId": parts[0],
"NatIpCidr": parts[1],
}
if d.HasChange("nat_ip_cidr_name") {
update = true
}
if v, ok := d.GetOk("nat_ip_cidr_name"); ok {
request["NatIpCidrName"] = v
}
request["RegionId"] = client.RegionId
if d.HasChange("dry_run") || d.IsNewResource() {
update = true
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
}
if d.HasChange("nat_ip_cidr_description") {
update = true
if v, ok := d.GetOk("nat_ip_cidr_description"); ok {
request["NatIpCidrDescription"] = v
}
}
if update {
action := "ModifyNatIpCidrAttribute"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("ModifyNatIpCidrAttribute")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudVpcNatIpCidrRead(d, meta)
}
func resourceAlicloudVpcNatIpCidrDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteNatIpCidr"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"NatGatewayId": parts[0],
"NatIpCidr": parts[1],
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("DeleteNatIpCidr")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudVpcTrafficMirrorFilter() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudVpcTrafficMirrorFilterCreate,
Read: resourceAlicloudVpcTrafficMirrorFilterRead,
Update: resourceAlicloudVpcTrafficMirrorFilterUpdate,
Delete: resourceAlicloudVpcTrafficMirrorFilterDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
Delete: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"traffic_mirror_filter_description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-zA-Z][\w\-]{1,255}$`), "The description must be `2` to `256` characters in length. It must start with a letter and cannot start with `http://` or `https://`"),
},
"traffic_mirror_filter_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-zA-Z][\w\-.]{1,127}$`), "The name must be `2` to `128` characters in length, and can contain digits, periods (.), underscores (_), and hyphens (-). It must start with a letter and cannot start with `http://` or `https://`."),
},
},
}
}
func resourceAlicloudVpcTrafficMirrorFilterCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateTrafficMirrorFilter"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("traffic_mirror_filter_description"); ok {
request["TrafficMirrorFilterDescription"] = v
}
if v, ok := d.GetOk("traffic_mirror_filter_name"); ok {
request["TrafficMirrorFilterName"] = v
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("CreateTrafficMirrorFilter")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_vpc_traffic_mirror_filter", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["TrafficMirrorFilterId"]))
vpcService := VpcService{client}
stateConf := BuildStateConf([]string{}, []string{"Created"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, vpcService.VpcTrafficMirrorFilterStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudVpcTrafficMirrorFilterRead(d, meta)
}
func resourceAlicloudVpcTrafficMirrorFilterRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeVpcTrafficMirrorFilter(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_vpc_traffic_mirror_filter vpcService.DescribeVpcTrafficMirrorFilter Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("status", object["TrafficMirrorFilterStatus"])
d.Set("traffic_mirror_filter_description", object["TrafficMirrorFilterDescription"])
d.Set("traffic_mirror_filter_name", object["TrafficMirrorFilterName"])
return nil
}
func resourceAlicloudVpcTrafficMirrorFilterUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
update := false
request := map[string]interface{}{
"TrafficMirrorFilterId": d.Id(),
}
request["RegionId"] = client.RegionId
if d.HasChange("traffic_mirror_filter_description") {
update = true
if v, ok := d.GetOk("traffic_mirror_filter_description"); ok {
request["TrafficMirrorFilterDescription"] = v
}
}
if d.HasChange("traffic_mirror_filter_name") {
update = true
if v, ok := d.GetOk("traffic_mirror_filter_name"); ok {
request["TrafficMirrorFilterName"] = v
}
}
if update {
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
action := "UpdateTrafficMirrorFilterAttribute"
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("UpdateTrafficMirrorFilterAttribute")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudVpcTrafficMirrorFilterRead(d, meta)
}
func resourceAlicloudVpcTrafficMirrorFilterDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteTrafficMirrorFilter"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"TrafficMirrorFilterId": d.Id(),
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("DeleteTrafficMirrorFilter")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectStatus.TrafficMirrorFilter", "IncorrectStatus.TrafficMirrorRule"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ResourceNotFound.TrafficMirrorFilter"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudVpcTrafficMirrorFilterEgressRule() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudVpcTrafficMirrorFilterEgressRuleCreate,
Read: resourceAlicloudVpcTrafficMirrorFilterEgressRuleRead,
Update: resourceAlicloudVpcTrafficMirrorFilterEgressRuleUpdate,
Delete: resourceAlicloudVpcTrafficMirrorFilterEgressRuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"destination_cidr_block": {
Type: schema.TypeString,
Required: true,
},
"destination_port_range": {
Type: schema.TypeString,
Optional: true,
Computed: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("protocol"); ok && v.(string) == "ICMP" {
return true
}
return false
},
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"priority": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(1, 10),
},
"protocol": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"ALL", "ICMP", "TCP", "UDP"}, false),
},
"rule_action": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"accept", "drop"}, false),
},
"source_cidr_block": {
Type: schema.TypeString,
Required: true,
},
"source_port_range": {
Type: schema.TypeString,
Optional: true,
Computed: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("protocol"); ok && v.(string) == "ICMP" {
return true
}
return false
},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"traffic_mirror_filter_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"traffic_mirror_filter_egress_rule_id": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudVpcTrafficMirrorFilterEgressRuleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateTrafficMirrorFilterRules"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
requestEgressRules := make(map[string]interface{})
requestEgressRulesMap := make([]interface{}, 0)
requestEgressRules["Action"] = d.Get("rule_action")
requestEgressRules["DestinationCidrBlock"] = d.Get("destination_cidr_block")
requestEgressRules["Priority"] = d.Get("priority")
requestEgressRules["Protocol"] = d.Get("protocol")
requestEgressRules["SourceCidrBlock"] = d.Get("source_cidr_block")
if fmt.Sprint(d.Get("protocol")) != "ICMP" {
if v, ok := d.GetOk("source_port_range"); ok {
requestEgressRules["SourcePortRange"] = v
}
if v, ok := d.GetOk("destination_port_range"); ok {
requestEgressRules["DestinationPortRange"] = v
}
}
requestEgressRulesMap = append(requestEgressRulesMap, requestEgressRules)
request["EgressRules"] = requestEgressRulesMap
request["RegionId"] = client.RegionId
request["TrafficMirrorFilterId"] = d.Get("traffic_mirror_filter_id")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("CreateTrafficMirrorFilterRules")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_vpc_traffic_mirror_filter_egress_rule", action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.EgressRules", response)
if err != nil || len(v.([]interface{})) < 1 {
return WrapErrorf(err, IdMsg, d.Id())
}
response = v.([]interface{})[0].(map[string]interface{})
d.SetId(fmt.Sprint(request["TrafficMirrorFilterId"], ":", response["InstanceId"]))
vpcService := VpcService{client}
stateConf := BuildStateConf([]string{}, []string{"Created"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, vpcService.VpcTrafficMirrorFilterEgressRuleStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudVpcTrafficMirrorFilterEgressRuleRead(d, meta)
}
func resourceAlicloudVpcTrafficMirrorFilterEgressRuleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeVpcTrafficMirrorFilterEgressRule(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_vpc_traffic_mirror_filter_egress_rule vpcService.DescribeVpcTrafficMirrorFilterEgressRule Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("traffic_mirror_filter_id", object["TrafficMirrorFilterId"])
d.Set("destination_cidr_block", object["DestinationCidrBlock"])
d.Set("destination_port_range", object["DestinationPortRange"])
d.Set("priority", object["Priority"])
d.Set("protocol", object["Protocol"])
d.Set("rule_action", object["Action"])
d.Set("source_cidr_block", object["SourceCidrBlock"])
d.Set("source_port_range", object["SourcePortRange"])
d.Set("status", object["TrafficMirrorFilterRuleStatus"])
d.Set("traffic_mirror_filter_egress_rule_id", fmt.Sprint(object["TrafficMirrorFilterRuleId"]))
return nil
}
func resourceAlicloudVpcTrafficMirrorFilterEgressRuleUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
update := false
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"TrafficMirrorFilterRuleId": parts[1],
}
request["RegionId"] = client.RegionId
if d.HasChange("destination_cidr_block") {
update = true
if v, ok := d.GetOk("destination_cidr_block"); ok {
request["DestinationCidrBlock"] = v
}
}
if d.HasChange("destination_port_range") {
update = true
if v, ok := d.GetOk("destination_port_range"); ok {
request["DestinationPortRange"] = v
}
}
if d.HasChange("priority") {
update = true
if v, ok := d.GetOk("priority"); ok {
request["Priority"] = v
}
}
if d.HasChange("protocol") {
update = true
if v, ok := d.GetOk("protocol"); ok {
request["Protocol"] = v
}
}
if d.HasChange("source_cidr_block") {
update = true
if v, ok := d.GetOk("source_cidr_block"); ok {
request["SourceCidrBlock"] = v
}
}
if d.HasChange("source_port_range") {
update = true
if v, ok := d.GetOk("source_port_range"); ok {
request["SourcePortRange"] = v
}
}
if d.HasChange("rule_action") {
update = true
if v, ok := d.GetOk("rule_action"); ok {
request["RuleAction"] = v
}
}
if update {
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
action := "UpdateTrafficMirrorFilterRuleAttribute"
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("UpdateTrafficMirrorFilterRuleAttribute")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Created"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, vpcService.VpcTrafficMirrorFilterEgressRuleStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudVpcTrafficMirrorFilterEgressRuleRead(d, meta)
}
func resourceAlicloudVpcTrafficMirrorFilterEgressRuleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteTrafficMirrorFilterRules"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"TrafficMirrorFilterRuleIds": []string{parts[1]},
"TrafficMirrorFilterId": parts[0],
"RegionId": client.RegionId,
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("DeleteTrafficMirrorFilterRules")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudVpcTrafficMirrorFilterIngressRule() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudVpcTrafficMirrorFilterIngressRuleCreate,
Read: resourceAlicloudVpcTrafficMirrorFilterIngressRuleRead,
Update: resourceAlicloudVpcTrafficMirrorFilterIngressRuleUpdate,
Delete: resourceAlicloudVpcTrafficMirrorFilterIngressRuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"destination_cidr_block": {
Type: schema.TypeString,
Required: true,
},
"destination_port_range": {
Type: schema.TypeString,
Optional: true,
Computed: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("protocol"); ok && v.(string) == "ICMP" {
return true
}
return false
},
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"priority": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(1, 10),
},
"protocol": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"ALL", "ICMP", "TCP", "UDP"}, false),
},
"rule_action": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"accept", "drop"}, false),
},
"source_cidr_block": {
Type: schema.TypeString,
Required: true,
},
"source_port_range": {
Type: schema.TypeString,
Optional: true,
Computed: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if v, ok := d.GetOk("protocol"); ok && v.(string) == "ICMP" {
return true
}
return false
},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"traffic_mirror_filter_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"traffic_mirror_filter_ingress_rule_id": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAlicloudVpcTrafficMirrorFilterIngressRuleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateTrafficMirrorFilterRules"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
requestIngressRules := make(map[string]interface{})
requestIngressRulesMap := make([]interface{}, 0)
requestIngressRules["Action"] = d.Get("rule_action")
requestIngressRules["DestinationCidrBlock"] = d.Get("destination_cidr_block")
requestIngressRules["Priority"] = d.Get("priority")
requestIngressRules["Protocol"] = d.Get("protocol")
requestIngressRules["SourceCidrBlock"] = d.Get("source_cidr_block")
if fmt.Sprint(d.Get("protocol")) != "ICMP" {
if v, ok := d.GetOk("source_port_range"); ok {
requestIngressRules["SourcePortRange"] = v
}
if v, ok := d.GetOk("destination_port_range"); ok {
requestIngressRules["DestinationPortRange"] = v
}
}
requestIngressRulesMap = append(requestIngressRulesMap, requestIngressRules)
request["IngressRules"] = requestIngressRulesMap
request["RegionId"] = client.RegionId
request["TrafficMirrorFilterId"] = d.Get("traffic_mirror_filter_id")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("CreateTrafficMirrorFilterRules")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_vpc_traffic_mirror_filter_ingress_rule", action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.IngressRules", response)
if err != nil || len(v.([]interface{})) < 1 {
return WrapErrorf(err, IdMsg, d.Id())
}
response = v.([]interface{})[0].(map[string]interface{})
d.SetId(fmt.Sprint(request["TrafficMirrorFilterId"], ":", response["InstanceId"]))
vpcService := VpcService{client}
stateConf := BuildStateConf([]string{}, []string{"Created"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, vpcService.VpcTrafficMirrorFilterIngressRuleStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudVpcTrafficMirrorFilterIngressRuleRead(d, meta)
}
func resourceAlicloudVpcTrafficMirrorFilterIngressRuleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeVpcTrafficMirrorFilterIngressRule(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_vpc_traffic_mirror_filter_ingress_rule vpcService.DescribeVpcTrafficMirrorFilterIngressRule Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("traffic_mirror_filter_id", object["TrafficMirrorFilterId"])
d.Set("destination_cidr_block", object["DestinationCidrBlock"])
d.Set("destination_port_range", object["DestinationPortRange"])
d.Set("priority", formatInt(object["Priority"]))
d.Set("protocol", object["Protocol"])
d.Set("rule_action", object["Action"])
d.Set("source_cidr_block", object["SourceCidrBlock"])
d.Set("source_port_range", object["SourcePortRange"])
d.Set("status", object["TrafficMirrorFilterRuleStatus"])
d.Set("traffic_mirror_filter_ingress_rule_id", fmt.Sprint(object["TrafficMirrorFilterRuleId"]))
return nil
}
func resourceAlicloudVpcTrafficMirrorFilterIngressRuleUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
update := false
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"TrafficMirrorFilterRuleId": parts[1],
}
request["RegionId"] = client.RegionId
if d.HasChange("destination_cidr_block") {
update = true
if v, ok := d.GetOk("destination_cidr_block"); ok {
request["DestinationCidrBlock"] = v
}
}
if d.HasChange("destination_port_range") {
update = true
if v, ok := d.GetOk("destination_port_range"); ok {
request["DestinationPortRange"] = v
}
}
if d.HasChange("priority") {
update = true
if v, ok := d.GetOk("priority"); ok {
request["Priority"] = v
}
}
if d.HasChange("protocol") {
update = true
if v, ok := d.GetOk("protocol"); ok {
request["Protocol"] = v
}
}
if d.HasChange("source_cidr_block") {
update = true
if v, ok := d.GetOk("source_cidr_block"); ok {
request["SourceCidrBlock"] = v
}
}
if d.HasChange("source_port_range") {
update = true
if v, ok := d.GetOk("source_port_range"); ok {
request["SourcePortRange"] = v
}
}
if d.HasChange("rule_action") {
update = true
if v, ok := d.GetOk("rule_action"); ok {
request["RuleAction"] = v
}
}
if update {
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
action := "UpdateTrafficMirrorFilterRuleAttribute"
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("UpdateTrafficMirrorFilterRuleAttribute")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Created"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, vpcService.VpcTrafficMirrorFilterIngressRuleStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
return resourceAlicloudVpcTrafficMirrorFilterIngressRuleRead(d, meta)
}
func resourceAlicloudVpcTrafficMirrorFilterIngressRuleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteTrafficMirrorFilterRules"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"TrafficMirrorFilterRuleIds": []string{parts[1]},
"TrafficMirrorFilterId": parts[0],
"RegionId": client.RegionId,
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("DeleteTrafficMirrorFilterRules")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudVpcTrafficMirrorSession() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudVpcTrafficMirrorSessionCreate,
Read: resourceAlicloudVpcTrafficMirrorSessionRead,
Update: resourceAlicloudVpcTrafficMirrorSessionUpdate,
Delete: resourceAlicloudVpcTrafficMirrorSessionDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
Delete: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(1 * time.Minute),
},
Schema: map[string]*schema.Schema{
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"enabled": {
Type: schema.TypeBool,
Optional: true,
},
"priority": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(1, 32766),
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"traffic_mirror_filter_id": {
Type: schema.TypeString,
Required: true,
},
"traffic_mirror_session_description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"traffic_mirror_session_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile("^[a-zA-Z\u4E00-\u9FA5][\u4E00-\u9FA5A-Za-z0-9_-]{2,128}$"), "The name must be `2` to `128` characters in length and can contain digits, underscores (_), and hyphens (-). It must start with a letter."),
},
"traffic_mirror_source_ids": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"traffic_mirror_target_id": {
Type: schema.TypeString,
Required: true,
},
"traffic_mirror_target_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"NetworkInterface", "SLB"}, false),
},
"virtual_network_id": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(0, 16777215),
},
},
}
}
func resourceAlicloudVpcTrafficMirrorSessionCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateTrafficMirrorSession"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
if v, ok := d.GetOk("enabled"); ok {
request["Enabled"] = v
}
request["Priority"] = d.Get("priority")
request["RegionId"] = client.RegionId
request["TrafficMirrorFilterId"] = d.Get("traffic_mirror_filter_id")
if v, ok := d.GetOk("traffic_mirror_session_description"); ok {
request["TrafficMirrorSessionDescription"] = v
}
if v, ok := d.GetOk("traffic_mirror_session_name"); ok {
request["TrafficMirrorSessionName"] = v
}
request["TrafficMirrorSourceIds"] = d.Get("traffic_mirror_source_ids")
request["TrafficMirrorTargetId"] = d.Get("traffic_mirror_target_id")
request["TrafficMirrorTargetType"] = d.Get("traffic_mirror_target_type")
if v, ok := d.GetOk("virtual_network_id"); ok {
request["VirtualNetworkId"] = v
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("CreateTrafficMirrorSession")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_vpc_traffic_mirror_session", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["TrafficMirrorSessionId"]))
vpcService := VpcService{client}
stateConf := BuildStateConf([]string{}, []string{"Created"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, vpcService.VpcTrafficMirrorSessionStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudVpcTrafficMirrorSessionRead(d, meta)
}
func resourceAlicloudVpcTrafficMirrorSessionRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeVpcTrafficMirrorSession(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_vpc_traffic_mirror_session vpcService.DescribeVpcTrafficMirrorSession Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("enabled", object["Enabled"])
d.Set("priority", formatInt(object["Priority"]))
d.Set("status", object["TrafficMirrorSessionStatus"])
d.Set("traffic_mirror_filter_id", object["TrafficMirrorFilterId"])
d.Set("traffic_mirror_session_description", object["TrafficMirrorSessionDescription"])
d.Set("traffic_mirror_session_name", object["TrafficMirrorSessionName"])
d.Set("traffic_mirror_source_ids", object["TrafficMirrorSourceIds"])
d.Set("traffic_mirror_target_id", object["TrafficMirrorTargetId"])
d.Set("traffic_mirror_target_type", object["TrafficMirrorTargetType"])
d.Set("virtual_network_id", formatInt(object["VirtualNetworkId"]))
return nil
}
func resourceAlicloudVpcTrafficMirrorSessionUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
d.Partial(true)
update := false
request := map[string]interface{}{
"TrafficMirrorSessionId": d.Id(),
}
request["RegionId"] = client.RegionId
if d.HasChange("enabled") {
update = true
if v, ok := d.GetOkExists("enabled"); ok {
request["Enabled"] = v
}
}
if d.HasChange("priority") {
update = true
request["Priority"] = d.Get("priority")
}
if d.HasChange("traffic_mirror_filter_id") {
update = true
request["TrafficMirrorFilterId"] = d.Get("traffic_mirror_filter_id")
}
if d.HasChange("traffic_mirror_session_description") {
update = true
if v, ok := d.GetOk("traffic_mirror_session_description"); ok {
request["TrafficMirrorSessionDescription"] = v
}
}
if d.HasChange("traffic_mirror_session_name") {
update = true
if v, ok := d.GetOk("traffic_mirror_session_name"); ok {
request["TrafficMirrorSessionName"] = v
}
}
request["TrafficMirrorTargetId"] = d.Get("traffic_mirror_target_id")
if d.HasChange("traffic_mirror_target_id") {
update = true
}
request["TrafficMirrorTargetType"] = d.Get("traffic_mirror_target_type")
if d.HasChange("traffic_mirror_target_type") {
update = true
}
if d.HasChange("virtual_network_id") {
update = true
if v, ok := d.GetOk("virtual_network_id"); ok {
request["VirtualNetworkId"] = v
}
}
if update {
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
action := "UpdateTrafficMirrorSessionAttribute"
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("UpdateTrafficMirrorSessionAttribute")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
vpcService := VpcService{client}
stateConf := BuildStateConf([]string{}, []string{"Created"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, vpcService.VpcTrafficMirrorSessionStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("enabled")
d.SetPartial("priority")
d.SetPartial("traffic_mirror_filter_id")
d.SetPartial("traffic_mirror_session_description")
d.SetPartial("traffic_mirror_session_name")
d.SetPartial("traffic_mirror_target_id")
d.SetPartial("traffic_mirror_target_type")
d.SetPartial("virtual_network_id")
}
d.Partial(false)
if d.HasChange("traffic_mirror_source_ids") {
oldTrafficMirrorSourceIds, newTrafficMirrorSourceIds := d.GetChange("traffic_mirror_source_ids")
removed := oldTrafficMirrorSourceIds.([]interface{})
added := newTrafficMirrorSourceIds.([]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if len(removed) > 0 {
removeSourcesFromTrafficMirrorSessionRequest := map[string]interface{}{
"TrafficMirrorSessionId": d.Id(),
"RegionId": client.RegionId,
}
removeSourcesFromTrafficMirrorSessionRequest["TrafficMirrorSourceIds"] = removed
if _, ok := d.GetOkExists("dry_run"); ok {
removeSourcesFromTrafficMirrorSessionRequest["DryRun"] = d.Get("dry_run")
}
action := "RemoveSourcesFromTrafficMirrorSession"
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("RemoveSourcesFromTrafficMirrorSession")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, removeSourcesFromTrafficMirrorSessionRequest, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, removeSourcesFromTrafficMirrorSessionRequest)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Created"}, d.Timeout(schema.TimeoutUpdate), 10*time.Second, vpcService.VpcTrafficMirrorSessionStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
if len(added) > 0 {
AddSourcesToTrafficMirrorSessionRequest := map[string]interface{}{
"TrafficMirrorSessionId": d.Id(),
"RegionId": client.RegionId,
}
AddSourcesToTrafficMirrorSessionRequest["TrafficMirrorSourceIds"] = added
if _, ok := d.GetOkExists("dry_run"); ok {
AddSourcesToTrafficMirrorSessionRequest["DryRun"] = d.Get("dry_run")
}
action := "AddSourcesToTrafficMirrorSession"
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("AddSourcesToTrafficMirrorSession")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, AddSourcesToTrafficMirrorSessionRequest, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, AddSourcesToTrafficMirrorSessionRequest)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Created"}, d.Timeout(schema.TimeoutUpdate), 10*time.Second, vpcService.VpcTrafficMirrorSessionStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
}
d.SetPartial("TrafficMirrorSourceIds")
}
return resourceAlicloudVpcTrafficMirrorSessionRead(d, meta)
}
func resourceAlicloudVpcTrafficMirrorSessionDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
action := "DeleteTrafficMirrorSession"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"TrafficMirrorSessionId": d.Id(),
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 10*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("DeleteTrafficMirrorSession")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectStatus.TrafficMirrorSession"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ResourceNotFound.TrafficMirrorSession"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, vpcService.VpcTrafficMirrorSessionStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudVpcVbrHa() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudVpcVbrHaCreate,
Read: resourceAlicloudVpcVbrHaRead,
Update: resourceAlicloudVpcVbrHaUpdate,
Delete: resourceAlicloudVpcVbrHaDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.All(validation.StringLenBetween(2, 256), validation.StringDoesNotMatch(regexp.MustCompile(`(^http://.*)|(^https://.*)`), "It cannot begin with \"http://\", \"https://\".")),
},
"dry_run": {
Type: schema.TypeBool,
Optional: true,
},
"peer_vbr_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"vbr_ha_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vbr_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceAlicloudVpcVbrHaCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateVbrHa"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
if v, ok := d.GetOkExists("dry_run"); ok {
request["DryRun"] = v
}
request["PeerVbrId"] = d.Get("peer_vbr_id")
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("vbr_ha_name"); ok {
request["Name"] = v
}
request["VbrId"] = d.Get("vbr_id")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("CreateVbrHa")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_vpc_vbr_ha", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["VbrHaId"]))
vpcService := VpcService{client}
stateConf := BuildStateConf([]string{}, []string{"Active"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, vpcService.VpcVbrHaStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudVpcVbrHaRead(d, meta)
}
func resourceAlicloudVpcVbrHaRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeVpcVbrHa(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_vpc_vbr_ha vpcService.DescribeVpcVbrHa Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", object["Description"])
d.Set("peer_vbr_id", object["PeerVbrId"])
d.Set("status", object["Status"])
d.Set("vbr_ha_name", object["Name"])
d.Set("vbr_id", object["VbrId"])
return nil
}
func resourceAlicloudVpcVbrHaUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return resourceAlicloudVpcVbrHaRead(d, meta)
}
func resourceAlicloudVpcVbrHaDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
action := "DeleteVbrHa"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"InstanceId": d.Id(),
}
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("DeleteVbrHa")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, vpcService.VpcVbrHaStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliyunVpnConnection() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunVpnConnectionCreate,
Read: resourceAliyunVpnConnectionRead,
Update: resourceAliyunVpnConnectionUpdate,
Delete: resourceAliyunVpnConnectionDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"customer_gateway_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"vpn_gateway_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 128),
},
"local_subnet": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validateCIDRNetworkAddress,
},
MinItems: 1,
MaxItems: 10,
},
"remote_subnet": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validateCIDRNetworkAddress,
},
MinItems: 1,
MaxItems: 10,
},
"effect_immediately": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"ike_config": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"psk": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(1, 100),
},
"ike_version": {
Type: schema.TypeString,
Optional: true,
Default: IKE_VERSION_1,
ValidateFunc: validation.StringInSlice([]string{IKE_VERSION_1, IKE_VERSION_2}, false),
},
"ike_mode": {
Type: schema.TypeString,
Optional: true,
Default: IKE_MODE_MAIN,
ValidateFunc: validation.StringInSlice([]string{IKE_MODE_MAIN, IKE_MODE_AGGRESSIVE}, false),
},
"ike_enc_alg": {
Type: schema.TypeString,
Optional: true,
Default: VPN_ENC_AES,
ValidateFunc: validation.StringInSlice([]string{VPN_ENC_AES, VPN_ENC_AES_3DES, VPN_ENC_AES_192, VPN_ENC_AES_256, VPN_ENC_AES_DES}, false),
},
"ike_auth_alg": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{VPN_AUTH_SHA, VPN_AUTH_MD5, VPN_AUTH_SHA256, VPN_AUTH_SHA386, VPN_AUTH_SHA512}, false),
},
"ike_pfs": {
Type: schema.TypeString,
Optional: true,
Default: VPN_PFS_G2,
ValidateFunc: validation.StringInSlice([]string{VPN_PFS_G1, VPN_PFS_G2, VPN_PFS_G5, VPN_PFS_G14, VPN_PFS_G24}, false),
},
"ike_lifetime": {
Type: schema.TypeInt,
Optional: true,
Default: 86400,
ValidateFunc: validation.IntBetween(0, 86400),
},
"ike_local_id": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(1, 100),
},
"ike_remote_id": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(1, 100),
},
},
},
},
"ipsec_config": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ipsec_enc_alg": {
Type: schema.TypeString,
Optional: true,
Default: VPN_ENC_AES,
ValidateFunc: validation.StringInSlice([]string{VPN_ENC_AES, VPN_ENC_AES_3DES, VPN_ENC_AES_192, VPN_ENC_AES_256, VPN_ENC_AES_DES}, false),
},
"ipsec_auth_alg": {
Type: schema.TypeString,
Optional: true,
Default: VPN_AUTH_SHA,
ValidateFunc: validation.StringInSlice([]string{VPN_AUTH_SHA, VPN_AUTH_MD5, VPN_AUTH_SHA256, VPN_AUTH_SHA386, VPN_AUTH_SHA512}, false),
},
"ipsec_pfs": {
Type: schema.TypeString,
Optional: true,
Default: VPN_PFS_G2,
ValidateFunc: validation.StringInSlice([]string{VPN_PFS_G1, VPN_PFS_G2, VPN_PFS_G5, VPN_PFS_G14, VPN_PFS_G24, VPN_PFS_DISABLED}, false),
},
"ipsec_lifetime": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(0, 86400),
},
},
},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAliyunVpnConnectionCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpnGatewayService := VpnGatewayService{client}
request, err := buildAliyunVpnConnectionArgs(d, meta)
if err != nil {
return WrapError(err)
}
var response *vpc.CreateVpnConnectionResponse
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
args := *request
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.CreateVpnConnection(&args)
})
if err != nil {
if IsExpectedErrors(err, []string{"VpnGateway.Configuring"}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*vpc.CreateVpnConnectionResponse)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_vpn_connection", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetId(response.VpnConnectionId)
if err := vpnGatewayService.WaitForVpnConnection(d.Id(), Null, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
return resourceAliyunVpnConnectionRead(d, meta)
}
func resourceAliyunVpnConnectionRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpnGatewayService := VpnGatewayService{client}
response, err := vpnGatewayService.DescribeVpnConnection(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("customer_gateway_id", response.CustomerGatewayId)
d.Set("vpn_gateway_id", response.VpnGatewayId)
d.Set("name", response.Name)
localSubnet := strings.Split(response.LocalSubnet, ",")
d.Set("local_subnet", localSubnet)
remoteSubnet := strings.Split(response.RemoteSubnet, ",")
d.Set("remote_subnet", remoteSubnet)
d.Set("effect_immediately", response.EffectImmediately)
d.Set("status", response.Status)
if err := d.Set("ike_config", vpnGatewayService.ParseIkeConfig(response.IkeConfig)); err != nil {
return WrapError(err)
}
if err := d.Set("ipsec_config", vpnGatewayService.ParseIpsecConfig(response.IpsecConfig)); err != nil {
return WrapError(err)
}
return nil
}
func resourceAliyunVpnConnectionUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpnGatewayService := VpnGatewayService{client}
request := vpc.CreateModifyVpnConnectionAttributeRequest()
request.RegionId = client.RegionId
request.ClientToken = buildClientToken(request.GetActionName())
request.VpnConnectionId = d.Id()
if d.HasChange("name") {
request.Name = d.Get("name").(string)
}
request.LocalSubnet = vpnGatewayService.AssembleNetworkSubnetToString(d.Get("local_subnet").(*schema.Set).List())
request.RemoteSubnet = vpnGatewayService.AssembleNetworkSubnetToString(d.Get("remote_subnet").(*schema.Set).List())
/* If not set effect_immediately value, VPN connection will automatically set the value to false*/
if v, ok := d.GetOk("effect_immediately"); ok {
request.EffectImmediately = requests.NewBoolean(v.(bool))
}
if d.HasChange("ike_config") {
ike_config, err := vpnGatewayService.AssembleIkeConfig(d.Get("ike_config").([]interface{}))
if err != nil {
return WrapError(err)
}
request.IkeConfig = ike_config
}
if d.HasChange("ipsec_config") {
ipsec_config, err := vpnGatewayService.AssembleIpsecConfig(d.Get("ipsec_config").([]interface{}))
if err != nil {
return WrapError(err)
}
request.IpsecConfig = ipsec_config
}
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.ModifyVpnConnectionAttribute(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return resourceAliyunVpnConnectionRead(d, meta)
}
func resourceAliyunVpnConnectionDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpnGatewayService := VpnGatewayService{client}
request := vpc.CreateDeleteVpnConnectionRequest()
request.RegionId = client.RegionId
request.ClientToken = buildClientToken(request.GetActionName())
request.VpnConnectionId = d.Id()
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
args := *request
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DeleteVpnConnection(&args)
})
if err != nil {
if IsExpectedErrors(err, []string{"VpnGateway.Configuring"}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidVpnConnectionInstanceId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(vpnGatewayService.WaitForVpnConnection(d.Id(), Deleted, DefaultTimeout))
}
func buildAliyunVpnConnectionArgs(d *schema.ResourceData, meta interface{}) (*vpc.CreateVpnConnectionRequest, error) {
client := meta.(*connectivity.AliyunClient)
vpnGatewayService := VpnGatewayService{client}
request := vpc.CreateCreateVpnConnectionRequest()
request.RegionId = client.RegionId
request.CustomerGatewayId = d.Get("customer_gateway_id").(string)
request.VpnGatewayId = d.Get("vpn_gateway_id").(string)
request.LocalSubnet = vpnGatewayService.AssembleNetworkSubnetToString(d.Get("local_subnet").(*schema.Set).List())
request.RemoteSubnet = vpnGatewayService.AssembleNetworkSubnetToString(d.Get("remote_subnet").(*schema.Set).List())
if v := d.Get("name").(string); v != "" {
request.Name = v
}
if v, ok := d.GetOk("effect_immediately"); ok {
request.EffectImmediately = requests.NewBoolean(v.(bool))
}
if v, ok := d.GetOk("ike_config"); ok {
ikeConfig, err := vpnGatewayService.AssembleIkeConfig(v.([]interface{}))
if err != nil {
return nil, WrapError(err)
}
request.IkeConfig = ikeConfig
}
if v, ok := d.GetOk("ipsec_config"); ok {
ipsecConfig, err := vpnGatewayService.AssembleIpsecConfig(v.([]interface{}))
if err != nil {
return nil, fmt.Errorf("wrong ipsec_config: %#v", err)
}
request.IpsecConfig = ipsecConfig
}
request.ClientToken = buildClientToken(request.GetActionName())
return request, nil
}
package alicloud
import (
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliyunVpnCustomerGateway() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunVpnCustomerGatewayCreate,
Read: resourceAliyunVpnCustomerGatewayRead,
Update: resourceAliyunVpnCustomerGatewayUpdate,
Delete: resourceAliyunVpnCustomerGatewayDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"ip_address": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.SingleIP(),
},
"name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 128),
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
},
}
}
func resourceAliyunVpnCustomerGatewayCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpnGatewayService := VpnGatewayService{client}
request := vpc.CreateCreateCustomerGatewayRequest()
request.RegionId = client.RegionId
request.IpAddress = d.Get("ip_address").(string)
if v := d.Get("name").(string); v != "" {
request.Name = v
}
if v := d.Get("description").(string); v != "" {
request.Description = v
}
request.ClientToken = buildClientToken(request.GetActionName())
wait := incrementalWait(3*time.Second, 5*time.Second)
var raw interface{}
var err error
err = resource.Retry(2*time.Minute, func() *resource.RetryError {
args := *request
raw, err = client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.CreateCustomerGateway(&args)
})
if err != nil {
if IsExpectedErrors(err, []string{Throttling, "OperationConflict"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_vpn_customer_gateway", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*vpc.CreateCustomerGatewayResponse)
d.SetId(response.CustomerGatewayId)
err = vpnGatewayService.WaitForVpnCustomerGateway(d.Id(), Null, 60)
if err != nil {
return WrapError(err)
}
return resourceAliyunVpnCustomerGatewayRead(d, meta)
}
func resourceAliyunVpnCustomerGatewayRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpnGatewayService := VpnGatewayService{client}
object, err := vpnGatewayService.DescribeVpnCustomerGateway(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("ip_address", object.IpAddress)
d.Set("name", object.Name)
d.Set("description", object.Description)
return nil
}
func resourceAliyunVpnCustomerGatewayUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := vpc.CreateModifyCustomerGatewayAttributeRequest()
request.RegionId = client.RegionId
request.CustomerGatewayId = d.Id()
if d.HasChange("name") {
request.Name = d.Get("name").(string)
}
if d.HasChange("description") {
request.Description = d.Get("description").(string)
}
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.ModifyCustomerGatewayAttribute(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return resourceAliyunVpnCustomerGatewayRead(d, meta)
}
func resourceAliyunVpnCustomerGatewayDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpnGatewayService := VpnGatewayService{client}
request := vpc.CreateDeleteCustomerGatewayRequest()
request.RegionId = client.RegionId
request.CustomerGatewayId = d.Id()
request.ClientToken = buildClientToken(request.GetActionName())
err := resource.Retry(2*time.Minute, func() *resource.RetryError {
args := *request
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DeleteCustomerGateway(&args)
})
if err != nil {
if IsExpectedErrors(err, []string{"VpnGateway.Configuring"}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidCustomerGatewayInstanceId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(vpnGatewayService.WaitForVpnCustomerGateway(d.Id(), Deleted, DefaultTimeout))
}
package alicloud
import (
"fmt"
"log"
"strconv"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/denverdino/aliyungo/common"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliyunVpnGateway() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunVpnGatewayCreate,
Read: resourceAliyunVpnGatewayRead,
Update: resourceAliyunVpnGatewayUpdate,
Delete: resourceAliyunVpnGatewayDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(1, 128),
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_charge_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: PostPaid,
ValidateFunc: validation.StringInSlice([]string{string(common.PrePaid), string(common.PostPaid)}, false),
},
"period": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
ValidateFunc: validation.Any(validation.IntBetween(1, 9), validation.IntInSlice([]int{12, 24, 36})),
DiffSuppressFunc: PostPaidDiffSuppressFunc,
},
"bandwidth": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntInSlice([]int{5, 10, 20, 50, 100, 200, 500, 1000}),
},
"enable_ipsec": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"enable_ssl": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"ssl_connections": {
Type: schema.TypeInt,
Optional: true,
Default: 5,
DiffSuppressFunc: vpnSslConnectionsDiffSuppressFunc,
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(2, 256),
},
"vswitch_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"internet_ip": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"business_status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAliyunVpnGatewayCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpnGatewayService := VpnGatewayService{client}
request := vpc.CreateCreateVpnGatewayRequest()
request.RegionId = client.RegionId
if v, ok := d.GetOk("name"); ok && v.(string) != "" {
request.Name = d.Get("name").(string)
}
if v, ok := d.GetOk("vswitch_id"); ok && v.(string) != "" {
request.VSwitchId = d.Get("vswitch_id").(string)
}
request.VpcId = d.Get("vpc_id").(string)
if v, ok := d.GetOk("instance_charge_type"); ok && v.(string) != "" {
if v.(string) == string(PostPaid) {
request.InstanceChargeType = string("POSTPAY")
} else {
request.InstanceChargeType = string("PREPAY")
}
}
if v, ok := d.GetOk("period"); ok && v.(int) != 0 && request.InstanceChargeType == string("PREPAY") {
request.Period = requests.NewInteger(v.(int))
}
request.Bandwidth = requests.NewInteger(d.Get("bandwidth").(int))
if v, ok := d.GetOkExists("enable_ipsec"); ok {
request.EnableIpsec = requests.NewBoolean(v.(bool))
}
if v, ok := d.GetOk("enable_ssl"); ok {
request.EnableSsl = requests.NewBoolean(v.(bool))
}
if v, ok := d.GetOk("ssl_connections"); ok && v.(int) != 0 {
request.SslConnections = requests.NewInteger(v.(int))
}
request.AutoPay = requests.NewBoolean(true)
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.CreateVpnGateway(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_vpn_gateway", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*vpc.CreateVpnGatewayResponse)
d.SetId(response.VpnGatewayId)
time.Sleep(10 * time.Second)
if err := vpnGatewayService.WaitForVpnGateway(d.Id(), Active, 2*DefaultTimeout); err != nil {
return WrapError(err)
}
return resourceAliyunVpnGatewayUpdate(d, meta)
}
func resourceAliyunVpnGatewayRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpnGatewayService := VpnGatewayService{client}
object, err := vpnGatewayService.DescribeVpnGateway(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("name", object.Name)
d.Set("description", object.Description)
d.Set("vpc_id", object.VpcId)
d.Set("internet_ip", object.InternetIp)
d.Set("status", object.Status)
d.Set("vswitch_id", object.VSwitchId)
d.Set("enable_ipsec", "enable" == strings.ToLower(object.IpsecVpn))
d.Set("enable_ssl", "enable" == strings.ToLower(object.SslVpn))
d.Set("ssl_connections", object.SslMaxConnections)
d.Set("business_status", object.BusinessStatus)
spec := strings.Split(object.Spec, "M")[0]
bandwidth, err := strconv.Atoi(spec)
if err == nil {
d.Set("bandwidth", bandwidth)
} else {
return WrapError(err)
}
if string("PostpayByFlow") == object.ChargeType {
d.Set("instance_charge_type", string(PostPaid))
} else {
d.Set("instance_charge_type", string(PrePaid))
}
return nil
}
func resourceAliyunVpnGatewayUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := vpc.CreateModifyVpnGatewayAttributeRequest()
request.RegionId = client.RegionId
request.VpnGatewayId = d.Id()
update := false
d.Partial(true)
if d.HasChange("name") {
request.Name = d.Get("name").(string)
update = true
}
if d.HasChange("description") {
request.Description = d.Get("description").(string)
update = true
}
if update {
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.ModifyVpnGatewayAttribute(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
d.SetPartial("name")
d.SetPartial("description")
}
if d.IsNewResource() {
d.Partial(false)
return resourceAliyunVpnGatewayRead(d, meta)
}
if d.HasChange("bandwidth") {
return fmt.Errorf("Now Cann't Support modify vpn gateway bandwidth, try to modify on the web console")
}
if d.HasChange("enable_ipsec") || d.HasChange("enable_ssl") {
return fmt.Errorf("Now Cann't Support modify ipsec/ssl switch, try to modify on the web console")
}
d.Partial(false)
return resourceAliyunVpnGatewayRead(d, meta)
}
func resourceAliyunVpnGatewayDelete(d *schema.ResourceData, meta interface{}) error {
if d.Get("instance_charge_type").(string) == "PrePaid" {
log.Printf("[WARN] Cannot destroy resource Alicloud Resource VPN Gateway. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
client := meta.(*connectivity.AliyunClient)
vpnGatewayService := VpnGatewayService{client}
request := vpc.CreateDeleteVpnGatewayRequest()
request.RegionId = client.RegionId
request.VpnGatewayId = d.Id()
request.ClientToken = buildClientToken(request.GetActionName())
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
args := *request
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DeleteVpnGateway(&args)
})
if err != nil {
if IsExpectedErrors(err, []string{"VpnGateway.Configuring"}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
/*Vpn known issue: while the vpn is configuring, it will return unknown error*/
if IsExpectedErrors(err, []string{"UnknownError"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidVpnGatewayInstanceId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(vpnGatewayService.WaitForVpnGateway(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAliyunVpnRouteEntry() *schema.Resource {
return &schema.Resource{
Create: resourceAliyunVpnRouteEntryCreate,
Read: resourceAliyunVpnRouteEntryRead,
Update: resourceAliyunVpnRouteEntryUpdate,
Delete: resourceAliyunVpnRouteEntryDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"vpn_gateway_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"next_hop": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"route_dest": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"weight": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntInSlice([]int{0, 100}),
},
"publish_vpc": {
Type: schema.TypeBool,
Required: true,
},
},
}
}
func resourceAliyunVpnRouteEntryCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpnRouteEntryService := VpnGatewayService{client}
request := vpc.CreateCreateVpnRouteEntryRequest()
request.RegionId = client.RegionId
request.VpnGatewayId = d.Get("vpn_gateway_id").(string)
request.RouteDest = d.Get("route_dest").(string)
request.NextHop = d.Get("next_hop").(string)
request.Weight = requests.NewInteger(d.Get("weight").(int))
request.PublishVpc = requests.NewBoolean(d.Get("publish_vpc").(bool))
request.ClientToken = buildClientToken(request.GetActionName())
var raw interface{}
wait := incrementalWait(5*time.Second, 5*time.Second)
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw1, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.CreateVpnRouteEntry(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"VpnGateway.Configuring"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
raw = raw1
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*vpc.CreateVpnRouteEntryResponse)
id := response.VpnInstanceId + ":" + response.NextHop + ":" + response.RouteDest
d.SetId(id)
if err := vpnRouteEntryService.WaitForVpnRouteEntry(d.Id(), Active, 2*DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
return resourceAliyunVpnRouteEntryRead(d, meta)
}
func resourceAliyunVpnRouteEntryRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpnRouteEntryService := VpnGatewayService{client}
object, err := vpnRouteEntryService.DescribeVpnRouteEntry(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("weight", object.Weight)
d.Set("next_hop", object.NextHop)
d.Set("route_dest", object.RouteDest)
d.Set("old_weight", object.Weight)
d.Set("vpn_gateway_id", object.VpnInstanceId)
if object.State == "published" {
d.Set("publish_vpc", true)
} else {
d.Set("publish_vpc", false)
}
return nil
}
func resourceAliyunVpnRouteEntryUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
d.Partial(true)
if d.HasChange("publish_vpc") {
request := vpc.CreatePublishVpnRouteEntryRequest()
request.RegionId = client.RegionId
request.VpnGatewayId = d.Get("vpn_gateway_id").(string)
request.RouteDest = d.Get("route_dest").(string)
request.NextHop = d.Get("next_hop").(string)
request.RouteType = "dbr"
request.PublishVpc = requests.NewBoolean(d.Get("publish_vpc").(bool))
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.PublishVpnRouteEntry(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("public_vpc")
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
if d.HasChange("weight") {
request := vpc.CreateModifyVpnRouteEntryWeightRequest()
oldWeight, newWeight := d.GetChange("weight")
request.RegionId = client.RegionId
request.VpnGatewayId = d.Get("vpn_gateway_id").(string)
request.RouteDest = d.Get("route_dest").(string)
request.NextHop = d.Get("next_hop").(string)
request.Weight = requests.NewInteger(oldWeight.(int))
request.NewWeight = requests.NewInteger(newWeight.(int))
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.ModifyVpnRouteEntryWeight(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("weight")
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
d.Partial(false)
return resourceAliyunVpnRouteEntryRead(d, meta)
}
func resourceAliyunVpnRouteEntryDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpnRouteEntryService := VpnGatewayService{client}
request := vpc.CreateDeleteVpnRouteEntryRequest()
request.RegionId = client.RegionId
request.VpnGatewayId = d.Get("vpn_gateway_id").(string)
request.RouteDest = d.Get("route_dest").(string)
request.NextHop = d.Get("next_hop").(string)
request.Weight = requests.NewInteger(d.Get("weight").(int))
request.ClientToken = buildClientToken(request.GetActionName())
wait := incrementalWait(5*time.Second, 5*time.Second)
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DeleteVpnRouteEntry(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"VpnGateway.Configuring"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return WrapError(vpnRouteEntryService.WaitForVpnRouteEntry(d.Id(), Deleted, DefaultTimeoutMedium))
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudVswitch() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudVswitchCreate,
Read: resourceAlicloudVswitchRead,
Update: resourceAlicloudVswitchUpdate,
Delete: resourceAlicloudVswitchDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"cidr_block": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
"vswitch_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"name"},
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"vswitch_name"},
Deprecated: "Field 'name' has been deprecated from provider version 1.119.0. New field 'vswitch_name' instead.",
},
"vpc_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"zone_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"availability_zone"},
},
"availability_zone": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"zone_id"},
Deprecated: "Field 'availability_zone' has been deprecated from provider version 1.119.0. New field 'zone_id' instead.",
},
},
}
}
func resourceAlicloudVswitchCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
action := "CreateVSwitch"
request := make(map[string]interface{})
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request["CidrBlock"] = d.Get("cidr_block")
if v, ok := d.GetOk("description"); ok {
request["Description"] = v
}
request["RegionId"] = client.RegionId
if v, ok := d.GetOk("vswitch_name"); ok {
request["VSwitchName"] = v
} else if v, ok := d.GetOk("name"); ok {
request["VSwitchName"] = v
}
request["VpcId"] = d.Get("vpc_id")
if v, ok := d.GetOk("zone_id"); ok {
request["ZoneId"] = v
} else if v, ok := d.GetOk("availability_zone"); ok {
request["ZoneId"] = v
} else {
return WrapError(Error(`[ERROR] Argument "availability_zone" or "zone_id" must be set one!`))
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
request["ClientToken"] = buildClientToken("CreateVSwitch")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidCidrBlock.Overlapped", "InvalidStatus.RouteEntry", "OperationFailed.IdempotentTokenProcessing", "TaskConflict", "Throttling", "UnknownError"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_vswitch", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(response["VSwitchId"]))
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, vpcService.VswitchStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudVswitchUpdate(d, meta)
}
func resourceAlicloudVswitchRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
object, err := vpcService.DescribeVswitch(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_vswitch vpcService.DescribeVswitch Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("cidr_block", object["CidrBlock"])
d.Set("description", object["Description"])
d.Set("status", object["Status"])
d.Set("vswitch_name", object["VSwitchName"])
d.Set("name", object["VSwitchName"])
d.Set("vpc_id", object["VpcId"])
d.Set("zone_id", object["ZoneId"])
d.Set("availability_zone", object["ZoneId"])
listTagResourcesObject, err := vpcService.ListTagResources(d.Id(), "VSWITCH")
if err != nil {
return WrapError(err)
}
d.Set("tags", tagsToMap(listTagResourcesObject))
return nil
}
func resourceAlicloudVswitchUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
var response map[string]interface{}
d.Partial(true)
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if d.HasChange("tags") {
if err := vpcService.SetResourceTags(d, "VSWITCH"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
update := false
request := map[string]interface{}{
"VSwitchId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("description") {
update = true
request["Description"] = d.Get("description")
}
request["RegionId"] = client.RegionId
if !d.IsNewResource() && d.HasChange("vswitch_name") {
update = true
request["VSwitchName"] = d.Get("vswitch_name")
}
if !d.IsNewResource() && d.HasChange("name") {
update = true
request["VSwitchName"] = d.Get("name")
}
if update {
action := "ModifyVSwitchAttribute"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("description")
d.SetPartial("name")
d.SetPartial("vswitch_name")
}
d.Partial(false)
return resourceAlicloudVswitchRead(d, meta)
}
func resourceAlicloudVswitchDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
action := "DeleteVSwitch"
var response map[string]interface{}
conn, err := client.NewVpcClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"VSwitchId": d.Id(),
}
request["RegionId"] = client.RegionId
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidVSwitchId.NotFound", "InvalidVswitchID.NotFound"}) {
return nil
}
if IsExpectedErrors(err, []string{"InvalidRegionId.NotFound"}) {
return resource.NonRetryableError(err)
}
wait()
return resource.RetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, vpcService.VswitchStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudWafCertificate() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudWafCertificateCreate,
Read: resourceAlicloudWafCertificateRead,
Update: resourceAlicloudWafCertificateUpdate,
Delete: resourceAlicloudWafCertificateDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"domain": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"certificate": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"certificate_id"},
ForceNew: true,
},
"private_key": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"certificate_id"},
ForceNew: true,
},
"certificate_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"certificate", "private_key", "certificate_name"},
},
"certificate_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"certificate_id"},
},
},
}
}
func resourceAlicloudWafCertificateCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := make(map[string]interface{})
conn, err := client.NewWafClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
if sslId, ok := d.GetOk("certificate_id"); ok {
action := "CreateCertificateByCertificateId"
request["InstanceId"] = d.Get("instance_id")
request["CertificateId"] = sslId.(string)
if v, ok := d.GetOk("domain"); ok {
request["Domain"] = v
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_waf_certificate", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["InstanceId"], ":", request["Domain"], ":", formatInt(response["CertificateId"])))
return resourceAlicloudWafCertificateRead(d, meta)
}
request = make(map[string]interface{})
action := "CreateCertificate"
if v, ok := d.GetOk("certificate"); ok {
request["Certificate"] = v
} else {
return WrapErrorf(err, RequiredWhenMsg, "certificate", "certificate_id", "null")
}
if v, ok := d.GetOk("private_key"); ok {
request["PrivateKey"] = v
} else {
return WrapErrorf(err, RequiredWhenMsg, "private_key", "certificate_id", "null")
}
if v, ok := d.GetOk("certificate_name"); ok {
request["CertificateName"] = v
} else {
return WrapErrorf(err, RequiredWhenMsg, "certificate_name", "certificate_id", "null")
}
request["Domain"] = d.Get("domain")
request["InstanceId"] = d.Get("instance_id")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_waf_certificate", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["InstanceId"], ":", request["Domain"], ":", formatInt(response["CertificateId"])))
return resourceAlicloudWafCertificateRead(d, meta)
}
func resourceAlicloudWafCertificateRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
wafOpenapiService := Waf_openapiService{client}
object, err := wafOpenapiService.DescribeWafCertificate(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_waf_certificate wafOpenapiService.DescribeWafCertificate Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
d.Set("certificate_id", object["CertificateId"])
d.Set("domain", parts[1])
d.Set("instance_id", parts[0])
d.Set("certificate_name", object["CertificateName"])
return nil
}
func resourceAlicloudWafCertificateUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println(fmt.Sprintf("[WARNING] The resouce has not update operation."))
return resourceAlicloudWafCertificateRead(d, meta)
}
func resourceAlicloudWafCertificateDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudWafCertificate. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudWafDomain() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudWafDomainCreate,
Read: resourceAlicloudWafDomainRead,
Update: resourceAlicloudWafDomainUpdate,
Delete: resourceAlicloudWafDomainDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"cluster_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"PhysicalCluster", "VirtualCluster"}, false),
Default: "PhysicalCluster",
},
"cname": {
Type: schema.TypeString,
Computed: true,
},
"connection_time": {
Type: schema.TypeInt,
Optional: true,
Default: 5,
},
"domain_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"domain"},
},
"domain": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Deprecated: "Field 'domain' has been deprecated from version 1.94.0. Use 'domain_name' instead.",
ConflictsWith: []string{"domain_name"},
},
"http2_port": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"http_port": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"http_to_user_ip": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Off", "On"}, false),
Default: "Off",
},
"https_port": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"https_redirect": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"Off", "On"}, false),
Default: "Off",
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"is_access_product": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"Off", "On"}, false),
},
"load_balancing": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"IpHash", "RoundRobin"}, false),
Default: "IpHash",
},
"log_headers": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Optional: true,
},
"value": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"read_time": {
Type: schema.TypeInt,
Optional: true,
Default: 120,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"source_ips": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"write_time": {
Type: schema.TypeInt,
Optional: true,
Default: 120,
},
},
}
}
func resourceAlicloudWafDomainCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
waf_openapiService := Waf_openapiService{client}
var response map[string]interface{}
action := "CreateDomain"
request := make(map[string]interface{})
conn, err := client.NewWafClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("cluster_type"); ok {
request["ClusterType"] = convertClusterTypeRequest(v.(string))
}
if v, ok := d.GetOk("connection_time"); ok {
request["ConnectionTime"] = v
}
if v, ok := d.GetOk("domain_name"); ok {
request["Domain"] = v
} else if v, ok := d.GetOk("domain"); ok {
request["Domain"] = v
} else {
return WrapError(Error(`[ERROR] Argument "domain" or "domain_name" must be set one!`))
}
if v, ok := d.GetOk("http2_port"); ok {
request["Http2Port"] = convertListToJsonString(v.(*schema.Set).List())
}
if v, ok := d.GetOk("http_port"); ok {
request["HttpPort"] = convertListToJsonString(v.(*schema.Set).List())
}
if v, ok := d.GetOk("http_to_user_ip"); ok {
request["HttpToUserIp"] = convertHttpToUserIpRequest(v.(string))
}
if v, ok := d.GetOk("https_port"); ok {
request["HttpsPort"] = convertListToJsonString(v.(*schema.Set).List())
}
if v, ok := d.GetOk("https_redirect"); ok {
request["HttpsRedirect"] = convertHttpsRedirectRequest(v.(string))
}
request["InstanceId"] = d.Get("instance_id")
request["IsAccessProduct"] = convertIsAccessProductRequest(d.Get("is_access_product").(string))
if v, ok := d.GetOk("load_balancing"); ok {
request["LoadBalancing"] = convertLoadBalancingRequest(v.(string))
}
if v, ok := d.GetOk("log_headers"); ok {
logHeaders, err := waf_openapiService.convertLogHeadersToString(v.(*schema.Set).List())
if err != nil {
return WrapError(err)
}
request["LogHeaders"] = logHeaders
}
if v, ok := d.GetOk("read_time"); ok {
request["ReadTime"] = v
}
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
if v, ok := d.GetOk("source_ips"); ok {
request["SourceIps"] = convertListToJsonString(v.(*schema.Set).List())
}
if v, ok := d.GetOk("write_time"); ok {
request["WriteTime"] = v
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_waf_domain", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
d.SetId(fmt.Sprint(request["InstanceId"], ":", request["Domain"]))
return resourceAlicloudWafDomainRead(d, meta)
}
func resourceAlicloudWafDomainRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
waf_openapiService := Waf_openapiService{client}
object, err := waf_openapiService.DescribeWafDomain(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_waf_domain waf_openapiService.DescribeWafDomain Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Set("domain_name", parts[1])
d.Set("domain", parts[1])
d.Set("instance_id", parts[0])
d.Set("cluster_type", convertClusterTypeResponse(formatInt(object["ClusterType"])))
d.Set("cname", object["Cname"])
d.Set("connection_time", formatInt(object["ConnectionTime"]))
d.Set("http2_port", convertJsonStringToStringList(object["Http2Port"]))
d.Set("http_port", convertJsonStringToStringList(object["HttpPort"]))
d.Set("http_to_user_ip", convertHttpToUserIpResponse(formatInt(object["HttpToUserIp"])))
d.Set("https_port", convertJsonStringToStringList(object["HttpsPort"]))
d.Set("https_redirect", convertHttpsRedirectResponse(formatInt(object["HttpsRedirect"])))
d.Set("is_access_product", convertIsAccessProductResponse(formatInt(object["IsAccessProduct"])))
d.Set("load_balancing", convertLoadBalancingResponse(formatInt(object["LoadBalancing"])))
if v, ok := object["LogHeaders"].([]interface{}); ok {
logHeaders := make([]map[string]interface{}, 0)
for _, val := range v {
item := val.(map[string]interface{})
logHeaders = append(logHeaders, map[string]interface{}{
"key": item["k"].(string),
"value": item["v"].(string),
})
}
if err := d.Set("log_headers", logHeaders); err != nil {
return WrapError(err)
}
}
d.Set("read_time", formatInt(object["ReadTime"]))
d.Set("resource_group_id", object["ResourceGroupId"])
d.Set("source_ips", object["SourceIps"])
d.Set("write_time", formatInt(object["WriteTime"]))
return nil
}
func resourceAlicloudWafDomainUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
waf_openapiService := Waf_openapiService{client}
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
d.Partial(true)
if d.HasChange("cluster_type") {
request := map[string]interface{}{
"Domain": parts[1],
"InstanceId": parts[0],
}
request["ClusterType"] = convertClusterTypeRequest(d.Get("cluster_type").(string))
action := "ModifyDomainClusterType"
conn, err := client.NewWafClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("cluster_type")
}
update := false
request := map[string]interface{}{
"Domain": parts[1],
"InstanceId": parts[0],
}
if d.HasChange("is_access_product") {
update = true
}
request["IsAccessProduct"] = convertIsAccessProductRequest(d.Get("is_access_product").(string))
if d.HasChange("connection_time") {
update = true
}
request["ConnectionTime"] = d.Get("connection_time")
if d.HasChange("http2_port") {
update = true
}
request["Http2Port"] = convertListToJsonString(d.Get("http2_port").(*schema.Set).List())
if d.HasChange("http_port") {
update = true
}
request["HttpPort"] = convertListToJsonString(d.Get("http_port").(*schema.Set).List())
if d.HasChange("http_to_user_ip") {
update = true
}
request["HttpToUserIp"] = convertHttpToUserIpRequest(d.Get("http_to_user_ip").(string))
if d.HasChange("https_port") {
update = true
}
request["HttpsPort"] = convertListToJsonString(d.Get("https_port").(*schema.Set).List())
if d.HasChange("https_redirect") {
update = true
}
request["HttpsRedirect"] = convertHttpsRedirectRequest(d.Get("https_redirect").(string))
if d.HasChange("load_balancing") {
update = true
}
request["LoadBalancing"] = convertLoadBalancingRequest(d.Get("load_balancing").(string))
if d.HasChange("log_headers") {
update = true
}
logHeaders, err := waf_openapiService.convertLogHeadersToString(d.Get("log_headers").(*schema.Set).List())
if err != nil {
return WrapError(err)
}
request["LogHeaders"] = logHeaders
if d.HasChange("read_time") {
update = true
}
request["ReadTime"] = d.Get("read_time")
if d.HasChange("source_ips") {
update = true
}
request["SourceIps"] = convertListToJsonString(d.Get("source_ips").(*schema.Set).List())
if d.HasChange("write_time") {
update = true
}
request["WriteTime"] = d.Get("write_time")
if update {
action := "ModifyDomain"
conn, err := client.NewWafClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("is_access_product")
d.SetPartial("connection_time")
d.SetPartial("http2_port")
d.SetPartial("http_port")
d.SetPartial("http_to_user_ip")
d.SetPartial("https_port")
d.SetPartial("https_redirect")
d.SetPartial("load_balancing")
d.SetPartial("log_headers")
d.SetPartial("read_time")
d.SetPartial("source_ips")
d.SetPartial("write_time")
}
d.Partial(false)
return resourceAlicloudWafDomainRead(d, meta)
}
func resourceAlicloudWafDomainDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
action := "DeleteDomain"
var response map[string]interface{}
conn, err := client.NewWafClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"Domain": parts[1],
"InstanceId": parts[0],
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"DomainNotExist"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func convertClusterTypeRequest(source string) int {
switch source {
case "PhysicalCluster":
return 0
case "VirtualCluster":
return 1
}
return 0
}
func convertHttpToUserIpRequest(source string) int {
switch source {
case "Off":
return 0
case "On":
return 1
}
return 0
}
func convertHttpsRedirectRequest(source string) int {
switch source {
case "Off":
return 0
case "On":
return 1
}
return 0
}
func convertIsAccessProductRequest(source string) int {
switch source {
case "Off":
return 0
case "On":
return 1
}
return 0
}
func convertLoadBalancingRequest(source string) int {
switch source {
case "IpHash":
return 0
case "RoundRobin":
return 1
}
return 0
}
func convertClusterTypeResponse(source int) string {
switch source {
case 0:
return "PhysicalCluster"
case 1:
return "VirtualCluster"
}
return ""
}
func convertHttpToUserIpResponse(source int) string {
switch source {
case 0:
return "Off"
case 1:
return "On"
}
return ""
}
func convertHttpsRedirectResponse(source int) string {
switch source {
case 0:
return "Off"
case 1:
return "On"
}
return ""
}
func convertIsAccessProductResponse(source int) string {
switch source {
case 0:
return "Off"
case 1:
return "On"
}
return ""
}
func convertLoadBalancingResponse(source int) string {
switch source {
case 0:
return "IpHash"
case 1:
return "RoundRobin"
}
return ""
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceAlicloudWafInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudWafInstanceCreate,
Read: resourceAlicloudWafInstanceRead,
Update: resourceAlicloudWafInstanceUpdate,
Delete: resourceAlicloudWafInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"big_screen": {
Type: schema.TypeString,
Required: true,
},
"exclusive_ip_package": {
Type: schema.TypeString,
Required: true,
},
"ext_bandwidth": {
Type: schema.TypeString,
Required: true,
},
"ext_domain_package": {
Type: schema.TypeString,
Required: true,
},
"log_storage": {
Type: schema.TypeString,
Required: true,
},
"log_time": {
Type: schema.TypeString,
Required: true,
},
"modify_type": {
Type: schema.TypeString,
Optional: true,
},
"package_code": {
Type: schema.TypeString,
Required: true,
},
"period": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"prefessional_service": {
Type: schema.TypeString,
Required: true,
},
"renew_period": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"renewal_status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
},
"status": {
Type: schema.TypeInt,
Computed: true,
},
"subscription_type": {
Type: schema.TypeString,
Required: true,
},
"waf_log": {
Type: schema.TypeString,
Required: true,
},
"region": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudWafInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "CreateInstance"
request := make(map[string]interface{})
conn, err := client.NewBssopenapiClient()
if err != nil {
return WrapError(err)
}
if v, ok := d.GetOk("period"); ok {
request["Period"] = v
}
request["ProductCode"] = "waf"
request["ProductType"] = "waf"
if v, ok := d.GetOk("renew_period"); ok {
request["RenewPeriod"] = v
}
if v, ok := d.GetOk("renewal_status"); ok {
request["RenewalStatus"] = v
}
region := client.RegionId
if v, ok := d.GetOk("region"); ok && v.(string) != "" {
region = v.(string)
}
request["SubscriptionType"] = d.Get("subscription_type")
request["Parameter"] = []map[string]string{
{
"Code": "BigScreen",
"Value": d.Get("big_screen").(string),
},
{
"Code": "ExclusiveIpPackage",
"Value": d.Get("exclusive_ip_package").(string),
},
{
"Code": "ExtBandwidth",
"Value": d.Get("ext_bandwidth").(string),
},
{
"Code": "ExtDomainPackage",
"Value": d.Get("ext_domain_package").(string),
},
{
"Code": "LogStorage",
"Value": d.Get("log_storage").(string),
},
{
"Code": "LogTime",
"Value": d.Get("log_time").(string),
},
{
"Code": "PackageCode",
"Value": d.Get("package_code").(string),
},
{
"Code": "PrefessionalService",
"Value": d.Get("prefessional_service").(string),
},
{
"Code": "Region",
"Value": region,
},
{
"Code": "WafLog",
"Value": d.Get("waf_log").(string),
},
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-14"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"NotApplicable"}) {
conn.Endpoint = String(connectivity.BssOpenAPIEndpointInternational)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_waf_instance", action, AlibabaCloudSdkGoERROR)
}
if response["Code"].(string) != "Success" {
return WrapErrorf(fmt.Errorf("%v", response), DefaultErrorMsg, "alicloud_waf_instance", action, AlibabaCloudSdkGoERROR)
}
response = response["Data"].(map[string]interface{})
d.SetId(fmt.Sprint(response["InstanceId"]))
return resourceAlicloudWafInstanceUpdate(d, meta)
}
func resourceAlicloudWafInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
waf_openapiService := Waf_openapiService{client}
object, err := waf_openapiService.DescribeWafInstance(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_waf_instance waf_openapiService.DescribeWafInstance Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("status", formatInt(object["InstanceInfo"].(map[string]interface{})["Status"]))
d.Set("subscription_type", object["InstanceInfo"].(map[string]interface{})["SubscriptionType"])
return nil
}
func resourceAlicloudWafInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewBssopenapiClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
update := false
request := map[string]interface{}{
"InstanceId": d.Id(),
}
if !d.IsNewResource() && d.HasChange("subscription_type") {
update = true
}
request["ProductType"] = "waf"
request["SubscriptionType"] = d.Get("subscription_type")
request["ProductCode"] = "waf"
request["ModifyType"] = d.Get("modify_type")
request["Parameter"] = []map[string]string{
{
"Code": "BigScreen",
"Value": d.Get("big_screen").(string),
},
{
"Code": "ExclusiveIpPackage",
"Value": d.Get("exclusive_ip_package").(string),
},
{
"Code": "ExtBandwidth",
"Value": d.Get("ext_bandwidth").(string),
},
{
"Code": "ExtDomainPackage",
"Value": d.Get("ext_domain_package").(string),
},
{
"Code": "LogStorage",
"Value": d.Get("log_storage").(string),
},
{
"Code": "LogTime",
"Value": d.Get("log_time").(string),
},
{
"Code": "PackageCode",
"Value": d.Get("package_code").(string),
},
{
"Code": "PrefessionalService",
"Value": d.Get("prefessional_service").(string),
},
{
"Code": "WafLog",
"Value": d.Get("waf_log").(string),
},
}
if update {
action := "ModifyInstance"
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-14"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"NotApplicable"}) {
conn.Endpoint = String(connectivity.BssOpenAPIEndpointInternational)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
if response["Code"].(string) != "Success" {
return WrapErrorf(fmt.Errorf("%v", response), DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return resourceAlicloudWafInstanceRead(d, meta)
}
func resourceAlicloudWafInstanceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "DeleteInstance"
var response map[string]interface{}
conn, err := client.NewWafClient()
if err != nil {
return WrapError(err)
}
request := map[string]interface{}{
"InstanceId": d.Id(),
}
if v, ok := d.GetOk("resource_group_id"); ok {
request["ResourceGroupId"] = v
}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ComboError"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"fmt"
"log"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceAlicloudWafProtectionModule() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudWafProtectionModuleCreate,
Read: resourceAlicloudWafProtectionModuleRead,
Update: resourceAlicloudWafProtectionModuleUpdate,
Delete: resourceAlicloudWafProtectionModuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"defense_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ac_cc", "antifraud", "dld", "normalized", "waf"}, false),
},
"domain": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"mode": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntInSlice([]int{0, 1, 2}),
},
"status": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntInSlice([]int{0, 1}),
},
},
}
}
func resourceAlicloudWafProtectionModuleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
action := "ModifyProtectionModuleMode"
request := make(map[string]interface{})
conn, err := client.NewWafClient()
if err != nil {
return WrapError(err)
}
request["DefenseType"] = d.Get("defense_type")
request["Domain"] = d.Get("domain")
request["InstanceId"] = d.Get("instance_id")
request["Mode"] = d.Get("mode")
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_waf_protection_module", action, AlibabaCloudSdkGoERROR)
}
d.SetId(fmt.Sprint(request["InstanceId"], ":", request["Domain"], ":", request["DefenseType"]))
return resourceAlicloudWafProtectionModuleUpdate(d, meta)
}
func resourceAlicloudWafProtectionModuleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
wafOpenapiService := Waf_openapiService{client}
object, err := wafOpenapiService.DescribeWafProtectionModule(d.Id())
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_waf_protection_module wafOpenapiService.DescribeWafProtectionModule Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
d.Set("defense_type", parts[2])
d.Set("domain", parts[1])
d.Set("instance_id", parts[0])
d.Set("mode", formatInt(object["Mode"]))
describeProtectionModuleStatusObject, err := wafOpenapiService.DescribeProtectionModuleStatus(d.Id())
if err != nil {
return WrapError(err)
}
d.Set("status", formatInt(describeProtectionModuleStatusObject["ModuleStatus"]))
return nil
}
func resourceAlicloudWafProtectionModuleUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewWafClient()
if err != nil {
return WrapError(err)
}
var response map[string]interface{}
parts, err := ParseResourceId(d.Id(), 3)
if err != nil {
return WrapError(err)
}
d.Partial(true)
request := map[string]interface{}{
"DefenseType": parts[2],
"Domain": parts[1],
"InstanceId": parts[0],
}
update := false
if !d.IsNewResource() && d.HasChange("mode") {
update = true
if v, ok := d.GetOkExists("mode"); ok {
request["Mode"] = v
}
}
if update {
action := "ModifyProtectionModuleMode"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("mode")
}
update = false
if d.IsNewResource() || d.HasChange("status") {
update = true
if v, ok := d.GetOkExists("status"); ok {
request["ModuleStatus"] = v
}
}
if update {
action := "ModifyProtectionModuleStatus"
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
d.SetPartial("status")
}
d.Partial(false)
return resourceAlicloudWafProtectionModuleRead(d, meta)
}
func resourceAlicloudWafProtectionModuleDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudWafProtectionModule. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
package alicloud
import (
"time"
log "github.com/sirupsen/logrus"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/bssopenapi"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
const (
RELEASE_HANG_MINS = 3
)
func resourceAlicloudDbauditInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDbauditInstanceCreate,
Read: resourceAlicloudDbauditInstanceRead,
Update: resourceAlicloudDbauditInstanceUpdate,
Delete: resourceAlicloudDbauditInstanceDelete,
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(20 * time.Minute),
Update: schema.DefaultTimeout(20 * time.Minute),
},
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(1, 64),
},
"plan_code": {
Type: schema.TypeString,
Required: true,
},
"period": {
Type: schema.TypeInt,
ValidateFunc: validation.IntInSlice([]int{1, 3, 6, 12, 24, 36}),
Required: true,
},
"vswitch_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"tags": tagsSchema(),
"resource_group_id": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceAlicloudDbauditInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
request := buildDbauditCreateRequest(d, meta)
var response *bssopenapi.CreateInstanceResponse
err := resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := client.WithBssopenapiClient(func(bssopenapiClient *bssopenapi.Client) (interface{}, error) {
return bssopenapiClient.CreateInstance(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"NotApplicable"}) {
request.RegionId = string(connectivity.APSouthEast1)
request.Domain = connectivity.BssOpenAPIEndpointInternational
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response = raw.(*bssopenapi.CreateInstanceResponse)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_yundun_dbaudit_instance", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
instanceId := response.Data.InstanceId
if !response.Success {
return WrapError(Error(response.Message))
}
d.SetId(instanceId)
dbauditService := DbauditService{client}
// check RAM policy
dbauditService.ProcessRolePolicy()
// wait for order complete
stateConf := BuildStateConf([]string{}, []string{"PENDING"}, d.Timeout(schema.TimeoutCreate), 20*time.Second, dbauditService.DbauditInstanceRefreshFunc(d.Id(), []string{"UPGRADING", "UPGRADE_FAILED", "CREATE_FAILED"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
// start instance
if err := dbauditService.StartDbauditInstance(instanceId, d.Get("vswitch_id").(string)); err != nil {
return WrapError(err)
}
// wait for pending
stateConf = BuildStateConf([]string{"PENDING", "CREATING"}, []string{"RUNNING"}, d.Timeout(schema.TimeoutCreate), 20*time.Second, dbauditService.DbauditInstanceRefreshFunc(d.Id(), []string{"UPGRADING", "UPGRADE_FAILED", "CREATE_FAILED"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return resourceAlicloudDbauditInstanceUpdate(d, meta)
}
func resourceAlicloudDbauditInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dbauditService := DbauditService{client}
instance, err := dbauditService.DescribeYundunDbauditInstance(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
d.Set("description", instance.Description)
//period, err := computePeriodByUnit(instance.StartTime/1000, instance.ExpireTime/1000, d.Get("period").(int), "Month")
//if err != nil {
// return WrapError(err)
//}
//d.Set("period", period)
d.Set("plan_code", instance.LicenseCode)
d.Set("region_id", client.RegionId)
d.Set("vswitch_id", instance.VswitchId)
tags, err := dbauditService.DescribeTags(d.Id(), nil, TagResourceInstance)
if err != nil {
return WrapError(err)
}
d.Set("tags", dbauditService.tagsToMap(tags))
return nil
}
func resourceAlicloudDbauditInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
dbauditService := DbauditService{client}
d.Partial(true)
if d.HasChange("tags") {
if err := dbauditService.setInstanceTags(d, TagResourceInstance); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
}
if d.HasChange("description") {
if err := dbauditService.UpdateDbauditInstanceDescription(d.Id(), d.Get("description").(string)); err != nil {
return WrapError(err)
}
d.SetPartial("description")
}
if d.HasChange("resource_group_id") {
if err := dbauditService.UpdateResourceGroup(d.Id(), d.Get("resource_group_id").(string)); err != nil {
return WrapError(err)
}
d.SetPartial("resource_group_id")
}
if d.IsNewResource() {
d.Partial(false)
return resourceAlicloudDbauditInstanceRead(d, meta)
}
if d.HasChange("plan_code") {
if err := dbauditService.UpdateInstanceSpec("plan_code", "PlanCode", d, meta); err != nil {
return WrapError(err)
}
stateConf := BuildStateConf([]string{"UPGRADING"}, []string{"PENDING", "RUNNING"}, d.Timeout(schema.TimeoutUpdate), 20*time.Second, dbauditService.DbauditInstanceRefreshFunc(d.Id(), []string{"CREATING", "UPGRADE_FAILED", "CREATE_FAILED"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
d.SetPartial("plan_code")
}
d.Partial(false)
// wait for order complete
return resourceAlicloudDbauditInstanceRead(d, meta)
}
func resourceAlicloudDbauditInstanceDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudDbauditInstance. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
func buildDbauditCreateRequest(d *schema.ResourceData, meta interface{}) *bssopenapi.CreateInstanceRequest {
request := bssopenapi.CreateCreateInstanceRequest()
request.ProductCode = "dbaudit"
request.SubscriptionType = "Subscription"
request.Period = requests.NewInteger(d.Get("period").(int))
client := meta.(*connectivity.AliyunClient)
request.Parameter = &[]bssopenapi.CreateInstanceParameter{
// force to buy vpc version
{
Code: "NetworkType",
Value: "vpc",
},
{
Code: "SeriesCode",
Value: "alpha",
},
{
Code: "PlanCode",
Value: d.Get("plan_code").(string),
},
{
Code: "RegionId",
Value: client.RegionId,
},
}
return request
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type ActiontrailService struct {
client *connectivity.AliyunClient
}
func (s *ActiontrailService) DescribeActiontrailTrail(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewActiontrailClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeTrails"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"NameList": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-07-06"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.TrailList", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.TrailList", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ActionTrail", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["Name"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ActionTrail", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *ActiontrailService) ActiontrailTrailStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeActiontrailTrail(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["Status"].(string) == failState {
return object, object["Status"].(string), WrapError(Error(FailedToReachTargetStatus, object["Status"].(string)))
}
}
return object, object["Status"].(string), nil
}
}
func (s *ActiontrailService) DescribeActiontrailHistoryDeliveryJob(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewActiontrailClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetDeliveryHistoryJob"
request := map[string]interface{}{
"JobId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-07-06"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"DeliveryHistoryJobNotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("ActionTrail:HistoryDeliveryJob", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *ActiontrailService) ActiontrailHistoryDeliveryJobStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeActiontrailHistoryDeliveryJob(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["JobStatus"]) == failState {
return object, fmt.Sprint(object["JobStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["JobStatus"])))
}
}
return object, fmt.Sprint(object["JobStatus"]), nil
}
}
package alicloud
import (
"fmt"
"log"
"regexp"
"strings"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/adb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type AdbService struct {
client *connectivity.AliyunClient
}
func (s *AdbService) DescribeAdbCluster(id string) (instance *adb.DBClusterInDescribeDBClusters, err error) {
request := adb.CreateDescribeDBClustersRequest()
request.RegionId = s.client.RegionId
dbClusterIds := []string{}
dbClusterIds = append(dbClusterIds, id)
request.DBClusterIds = id
raw, err := s.client.WithAdbClient(func(adbClient *adb.Client) (interface{}, error) {
return adbClient.DescribeDBClusters(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return nil, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*adb.DescribeDBClustersResponse)
if len(response.Items.DBCluster) < 1 {
return nil, WrapErrorf(Error(GetNotFoundMessage("Cluster", id)), NotFoundMsg, ProviderERROR)
}
return &response.Items.DBCluster[0], nil
}
func (s *AdbService) DescribeAdbClusterAttribute(id string) (instance *adb.DBCluster, err error) {
request := adb.CreateDescribeDBClusterAttributeRequest()
request.RegionId = s.client.RegionId
request.DBClusterId = id
raw, err := s.client.WithAdbClient(func(adbClient *adb.Client) (interface{}, error) {
return adbClient.DescribeDBClusterAttribute(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
return instance, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return instance, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*adb.DescribeDBClusterAttributeResponse)
if len(response.Items.DBCluster) < 1 {
return nil, WrapErrorf(Error(GetNotFoundMessage("Cluster", id)), NotFoundMsg, ProviderERROR)
}
return &response.Items.DBCluster[0], nil
}
func (s *AdbService) DescribeAdbAutoRenewAttribute(id string) (instance *adb.AutoRenewAttribute, err error) {
request := adb.CreateDescribeAutoRenewAttributeRequest()
request.RegionId = s.client.RegionId
request.DBClusterIds = id
raw, err := s.client.WithAdbClient(func(adbClient *adb.Client) (interface{}, error) {
return adbClient.DescribeAutoRenewAttribute(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
return instance, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return instance, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*adb.DescribeAutoRenewAttributeResponse)
if len(response.Items.AutoRenewAttribute) < 1 {
return nil, WrapErrorf(Error(GetNotFoundMessage("Cluster", id)), NotFoundMsg, ProviderERROR)
}
return &response.Items.AutoRenewAttribute[0], nil
}
func (s *AdbService) WaitForAdbConnection(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeAdbConnection(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if status != Deleted && object != nil && object.ConnectionString != "" {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.ConnectionString, id, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *AdbService) DescribeAdbConnection(id string) (*adb.Address, error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
return nil, WrapError(err)
}
deadline := time.Now().Add(time.Duration(DefaultIntervalLong) * time.Second)
for {
object, err := s.DescribeAdbClusterNetInfo(parts[0])
if err != nil {
if NotFoundError(err) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return nil, WrapError(err)
}
if object != nil {
for _, p := range object {
if p.NetType == "Public" {
return &p, nil
}
}
}
time.Sleep(DefaultIntervalMini * time.Second)
if time.Now().After(deadline) {
break
}
}
return nil, WrapErrorf(Error(GetNotFoundMessage("DBConnection", id)), NotFoundMsg, ProviderERROR)
}
func (s *AdbService) DescribeAdbClusterNetInfo(id string) ([]adb.Address, error) {
request := adb.CreateDescribeDBClusterNetInfoRequest()
request.RegionId = s.client.RegionId
request.DBClusterId = id
raw, err := s.client.WithAdbClient(func(adbClient *adb.Client) (interface{}, error) {
return adbClient.DescribeDBClusterNetInfo(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return nil, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*adb.DescribeDBClusterNetInfoResponse)
if len(response.Items.Address) < 1 {
return nil, WrapErrorf(Error(GetNotFoundMessage("DBInstanceNetInfo", id)), NotFoundMsg, ProviderERROR)
}
return response.Items.Address, nil
}
func (s *AdbService) WaitForAdbAccount(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeAdbAccount(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.AccountStatus == string(status) {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.AccountStatus, status, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *AdbService) DescribeAdbAccount(id string) (ds *adb.DBAccount, err error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := adb.CreateDescribeAccountsRequest()
request.RegionId = s.client.RegionId
request.DBClusterId = parts[0]
request.AccountName = parts[1]
invoker := NewInvoker()
invoker.AddCatcher(DBInstanceStatusCatcher)
var response *adb.DescribeAccountsResponse
if err := invoker.Run(func() error {
raw, err := s.client.WithAdbClient(func(adbClient *adb.Client) (interface{}, error) {
return adbClient.DescribeAccounts(request)
})
if err != nil {
return err
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*adb.DescribeAccountsResponse)
return nil
}); err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return nil, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
if len(response.AccountList.DBAccount) < 1 {
return nil, WrapErrorf(Error(GetNotFoundMessage("DBAccount", id)), NotFoundMsg, ProviderERROR)
}
return &response.AccountList.DBAccount[0], nil
}
// WaitForInstance waits for instance to given status
func (s *AdbService) WaitForAdbInstance(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeAdbCluster(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if strings.ToLower(object.DBClusterStatus) == strings.ToLower(string(status)) {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.DBClusterStatus, status, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *AdbService) setClusterTags(d *schema.ResourceData) error {
if d.HasChange("tags") {
oraw, nraw := d.GetChange("tags")
o := oraw.(map[string]interface{})
n := nraw.(map[string]interface{})
create, remove := s.diffTags(s.tagsFromMap(o), s.tagsFromMap(n))
if len(remove) > 0 {
var tagKey []string
for _, v := range remove {
tagKey = append(tagKey, v.Key)
}
request := adb.CreateUntagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.ResourceType = "cluster"
request.TagKey = &tagKey
request.RegionId = s.client.RegionId
raw, err := s.client.WithAdbClient(func(client *adb.Client) (interface{}, error) {
return client.UntagResources(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
if len(create) > 0 {
request := adb.CreateTagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.Tag = &create
request.ResourceType = "cluster"
request.RegionId = s.client.RegionId
raw, err := s.client.WithAdbClient(func(client *adb.Client) (interface{}, error) {
return client.TagResources(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
d.SetPartial("tags")
}
return nil
}
func (s *AdbService) diffTags(oldTags, newTags []adb.TagResourcesTag) ([]adb.TagResourcesTag, []adb.TagResourcesTag) {
// First, we're creating everything we have
create := make(map[string]interface{})
for _, t := range newTags {
create[t.Key] = t.Value
}
// Build the list of what to remove
var remove []adb.TagResourcesTag
for _, t := range oldTags {
old, ok := create[t.Key]
if !ok || old != t.Value {
// Delete it!
remove = append(remove, t)
}
}
return s.tagsFromMap(create), remove
}
func (s *AdbService) tagsToMap(tags []adb.TagResource) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !s.ignoreTag(t) {
result[t.TagKey] = t.TagValue
}
}
return result
}
func (s *AdbService) tagsFromMap(m map[string]interface{}) []adb.TagResourcesTag {
result := make([]adb.TagResourcesTag, 0, len(m))
for k, v := range m {
result = append(result, adb.TagResourcesTag{
Key: k,
Value: v.(string),
})
}
return result
}
func (s *AdbService) ignoreTag(t adb.TagResource) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, t.TagKey)
ok, _ := regexp.MatchString(v, t.TagValue)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific t %s (val: %s), ignoring.\n", t.TagKey, t.TagValue)
return true
}
}
return false
}
func (s *AdbService) DescribeTags(resourceId string, resourceType TagResourceType) (tags []adb.TagResource, err error) {
request := adb.CreateListTagResourcesRequest()
request.RegionId = s.client.RegionId
request.ResourceType = string(resourceType)
request.ResourceId = &[]string{resourceId}
raw, err := s.client.WithAdbClient(func(client *adb.Client) (interface{}, error) {
return client.ListTagResources(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, resourceId, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*adb.ListTagResourcesResponse)
return response.TagResources.TagResource, nil
}
// WaitForCluster waits for cluster to given status
func (s *AdbService) WaitForCluster(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeAdbClusterAttribute(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if strings.ToLower(object.DBClusterStatus) == strings.ToLower(string(status)) {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.DBClusterStatus, status, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *AdbService) DescribeDBSecurityIps(clusterId string) (ips []string, err error) {
request := adb.CreateDescribeDBClusterAccessWhiteListRequest()
request.RegionId = s.client.RegionId
request.DBClusterId = clusterId
raw, err := s.client.WithAdbClient(func(adbClient *adb.Client) (interface{}, error) {
return adbClient.DescribeDBClusterAccessWhiteList(request)
})
if err != nil {
return ips, WrapErrorf(err, DefaultErrorMsg, clusterId, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
resp, _ := raw.(*adb.DescribeDBClusterAccessWhiteListResponse)
var ipstr, separator string
ipsMap := make(map[string]string)
for _, ip := range resp.Items.IPArray {
if ip.DBClusterIPArrayAttribute != "hidden" {
ipstr += separator + ip.SecurityIPList
separator = COMMA_SEPARATED
}
}
for _, ip := range strings.Split(ipstr, COMMA_SEPARATED) {
ipsMap[ip] = ip
}
var finalIps []string
if len(ipsMap) > 0 {
for key := range ipsMap {
finalIps = append(finalIps, key)
}
}
return finalIps, nil
}
func (s *AdbService) ModifyDBSecurityIps(clusterId, ips string) error {
request := adb.CreateModifyDBClusterAccessWhiteListRequest()
request.RegionId = s.client.RegionId
request.DBClusterId = clusterId
request.SecurityIps = ips
raw, err := s.client.WithAdbClient(func(adbClient *adb.Client) (interface{}, error) {
return adbClient.ModifyDBClusterAccessWhiteList(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, clusterId, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
if err := s.WaitForCluster(clusterId, Running, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
return nil
}
func (s *AdbService) DescribeAdbBackupPolicy(id string) (policy *adb.DescribeBackupPolicyResponse, err error) {
request := adb.CreateDescribeBackupPolicyRequest()
request.DBClusterId = id
request.RegionId = s.client.RegionId
raw, err := s.client.WithAdbClient(func(adbClient *adb.Client) (interface{}, error) {
return adbClient.DescribeBackupPolicy(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return policy, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return raw.(*adb.DescribeBackupPolicyResponse), nil
}
func (s *AdbService) ModifyAdbBackupPolicy(clusterId, backupTime, backupPeriod string) error {
request := adb.CreateModifyBackupPolicyRequest()
request.RegionId = s.client.RegionId
request.DBClusterId = clusterId
request.PreferredBackupPeriod = backupPeriod
request.PreferredBackupTime = backupTime
raw, err := s.client.WithAdbClient(func(adbClient *adb.Client) (interface{}, error) {
return adbClient.ModifyBackupPolicy(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, clusterId, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
if err := s.WaitForCluster(clusterId, Running, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
return nil
}
func (s *AdbService) AdbClusterStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeAdbClusterAttribute(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.DBClusterStatus == failState {
return object, object.DBClusterStatus, WrapError(Error(FailedToReachTargetStatus, object.DBClusterStatus))
}
}
return object, object.DBClusterStatus, nil
}
}
func (s *AdbService) DescribeTask(id, taskId string) (*adb.DescribeTaskInfoResponse, error) {
request := adb.CreateDescribeTaskInfoRequest()
request.RegionId = s.client.RegionId
request.DBClusterId = id
request.TaskId = requests.Integer(taskId)
raw, err := s.client.WithAdbClient(func(adbClient *adb.Client) (interface{}, error) {
return adbClient.DescribeTaskInfo(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return nil, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*adb.DescribeTaskInfoResponse)
return response, nil
}
func (s *AdbService) AdbTaskStateRefreshFunc(id, taskId string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeTask(id, taskId)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
return object, object.TaskInfo.Status, nil
}
}
func (s *AdbService) DescribeAutoRenewAttribute(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAdsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeAutoRenewAttribute"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBClusterIds": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Items.AutoRenewAttribute", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Items.AutoRenewAttribute", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("AnalyticDBForMySQL3.0", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["DBClusterId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("AnalyticDBForMySQL3.0", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *AdbService) DescribeDBClusterAccessWhiteList(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAdsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDBClusterAccessWhiteList"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBClusterId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBCluster.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("AnalyticdbForMysql3.0DbCluster", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Items.IPArray", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Items.IPArray", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("AnalyticDBForMySQL3.0", id)), NotFoundWithResponse, response)
} else {
ipList := ""
for _, item := range v.([]interface{}) {
if item.(map[string]interface{})["DBClusterIPArrayAttribute"] == "hidden" {
continue
}
ipList += item.(map[string]interface{})["SecurityIPList"].(string) + ","
}
v.([]interface{})[0].(map[string]interface{})["SecurityIPList"] = strings.TrimSuffix(ipList, ",")
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *AdbService) SetResourceTags(d *schema.ResourceData, resourceType string) error {
if d.HasChange("tags") {
added, removed := parsingTags(d)
conn, err := s.client.NewAdsClient()
if err != nil {
return WrapError(err)
}
removedTagKeys := make([]string, 0)
for _, v := range removed {
if !ignoredTags(v, "") {
removedTagKeys = append(removedTagKeys, v)
}
}
if len(removedTagKeys) > 0 {
action := "UntagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": d.Id(),
}
for i, key := range removedTagKeys {
request[fmt.Sprintf("TagKey.%d", i+1)] = key
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
action := "TagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": d.Id(),
}
count := 1
for key, value := range added {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("tags")
}
return nil
}
func (s *AdbService) DescribeAdbDbCluster(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAdsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDBClusterAttribute"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBClusterId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBCluster.NotFound", "InvalidDBClusterId.NotFoundError"}) {
err = WrapErrorf(Error(GetNotFoundMessage("AdbDbCluster", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Items.DBCluster", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Items.DBCluster", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("AnalyticDBForMySQL3.0", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["DBClusterId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("AnalyticDBForMySQL3.0", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *AdbService) DescribeDBClusters(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAdsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDBClusters"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBClusterIds": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Items.DBCluster", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Items.DBCluster", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("AnalyticDBForMySQL3.0", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["DBClusterId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("AnalyticDBForMySQL3.0", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *AdbService) AdbDbClusterStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeAdbDbCluster(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["DBClusterStatus"].(string) == failState {
return object, object["DBClusterStatus"].(string), WrapError(Error(FailedToReachTargetStatus, object["DBClusterStatus"].(string)))
}
}
return object, object["DBClusterStatus"].(string), nil
}
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type AlbService struct {
client *connectivity.AliyunClient
}
func (s *AlbService) ListAclEntries(id string) (objects []map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAlbClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListAclEntries"
request := map[string]interface{}{
"AclId": id,
"MaxResults": PageSizeLarge,
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ResourceNotFound.Acl"}) {
return objects, WrapErrorf(Error(GetNotFoundMessage("ALB:Acl", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return objects, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.AclEntries", response)
if formatInt(response["TotalCount"]) != 0 && err != nil {
return objects, WrapErrorf(err, FailedGetAttributeMsg, id, "$.AclEntries", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
return objects, nil
}
func (s *AlbService) ListTagResources(id string, resourceType string) (object interface{}, err error) {
conn, err := s.client.NewAlbClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListTagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": id,
}
tags := make([]interface{}, 0)
var response map[string]interface{}
for {
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{Throttling}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.TagResources", response)
if err != nil {
return resource.NonRetryableError(WrapErrorf(err, FailedGetAttributeMsg, id, "$.TagResources", response))
}
if v != nil {
tags = append(tags, v.([]interface{})...)
}
return nil
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
if response["NextToken"] == nil {
break
}
request["NextToken"] = response["NextToken"]
}
return tags, nil
}
func (s *AlbService) SetResourceTags(d *schema.ResourceData, resourceType string) error {
if d.HasChange("tags") {
added, removed := parsingTags(d)
conn, err := s.client.NewAlbClient()
if err != nil {
return WrapError(err)
}
removedTagKeys := make([]string, 0)
for _, v := range removed {
if !ignoredTags(v, "") {
removedTagKeys = append(removedTagKeys, v)
}
}
if len(removedTagKeys) > 0 {
action := "UnTagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": d.Id(),
}
for i, key := range removedTagKeys {
request[fmt.Sprintf("TagKey.%d", i+1)] = key
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
action := "TagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": d.Id(),
}
count := 1
for key, value := range added {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("tags")
}
return nil
}
func (s *AlbService) DescribeAlbAcl(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAlbClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListAcls"
request := map[string]interface{}{
"MaxResults": 100,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Forbidden.Acl"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("ALB:Acl", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
totalCount, err := jsonpath.Get("$.TotalCount", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.TotalCount", response)
}
if fmt.Sprint(totalCount) == "0" {
return object, WrapErrorf(Error(GetNotFoundMessage("ALB", id)), NotFoundWithResponse, response)
}
v, err := jsonpath.Get("$.Acls", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Acls", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ALB", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["AclId"]) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("ALB", id)), NotFoundWithResponse, response)
}
return
}
func (s *AlbService) DescribeAlbSecurityPolicy(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAlbClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListSecurityPolicies"
request := map[string]interface{}{
"MaxResults": 100,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.SecurityPolicies", response)
if formatInt(response["TotalCount"]) == 0 {
return object, WrapErrorf(Error(GetNotFoundMessage("ALB", id)), NotFoundWithResponse, response)
}
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.SecurityPolicies", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ALB", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["SecurityPolicyId"]) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("ALB", id)), NotFoundWithResponse, response)
}
return
}
func (s *AlbService) ListSystemSecurityPolicies(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAlbClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListSystemSecurityPolicies"
request := map[string]interface{}{}
idExist := false
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.SecurityPolicies", response)
if formatInt(response["TotalCount"]) == 0 {
return object, WrapErrorf(Error(GetNotFoundMessage("ALB", id)), NotFoundWithResponse, response)
}
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.SecurityPolicies", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ALB", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["SecurityPolicyId"]) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("ALB", id)), NotFoundWithResponse, response)
}
return object, nil
}
func (s *AlbService) AlbSecurityPolicyStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeAlbSecurityPolicy(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["SecurityPolicyStatus"]) == failState {
return object, fmt.Sprint(object["SecurityPolicyStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["SecurityPolicyStatus"])))
}
}
return object, fmt.Sprint(object["SecurityPolicyStatus"]), nil
}
}
func (s *AlbService) ListServerGroupServers(id string) (object []interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAlbClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListServerGroupServers"
request := map[string]interface{}{
"ServerGroupId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, _ := jsonpath.Get("$.Servers", response)
if v == nil {
return object, nil
}
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["ServerGroupId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ALB", id)), NotFoundWithResponse, response)
}
return v.([]interface{}), nil
}
func (s *AlbService) DescribeAlbServerGroup(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAlbClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListServerGroups"
request := map[string]interface{}{
"MaxResults": 100,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.ServerGroups", response)
if formatInt(response["TotalCount"]) != 0 && err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ServerGroups", response)
}
if v != nil {
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["ServerGroupId"]) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("ALB", id)), NotFoundWithResponse, response)
}
return
}
func (s *AlbService) AlbServerGroupStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeAlbServerGroup(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["ServerGroupStatus"]) == failState {
return object, fmt.Sprint(object["ServerGroupStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["ServerGroupStatus"])))
}
}
return object, fmt.Sprint(object["ServerGroupStatus"]), nil
}
}
func (s *AlbService) DescribeAlbLoadBalancer(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAlbClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetLoadBalancerAttribute"
request := map[string]interface{}{
"LoadBalancerId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ResourceNotFound.LoadBalancer"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("ALB:LoadBalancer", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *AlbService) GetLoadBalancerAttribute(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAlbClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetLoadBalancerAttribute"
request := map[string]interface{}{
"LoadBalancerId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ResourceNotFound.LoadBalancer"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("ALB:LoadBalancer", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *AlbService) AlbLoadBalancerStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeAlbLoadBalancer(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["LoadBalancerStatus"]) == failState {
return object, fmt.Sprint(object["LoadBalancerStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["LoadBalancerStatus"])))
}
}
return object, fmt.Sprint(object["LoadBalancerStatus"]), nil
}
}
func (s *AlbService) AlbAclStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeAlbAcl(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["AclStatus"]) == failState {
return object, fmt.Sprint(object["AclStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["AclStatus"])))
}
}
return object, fmt.Sprint(object["AclStatus"]), nil
}
}
func (s *AlbService) AlbListenerStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeAlbListener(id)
if err != nil {
if NotFoundError(err) {
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["ListenerStatus"]) == failState {
return object, fmt.Sprint(object["ListenerStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["ListenerStatus"])))
}
}
return object, fmt.Sprint(object["ListenerStatus"]), nil
}
}
func (s *AlbService) DescribeAlbListener(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAlbClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetListenerAttribute"
request := map[string]interface{}{
"ListenerId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ResourceNotFound.Listener"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("ALB:Listener", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *AlbService) DescribeAlbRule(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAlbClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListRules"
request := map[string]interface{}{
"MaxResults": PageSizeLarge,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Rules", response)
if formatInt(response["TotalCount"]) != 0 && err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Rules", response)
}
if val, ok := v.([]interface{}); !ok || len(val) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ALB", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["RuleId"]) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("ALB", id)), NotFoundWithResponse, response)
}
return
}
func (s *AlbService) AlbRuleStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeAlbRule(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["RuleStatus"]) == failState {
return object, fmt.Sprint(object["RuleStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["RuleStatus"])))
}
}
return object, fmt.Sprint(object["RuleStatus"]), nil
}
}
func (s *AlbService) DescribeAlbHealthCheckTemplate(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAlbClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetHealthCheckTemplateAttribute"
request := map[string]interface{}{
"HealthCheckTemplateId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ResourceNotFound.HealthCheckTemplate"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("ALB:HealthCheckTemplate", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/alidns"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type AlidnsService struct {
client *connectivity.AliyunClient
}
func (s *AlidnsService) DescribeAlidnsDomainGroup(id string) (object alidns.DomainGroup, err error) {
request := alidns.CreateDescribeDomainGroupsRequest()
request.RegionId = s.client.RegionId
request.PageNumber = requests.NewInteger(1)
request.PageSize = requests.NewInteger(20)
for {
raw, err := s.client.WithAlidnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.DescribeDomainGroups(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*alidns.DescribeDomainGroupsResponse)
if len(response.DomainGroups.DomainGroup) < 1 {
err = WrapErrorf(Error(GetNotFoundMessage("AlidnsDomainGroup", id)), NotFoundMsg, ProviderERROR, response.RequestId)
return object, err
}
for _, object := range response.DomainGroups.DomainGroup {
if object.GroupId == id {
return object, nil
}
}
if len(response.DomainGroups.DomainGroup) < PageSizeMedium {
break
}
if page, err := getNextpageNumber(request.PageNumber); err != nil {
return object, WrapError(err)
} else {
request.PageNumber = page
}
}
err = WrapErrorf(Error(GetNotFoundMessage("AlidnsDomainGroup", id)), NotFoundMsg, ProviderERROR)
return
}
func (s *AlidnsService) DescribeAlidnsRecord(id string) (object alidns.DescribeDomainRecordInfoResponse, err error) {
request := alidns.CreateDescribeDomainRecordInfoRequest()
request.RegionId = s.client.RegionId
request.RecordId = id
raw, err := s.client.WithAlidnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.DescribeDomainRecordInfo(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"DomainRecordNotBelongToUser", "InvalidRR.NoExist"}) {
err = WrapErrorf(Error(GetNotFoundMessage("AlidnsRecord", id)), NotFoundMsg, ProviderERROR)
return
}
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*alidns.DescribeDomainRecordInfoResponse)
return *response, nil
}
func (s *AlidnsService) ListTagResources(id string) (object alidns.ListTagResourcesResponse, err error) {
request := alidns.CreateListTagResourcesRequest()
request.RegionId = s.client.RegionId
request.ResourceType = "DOMAIN"
request.ResourceId = &[]string{id}
raw, err := s.client.WithAlidnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.ListTagResources(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*alidns.ListTagResourcesResponse)
return *response, nil
}
func (s *AlidnsService) SetResourceTags(d *schema.ResourceData, resourceType string) error {
oldItems, newItems := d.GetChange("tags")
added := make([]alidns.TagResourcesTag, 0)
for key, value := range newItems.(map[string]interface{}) {
added = append(added, alidns.TagResourcesTag{
Key: key,
Value: value.(string),
})
}
removed := make([]string, 0)
for key, _ := range oldItems.(map[string]interface{}) {
removed = append(removed, key)
}
if len(removed) > 0 {
request := alidns.CreateUntagResourcesRequest()
request.RegionId = s.client.RegionId
request.ResourceId = &[]string{d.Id()}
request.ResourceType = resourceType
request.TagKey = &removed
raw, err := s.client.WithAlidnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.UntagResources(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
request := alidns.CreateTagResourcesRequest()
request.RegionId = s.client.RegionId
request.ResourceId = &[]string{d.Id()}
request.ResourceType = resourceType
request.Tag = &added
raw, err := s.client.WithAlidnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.TagResources(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
return nil
}
func (s *AlidnsService) DescribeAlidnsDomain(id string) (object alidns.DescribeDomainInfoResponse, err error) {
request := alidns.CreateDescribeDomainInfoRequest()
request.RegionId = s.client.RegionId
request.DomainName = id
raw, err := s.client.WithAlidnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.DescribeDomainInfo(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDomainName.NoExist"}) {
err = WrapErrorf(Error(GetNotFoundMessage("AlidnsDomain", id)), NotFoundMsg, ProviderERROR)
return
}
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*alidns.DescribeDomainInfoResponse)
return *response, nil
}
func (s *AlidnsService) DescribeAlidnsInstance(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAlidnsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDnsProductInstance"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"InstanceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(11*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDnsProduct"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Alidns:Instance", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *AlidnsService) QueryAvailableInstances(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewBssopenapiClient()
if err != nil {
return nil, WrapError(err)
}
action := "QueryAvailableInstances"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"InstanceIDs": id,
"ProductCode": "dns",
"ProductType": "alidns_pre",
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(11*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-14"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"NotApplicable"}) {
conn.Endpoint = String(connectivity.BssOpenAPIEndpointInternational)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDnsProduct"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Alidns:Instance", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Data.InstanceList", response)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
res, _ := v.([]interface{})
if len(res) < 1 || res[0].(map[string]interface{})["InstanceID"].(string) != id {
return nil, WrapErrorf(Error(GetNotFoundMessage("Alidns:Instance", id)), NotFoundWithResponse, response)
}
object = res[0].(map[string]interface{})
return object, nil
}
func (s *AlidnsService) DescribeAlidnsCustomLine(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAlidnsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeCustomLine"
request := map[string]interface{}{
"LineId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"DnsCustomLine.NotExists"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Alidns::CustomLine", id)), NotFoundMsg, ProviderERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *AlidnsService) DescribeCustomLine(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAlidnsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeCustomLine"
request := map[string]interface{}{
"LineId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"DnsCustomLine.NotExists"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Alidns::CustomLine", id)), NotFoundMsg, ProviderERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *AlidnsService) DescribeAlidnsGtmInstance(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAlidnsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDnsGtmInstance"
request := map[string]interface{}{
"InstanceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"DnsGtmInstance.NotExists"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Alidns:GtmInstance", id)), NotFoundWithResponse, response)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *AlidnsService) DescribeAlidnsAddressPool(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAlidnsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDnsGtmInstanceAddressPool"
request := map[string]interface{}{
"AddrPoolId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"DnsGtmAddrPool.NotExists"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Alidns::AddressPool", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *AlidnsService) DescribeAlidnsAccessStrategy(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAlidnsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDnsGtmAccessStrategy"
request := map[string]interface{}{
"StrategyId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"DnsGtmAccessStrategy.NotExists"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Alidns:DnsGtmAccessStrategy", id)), NotFoundWithResponse, response)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *AlidnsService) DescribeAlidnsMonitorConfig(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAlidnsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDnsGtmMonitorConfig"
request := map[string]interface{}{
"MonitorConfigId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"log"
"regexp"
"strings"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/aliyun/alibaba-cloud-sdk-go/services/alikafka"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
)
type AlikafkaService struct {
client *connectivity.AliyunClient
}
func (alikafkaService *AlikafkaService) DescribeAlikafkaInstance(instanceId string) (*alikafka.InstanceVO, error) {
alikafkaInstance := &alikafka.InstanceVO{}
instanceListReq := alikafka.CreateGetInstanceListRequest()
instanceListReq.RegionId = alikafkaService.client.RegionId
wait := incrementalWait(2*time.Second, 1*time.Second)
var raw interface{}
var err error
err = resource.Retry(10*time.Minute, func() *resource.RetryError {
raw, err = alikafkaService.client.WithAlikafkaClient(func(client *alikafka.Client) (interface{}, error) {
return client.GetInstanceList(instanceListReq)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(instanceListReq.GetActionName(), raw, instanceListReq.RpcRequest, instanceListReq)
return nil
})
if err != nil {
return alikafkaInstance, WrapErrorf(err, DefaultErrorMsg, instanceId, instanceListReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
instanceListResp, _ := raw.(*alikafka.GetInstanceListResponse)
addDebug(instanceListReq.GetActionName(), raw, instanceListReq.RpcRequest, instanceListReq)
for _, v := range instanceListResp.InstanceList.InstanceVO {
// ServiceStatus equals 10 means the instance is released, do not return the instance.
if v.InstanceId == instanceId && v.ServiceStatus != 10 {
return &v, nil
}
}
return alikafkaInstance, WrapErrorf(Error(GetNotFoundMessage("AlikafkaInstance", instanceId)), NotFoundMsg, ProviderERROR)
}
func (alikafkaService *AlikafkaService) DescribeAlikafkaNodeStatus(instanceId string) (*alikafka.StatusList, error) {
alikafkaStatusList := &alikafka.StatusList{}
describeNodeStatusReq := alikafka.CreateDescribeNodeStatusRequest()
describeNodeStatusReq.RegionId = alikafkaService.client.RegionId
describeNodeStatusReq.InstanceId = instanceId
wait := incrementalWait(2*time.Second, 1*time.Second)
var raw interface{}
var err error
err = resource.Retry(10*time.Minute, func() *resource.RetryError {
raw, err = alikafkaService.client.WithAlikafkaClient(func(client *alikafka.Client) (interface{}, error) {
return client.DescribeNodeStatus(describeNodeStatusReq)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(describeNodeStatusReq.GetActionName(), raw, describeNodeStatusReq.RpcRequest, describeNodeStatusReq)
return nil
})
if err != nil {
return alikafkaStatusList, WrapErrorf(err, DefaultErrorMsg, instanceId, describeNodeStatusReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
describeNodeStatusResp, _ := raw.(*alikafka.DescribeNodeStatusResponse)
addDebug(describeNodeStatusReq.GetActionName(), raw, describeNodeStatusReq.RpcRequest, describeNodeStatusReq)
return &describeNodeStatusResp.StatusList, nil
}
func (alikafkaService *AlikafkaService) DescribeAlikafkaInstanceByOrderId(orderId string, timeout int) (*alikafka.InstanceVO, error) {
alikafkaInstance := &alikafka.InstanceVO{}
instanceListReq := alikafka.CreateGetInstanceListRequest()
instanceListReq.RegionId = alikafkaService.client.RegionId
instanceListReq.OrderId = orderId
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
wait := incrementalWait(2*time.Second, 1*time.Second)
var raw interface{}
var err error
err = resource.Retry(10*time.Minute, func() *resource.RetryError {
raw, err = alikafkaService.client.WithAlikafkaClient(func(client *alikafka.Client) (interface{}, error) {
return client.GetInstanceList(instanceListReq)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(instanceListReq.GetActionName(), raw, instanceListReq.RpcRequest, instanceListReq)
return nil
})
if err != nil {
return alikafkaInstance, WrapErrorf(err, DefaultErrorMsg, orderId, instanceListReq.GetActionName(), AlibabaCloudSdkGoERROR)
}
instanceListResp, _ := raw.(*alikafka.GetInstanceListResponse)
addDebug(instanceListReq.GetActionName(), raw, instanceListReq.RpcRequest, instanceListReq)
for _, v := range instanceListResp.InstanceList.InstanceVO {
return &v, nil
}
if time.Now().After(deadline) {
return alikafkaInstance, WrapErrorf(Error(GetNotFoundMessage("AlikafkaInstance", orderId)), NotFoundMsg, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (alikafkaService *AlikafkaService) DescribeAlikafkaConsumerGroup(id string) (*alikafka.ConsumerVO, error) {
alikafkaConsumerGroup := &alikafka.ConsumerVO{}
parts, err := ParseResourceId(id, 2)
if err != nil {
return alikafkaConsumerGroup, WrapError(err)
}
instanceId := parts[0]
consumerId := parts[1]
request := alikafka.CreateGetConsumerListRequest()
request.InstanceId = instanceId
request.RegionId = alikafkaService.client.RegionId
wait := incrementalWait(2*time.Second, 1*time.Second)
var raw interface{}
err = resource.Retry(10*time.Minute, func() *resource.RetryError {
raw, err = alikafkaService.client.WithAlikafkaClient(func(client *alikafka.Client) (interface{}, error) {
return client.GetConsumerList(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return alikafkaConsumerGroup, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
consumerListResp, _ := raw.(*alikafka.GetConsumerListResponse)
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
for _, v := range consumerListResp.ConsumerList.ConsumerVO {
if v.ConsumerId == consumerId {
return &v, nil
}
}
return alikafkaConsumerGroup, WrapErrorf(Error(GetNotFoundMessage("AlikafkaConsumerGroup", id)), NotFoundMsg, ProviderERROR)
}
func (alikafkaService *AlikafkaService) DescribeAlikafkaTopicStatus(id string) (*alikafka.TopicStatus, error) {
alikafkaTopicStatus := &alikafka.TopicStatus{}
parts, err := ParseResourceId(id, 2)
if err != nil {
return alikafkaTopicStatus, WrapError(err)
}
instanceId := parts[0]
topic := parts[1]
request := alikafka.CreateGetTopicStatusRequest()
request.InstanceId = instanceId
request.RegionId = alikafkaService.client.RegionId
request.Topic = topic
wait := incrementalWait(3*time.Second, 5*time.Second)
var raw interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.GetTopicStatus(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return alikafkaTopicStatus, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
topicStatusResp, _ := raw.(*alikafka.GetTopicStatusResponse)
if topicStatusResp.TopicStatus.OffsetTable.OffsetTableItem != nil {
return &topicStatusResp.TopicStatus, nil
}
return alikafkaTopicStatus, WrapErrorf(Error(GetNotFoundMessage("AlikafkaTopicStatus "+ResourceNotfound, id)), ResourceNotfound)
}
func (alikafkaService *AlikafkaService) DescribeAlikafkaTopic(id string) (*alikafka.TopicVO, error) {
alikafkaTopic := &alikafka.TopicVO{}
parts, err := ParseResourceId(id, 2)
if err != nil {
return alikafkaTopic, WrapError(err)
}
instanceId := parts[0]
topic := parts[1]
request := alikafka.CreateGetTopicListRequest()
request.InstanceId = instanceId
request.RegionId = alikafkaService.client.RegionId
wait := incrementalWait(3*time.Second, 5*time.Second)
var raw interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.GetTopicList(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return alikafkaTopic, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
topicListResp, _ := raw.(*alikafka.GetTopicListResponse)
for _, v := range topicListResp.TopicList.TopicVO {
if v.Topic == topic {
return &v, nil
}
}
return alikafkaTopic, WrapErrorf(Error(GetNotFoundMessage("AlikafkaTopic", id)), NotFoundMsg, ProviderERROR)
}
func (alikafkaService *AlikafkaService) DescribeAlikafkaSaslUser(id string) (*alikafka.SaslUserVO, error) {
alikafkaSaslUser := &alikafka.SaslUserVO{}
parts, err := ParseResourceId(id, 2)
if err != nil {
return alikafkaSaslUser, WrapError(err)
}
instanceId := parts[0]
username := parts[1]
request := alikafka.CreateDescribeSaslUsersRequest()
request.InstanceId = instanceId
request.RegionId = alikafkaService.client.RegionId
wait := incrementalWait(3*time.Second, 5*time.Second)
var raw interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.DescribeSaslUsers(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return alikafkaSaslUser, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
userListResp, _ := raw.(*alikafka.DescribeSaslUsersResponse)
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
for _, v := range userListResp.SaslUserList.SaslUserVO {
if v.Username == username {
return &v, nil
}
}
return alikafkaSaslUser, WrapErrorf(Error(GetNotFoundMessage("AlikafkaSaslUser", id)), NotFoundMsg, ProviderERROR)
}
func (alikafkaService *AlikafkaService) DescribeAlikafkaSaslAcl(id string) (*alikafka.KafkaAclVO, error) {
alikafkaSaslAcl := &alikafka.KafkaAclVO{}
parts, err := ParseResourceId(id, 6)
if err != nil {
return alikafkaSaslAcl, WrapError(err)
}
instanceId := parts[0]
username := parts[1]
aclResourceType := parts[2]
aclResourceName := parts[3]
aclResourcePatternType := parts[4]
aclOperationType := parts[5]
request := alikafka.CreateDescribeAclsRequest()
request.InstanceId = instanceId
request.RegionId = alikafkaService.client.RegionId
request.Username = username
request.AclResourceType = aclResourceType
request.AclResourceName = aclResourceName
wait := incrementalWait(3*time.Second, 5*time.Second)
var raw interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = alikafkaService.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.DescribeAcls(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"BIZ_SUBSCRIPTION_NOT_FOUND", "BIZ_TOPIC_NOT_FOUND"}) {
return alikafkaSaslAcl, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return alikafkaSaslAcl, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
aclListResp, _ := raw.(*alikafka.DescribeAclsResponse)
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
for _, v := range aclListResp.KafkaAclList.KafkaAclVO {
if v.AclResourcePatternType == aclResourcePatternType && v.AclOperationType == aclOperationType {
return &v, nil
}
}
return alikafkaSaslAcl, WrapErrorf(Error(GetNotFoundMessage("AlikafkaSaslAcl", id)), NotFoundMsg, ProviderERROR)
}
func (s *AlikafkaService) WaitForAlikafkaInstanceUpdated(id string, topicQuota int, diskSize int, ioMax int,
eipMax int, paidType int, specType string, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeAlikafkaInstance(id)
if err != nil {
return WrapError(err)
}
// Wait for all variables be equal.
if object.InstanceId == id && object.TopicNumLimit == topicQuota && object.DiskSize == diskSize && object.IoMax == ioMax && object.EipMax == eipMax && object.PaidType == paidType && object.SpecType == specType {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.InstanceId, id, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *AlikafkaService) WaitForAlikafkaInstance(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeAlikafkaInstance(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
// Process wait for running.
if object.InstanceId == id && status == Running {
// ServiceStatus equals 5, means the server is in service.
if object.ServiceStatus == 5 {
return nil
}
} else if object.InstanceId == id {
// If target status is not deleted and found a instance, return.
if status != Deleted {
return nil
} else {
// ServiceStatus equals 10, means the server is in released.
if object.ServiceStatus == 10 {
return nil
}
}
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.InstanceId, id, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *AlikafkaService) WaitForAllAlikafkaNodeRelease(id string, status string, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeAlikafkaNodeStatus(id)
if err != nil {
if NotFoundError(err) {
return nil
} else {
return WrapError(err)
}
}
// Process wait for all node become released.
allReleased := true
for _, v := range object.Status {
if v != status && !strings.HasSuffix(v, status) {
allReleased = false
}
}
if allReleased {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object, id, ProviderERROR)
}
time.Sleep(DefaultIntervalMedium * time.Second)
}
}
func (s *AlikafkaService) WaitForAlikafkaConsumerGroup(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeAlikafkaConsumerGroup(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.InstanceId+":"+object.ConsumerId == id && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.InstanceId+":"+object.ConsumerId, id, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *AlikafkaService) KafkaTopicStatusRefreshFunc(id string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeAlikafkaTopicStatus(id)
if err != nil {
if !IsExpectedErrors(err, []string{ResourceNotfound}) {
return nil, "", WrapError(err)
}
}
if object.OffsetTable.OffsetTableItem != nil && len(object.OffsetTable.OffsetTableItem) > 0 {
return object, "Running", WrapError(err)
}
return object, "Creating", nil
}
}
func (s *AlikafkaService) WaitForAlikafkaTopic(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeAlikafkaTopic(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.InstanceId+":"+object.Topic == id && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.InstanceId+":"+object.Topic, id, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *AlikafkaService) WaitForAlikafkaSaslUser(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
parts, err := ParseResourceId(id, 2)
if err != nil {
return WrapError(err)
}
instanceId := parts[0]
for {
object, err := s.DescribeAlikafkaSaslUser(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if instanceId+":"+object.Username == id && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, instanceId+":"+object.Username, id, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *AlikafkaService) WaitForAlikafkaSaslAcl(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
parts, err := ParseResourceId(id, 6)
if err != nil {
return WrapError(err)
}
instanceId := parts[0]
for {
object, err := s.DescribeAlikafkaSaslAcl(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if instanceId+":"+object.Username+":"+object.AclResourceType+":"+object.AclResourceName+":"+object.AclResourcePatternType+":"+object.AclOperationType == id && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, instanceId+":"+object.Username, id, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *AlikafkaService) DescribeTags(resourceId string, resourceTags map[string]interface{}, resourceType TagResourceType) (tags []alikafka.TagResource, err error) {
request := alikafka.CreateListTagResourcesRequest()
request.RegionId = s.client.RegionId
request.ResourceType = string(resourceType)
request.ResourceId = &[]string{resourceId}
if resourceTags != nil && len(resourceTags) > 0 {
var reqTags []alikafka.ListTagResourcesTag
for key, value := range resourceTags {
reqTags = append(reqTags, alikafka.ListTagResourcesTag{
Key: key,
Value: value.(string),
})
}
request.Tag = &reqTags
}
wait := incrementalWait(3*time.Second, 5*time.Second)
var raw interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithAlikafkaClient(func(alikafkaClient *alikafka.Client) (interface{}, error) {
return alikafkaClient.ListTagResources(request)
})
if err != nil {
if IsExpectedErrors(err, []string{Throttling, ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, resourceId, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
response, _ := raw.(*alikafka.ListTagResourcesResponse)
return response.TagResources.TagResource, nil
}
func (s *AlikafkaService) setInstanceTags(d *schema.ResourceData, resourceType TagResourceType) error {
if d.HasChange("tags") {
oraw, nraw := d.GetChange("tags")
o := oraw.(map[string]interface{})
n := nraw.(map[string]interface{})
create, remove := s.diffTags(s.tagsFromMap(o), s.tagsFromMap(n))
if len(remove) > 0 {
var tagKey []string
for _, v := range remove {
tagKey = append(tagKey, v.Key)
}
request := alikafka.CreateUntagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.ResourceType = string(resourceType)
request.TagKey = &tagKey
request.RegionId = s.client.RegionId
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithAlikafkaClient(func(client *alikafka.Client) (interface{}, error) {
return client.UntagResources(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
if len(create) > 0 {
request := alikafka.CreateTagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.Tag = &create
request.ResourceType = string(resourceType)
request.RegionId = s.client.RegionId
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithAlikafkaClient(func(client *alikafka.Client) (interface{}, error) {
return client.TagResources(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ONS_SYSTEM_FLOW_CONTROL"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("tags")
}
return nil
}
func (s *AlikafkaService) tagsToMap(tags []alikafka.TagResource) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !s.ignoreTag(t) {
result[t.TagKey] = t.TagValue
}
}
return result
}
func (s *AlikafkaService) ignoreTag(t alikafka.TagResource) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, t.TagKey)
ok, _ := regexp.MatchString(v, t.TagKey)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific t %s (val: %s), ignoring.\n", t.TagKey, t.TagValue)
return true
}
}
return false
}
func (s *AlikafkaService) tagVOTagsToMap(tags []alikafka.TagVO) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !s.tagVOIgnoreTag(t) {
result[t.Key] = t.Value
}
}
return result
}
func (s *AlikafkaService) tagVOIgnoreTag(t alikafka.TagVO) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, t.Key)
ok, _ := regexp.MatchString(v, t.Key)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific t %s (val: %s), ignoring.\n", t.Key, t.Value)
return true
}
}
return false
}
func (s *AlikafkaService) diffTags(oldTags, newTags []alikafka.TagResourcesTag) ([]alikafka.TagResourcesTag, []alikafka.TagResourcesTag) {
// First, we're creating everything we have
create := make(map[string]interface{})
for _, t := range newTags {
create[t.Key] = t.Value
}
// Build the list of what to remove
var remove []alikafka.TagResourcesTag
for _, t := range oldTags {
old, ok := create[t.Key]
if !ok || old != t.Value {
// Delete it!
remove = append(remove, t)
}
}
return s.tagsFromMap(create), remove
}
func (s *AlikafkaService) tagsFromMap(m map[string]interface{}) []alikafka.TagResourcesTag {
result := make([]alikafka.TagResourcesTag, 0, len(m))
for k, v := range m {
result = append(result, alikafka.TagResourcesTag{
Key: k,
Value: v.(string),
})
}
return result
}
func (s *AlikafkaService) GetAllowedIpList(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAlikafkaClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetAllowedIpList"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"InstanceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-16"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type AmqpOpenService struct {
client *connectivity.AliyunClient
}
func (s *AmqpOpenService) DescribeAmqpVirtualHost(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewOnsproxyClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListVirtualHosts"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"InstanceId": parts[0],
"MaxResults": 100,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-12-12"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Data.VirtualHosts", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data.VirtualHosts", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("Amqp", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["Name"]) == parts[1] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("Amqp", id)), NotFoundWithResponse, response)
}
return
}
func (s *AmqpOpenService) DescribeAmqpQueue(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewOnsproxyClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListQueues"
parts, err := ParseResourceId(id, 3)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"InstanceId": parts[0],
"VirtualHost": parts[1],
"MaxResults": 100,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-12-12"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Data.Queues", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data.Queues", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("Amqp", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["Name"]) == parts[2] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("Amqp", id)), NotFoundWithResponse, response)
}
return
}
func (s *AmqpOpenService) DescribeAmqpExchange(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewOnsproxyClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListExchanges"
parts, err := ParseResourceId(id, 3)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"InstanceId": parts[0],
"VirtualHost": parts[1],
"MaxResults": 100,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-12-12"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Data.Exchanges", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data.Exchanges", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("Amqp", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["Name"]) == parts[2] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("Amqp", id)), NotFoundWithResponse, response)
}
return
}
func (s *AmqpOpenService) DescribeAmqpInstance(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewOnsproxyClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListInstances"
request := map[string]interface{}{
"MaxResults": 100,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-12-12"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Data.Instances", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data.Instances", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("Amqp", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["InstanceId"]) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("Amqp", id)), NotFoundWithResponse, response)
}
return
}
func (s *AmqpOpenService) AmqpInstanceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeAmqpInstance(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *AmqpOpenService) DescribeAmqpBinding(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewOnsproxyClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListBindings"
parts, err := ParseResourceId(id, 4)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"InstanceId": parts[0],
"VirtualHost": parts[1],
"MaxResults": 100,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-12-12"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Data.Bindings", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data.Bindings", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("Amqp", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["SourceExchange"]) == parts[2] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("Amqp", id)), NotFoundWithResponse, response)
}
return
}
package alicloud
import (
"fmt"
"log"
"regexp"
"strconv"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cloudapi"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
)
type CloudApiService struct {
client *connectivity.AliyunClient
}
func (s *CloudApiService) DescribeApiGatewayGroup(id string) (*cloudapi.DescribeApiGroupResponse, error) {
apiGroup := &cloudapi.DescribeApiGroupResponse{}
request := cloudapi.CreateDescribeApiGroupRequest()
request.RegionId = s.client.RegionId
request.GroupId = id
raw, err := s.client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.DescribeApiGroup(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"NotFoundApiGroup"}) {
return apiGroup, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return apiGroup, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
apiGroup, _ = raw.(*cloudapi.DescribeApiGroupResponse)
if apiGroup.GroupId == "" {
return apiGroup, WrapErrorf(Error(GetNotFoundMessage("ApiGatewayGroup", id)), NotFoundMsg, ProviderERROR)
}
return apiGroup, nil
}
func (s *CloudApiService) WaitForApiGatewayGroup(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeApiGatewayGroup(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if string(object.GroupId) == id && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, string(object.GroupId), id, ProviderERROR)
}
}
}
func (s *CloudApiService) DescribeApiGatewayApp(id string) (*cloudapi.DescribeAppResponse, error) {
app := &cloudapi.DescribeAppResponse{}
request := cloudapi.CreateDescribeAppRequest()
request.RegionId = s.client.RegionId
request.AppId = requests.Integer(id)
raw, err := s.client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.DescribeApp(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"NotFoundApp"}) {
return app, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return app, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
app, _ = raw.(*cloudapi.DescribeAppResponse)
return app, nil
}
func (s *CloudApiService) WaitForApiGatewayApp(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeApiGatewayApp(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if fmt.Sprint(object.AppId) == id && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, fmt.Sprint(object.AppId), id, ProviderERROR)
}
}
}
func (s *CloudApiService) DescribeApiGatewayApi(id string) (*cloudapi.DescribeApiResponse, error) {
api := &cloudapi.DescribeApiResponse{}
parts, err := ParseResourceId(id, 2)
if err != nil {
return api, WrapError(err)
}
request := cloudapi.CreateDescribeApiRequest()
request.RegionId = s.client.RegionId
request.ApiId = parts[1]
request.GroupId = parts[0]
raw, err := s.client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.DescribeApi(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"NotFoundApiGroup", "NotFoundApi"}) {
return api, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return api, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
api, _ = raw.(*cloudapi.DescribeApiResponse)
if api.ApiId == "" {
return api, WrapErrorf(Error(GetNotFoundMessage("ApiGatewayApi", id)), NotFoundMsg, ProviderERROR)
}
return api, nil
}
func (s *CloudApiService) WaitForApiGatewayApi(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeApiGatewayApi(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
}
return WrapError(err)
}
respId := fmt.Sprintf("%s%s%s", object.GroupId, COLON_SEPARATED, object.ApiId)
if respId == id && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, respId, id, ProviderERROR)
}
}
}
func (s *CloudApiService) DescribeApiGatewayAppAttachment(id string) (*cloudapi.AuthorizedApp, error) {
app := &cloudapi.AuthorizedApp{}
request := cloudapi.CreateDescribeAuthorizedAppsRequest()
request.RegionId = s.client.RegionId
parts, err := ParseResourceId(id, 4)
if err != nil {
return app, WrapError(err)
}
request.GroupId = parts[0]
request.ApiId = parts[1]
request.StageName = parts[3]
appId, _ := strconv.ParseInt(parts[2], 10, 64)
var allApps []cloudapi.AuthorizedApp
for {
raw, err := s.client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.DescribeAuthorizedApps(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"NotFoundApiGroup", "NotFoundApi"}) {
return app, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return app, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cloudapi.DescribeAuthorizedAppsResponse)
allApps = append(allApps, response.AuthorizedApps.AuthorizedApp...)
if len(allApps) < PageSizeLarge {
break
}
page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return app, WrapError(err)
}
request.PageNumber = page
}
var filteredAppsTemp []cloudapi.AuthorizedApp
for _, app := range allApps {
if app.AppId == appId {
filteredAppsTemp = append(filteredAppsTemp, app)
}
}
if len(filteredAppsTemp) < 1 {
return app, WrapErrorf(Error(GetNotFoundMessage("ApigatewayAppAttachment", id)), NotFoundMsg, ProviderERROR)
}
app = &filteredAppsTemp[0]
return app, nil
}
func (s *CloudApiService) DescribeApiGatewayVpcAccess(id string) (*cloudapi.VpcAccessAttribute, error) {
vpc := &cloudapi.VpcAccessAttribute{}
request := cloudapi.CreateDescribeVpcAccessesRequest()
request.RegionId = s.client.RegionId
parts, err := ParseResourceId(id, 4)
if err != nil {
return vpc, WrapError(err)
}
var allVpcs []cloudapi.VpcAccessAttribute
for {
raw, err := s.client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.DescribeVpcAccesses(request)
})
if err != nil {
return vpc, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cloudapi.DescribeVpcAccessesResponse)
allVpcs = append(allVpcs, response.VpcAccessAttributes.VpcAccessAttribute...)
if len(allVpcs) < PageSizeLarge {
break
}
if page, err := getNextpageNumber(request.PageNumber); err != nil {
return vpc, WrapError(err)
} else {
request.PageNumber = page
}
}
var filteredVpcsTemp []cloudapi.VpcAccessAttribute
for _, vpc := range allVpcs {
iPort, _ := strconv.Atoi(parts[3])
if vpc.Port == iPort && vpc.InstanceId == parts[2] && vpc.VpcId == parts[1] && vpc.Name == parts[0] {
filteredVpcsTemp = append(filteredVpcsTemp, vpc)
}
}
if len(filteredVpcsTemp) < 1 {
return vpc, WrapErrorf(Error(GetNotFoundMessage("ApiGatewayVpcAccess", id)), NotFoundMsg, ProviderERROR)
}
return &filteredVpcsTemp[0], nil
}
func (s *CloudApiService) WaitForApiGatewayAppAttachment(id string, status Status, timeout int) (err error) {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
parts, err := ParseResourceId(id, 4)
if err != nil {
return WrapError(err)
}
appIds := parts[2]
for {
object, err := s.DescribeApiGatewayAppAttachment(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if strconv.FormatInt(object.AppId, 10) == appIds && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, strconv.FormatInt(object.AppId, 10), appIds, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *CloudApiService) DescribeDeployedApi(id string, stageName string) (*cloudapi.DescribeDeployedApiResponse, error) {
api := &cloudapi.DescribeDeployedApiResponse{}
request := cloudapi.CreateDescribeDeployedApiRequest()
request.RegionId = s.client.RegionId
parts, err := ParseResourceId(id, 2)
if err != nil {
return api, WrapError(err)
}
request.ApiId = parts[1]
request.GroupId = parts[0]
request.StageName = stageName
raw, err := s.client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.DescribeDeployedApi(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"NotFoundApiGroup", "NotFoundApi", "NotFoundStage"}) {
return api, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return api, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
api, _ = raw.(*cloudapi.DescribeDeployedApiResponse)
return api, nil
}
func (s *CloudApiService) DeployedApi(id string, stageName string) (err error) {
request := cloudapi.CreateDeployApiRequest()
request.RegionId = s.client.RegionId
parts, err := ParseResourceId(id, 2)
if err != nil {
return WrapError(err)
}
request.ApiId = parts[1]
request.GroupId = parts[0]
request.StageName = stageName
request.Description = DeployCommonDescription
raw, err := s.client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.DeployApi(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return
}
func (s *CloudApiService) AbolishApi(id string, stageName string) (err error) {
request := cloudapi.CreateAbolishApiRequest()
request.RegionId = s.client.RegionId
parts, err := ParseResourceId(id, 2)
if err != nil {
return WrapError(err)
}
request.ApiId = parts[1]
request.GroupId = parts[0]
request.StageName = stageName
raw, err := s.client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.AbolishApi(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"NotFoundApiGroup", "NotFoundApi", "NotFoundStage"}) {
return WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return
}
func (s *CloudApiService) DescribeTags(resourceId string, resourceTags map[string]interface{}, resourceType TagResourceType) (tags []cloudapi.TagResource, err error) {
request := cloudapi.CreateListTagResourcesRequest()
request.RegionId = s.client.RegionId
request.ResourceType = string(resourceType)
request.ResourceId = &[]string{resourceId}
if resourceTags != nil && len(resourceTags) > 0 {
var reqTags []cloudapi.ListTagResourcesTag
for key, value := range resourceTags {
reqTags = append(reqTags, cloudapi.ListTagResourcesTag{
Key: key,
Value: value.(string),
})
}
request.Tag = &reqTags
}
raw, err := s.client.WithCloudApiClient(func(cloudApiClient *cloudapi.Client) (interface{}, error) {
return cloudApiClient.ListTagResources(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, resourceId, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cloudapi.ListTagResourcesResponse)
return response.TagResources.TagResource, nil
}
func (s *CloudApiService) setInstanceTags(d *schema.ResourceData, resourceType TagResourceType) error {
oraw, nraw := d.GetChange("tags")
o := oraw.(map[string]interface{})
n := nraw.(map[string]interface{})
create, remove := s.diffTags(s.tagsFromMap(o), s.tagsFromMap(n))
if len(remove) > 0 {
var tagKey []string
for _, v := range remove {
tagKey = append(tagKey, v.Key)
}
request := cloudapi.CreateUntagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.ResourceType = string(resourceType)
request.TagKey = &tagKey
request.RegionId = s.client.RegionId
raw, err := s.client.WithCloudApiClient(func(client *cloudapi.Client) (interface{}, error) {
return client.UntagResources(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
if len(create) > 0 {
request := cloudapi.CreateTagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.Tag = &create
request.ResourceType = string(resourceType)
request.RegionId = s.client.RegionId
raw, err := s.client.WithCloudApiClient(func(client *cloudapi.Client) (interface{}, error) {
return client.TagResources(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
d.SetPartial("tags")
return nil
}
func (s *CloudApiService) tagsToMap(tags []cloudapi.TagResource) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !s.ignoreTag(t) {
result[t.TagKey] = t.TagValue
}
}
return result
}
func (s *CloudApiService) ignoreTag(t cloudapi.TagResource) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, t.TagKey)
ok, _ := regexp.MatchString(v, t.TagKey)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific t %s (val: %s), ignoring.\n", t.TagKey, t.TagValue)
return true
}
}
return false
}
func (s *CloudApiService) diffTags(oldTags, newTags []cloudapi.TagResourcesTag) ([]cloudapi.TagResourcesTag, []cloudapi.TagResourcesTag) {
// First, we're creating everything we have
create := make(map[string]interface{})
for _, t := range newTags {
create[t.Key] = t.Value
}
// Build the list of what to remove
var remove []cloudapi.TagResourcesTag
for _, t := range oldTags {
old, ok := create[t.Key]
if !ok || old != t.Value {
// Delete it!
remove = append(remove, t)
}
}
return s.tagsFromMap(create), remove
}
func (s *CloudApiService) tagsFromMap(m map[string]interface{}) []cloudapi.TagResourcesTag {
result := make([]cloudapi.TagResourcesTag, 0, len(m))
for k, v := range m {
result = append(result, cloudapi.TagResourcesTag{
Key: k,
Value: v.(string),
})
}
return result
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type ArmsService struct {
client *connectivity.AliyunClient
}
func (s *ArmsService) DescribeArmsAlertContact(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewArmsClient()
if err != nil {
return nil, WrapError(err)
}
action := "SearchAlertContact"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ContactIds": convertListToJsonString([]interface{}{id}),
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.PageBean.Contacts", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.PageBean.Contacts", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ARMS", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["ContactId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ARMS", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *ArmsService) DescribeArmsAlertContactGroup(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewArmsClient()
if err != nil {
return nil, WrapError(err)
}
action := "SearchAlertContactGroup"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ContactGroupIds": convertListToJsonString([]interface{}{id}),
"IsDetail": "true",
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.ContactGroups", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ContactGroups", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ARMS", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["ContactGroupId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ARMS", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *ArmsService) DescribeArmsDispatchRule(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewArmsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDispatchRule"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"Id": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"50003"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("ARMS", id)), NotFoundWithResponse, response)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.DispatchRule", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.DispatchRule", response)
}
return v.(map[string]interface{}), nil
}
func (s *ArmsService) DescribeArmsPrometheusAlertRule(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewArmsClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListPrometheusAlertRules"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ClusterId": parts[0],
}
idExist := false
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.PrometheusAlertRules", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.PrometheusAlertRules", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ARMS", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["AlertId"]) == parts[1] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("ARMS", id)), NotFoundWithResponse, response)
}
return object, nil
}
package alicloud
import (
"fmt"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
)
type Brain_industrialService struct {
client *connectivity.AliyunClient
}
func (s *Brain_industrialService) DescribeBrainIndustrialPidOrganization(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAistudioClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListPidOrganizations"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
}
idExist := false
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
addDebug(action, response, request)
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
err = Error("ListPidOrganizations failed for " + response["Message"].(string))
return object, err
}
v, err := jsonpath.Get("$.OrganizationList", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.OrganizationList", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("BrainIndustrial", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if v.(map[string]interface{})["OrganizationId"].(string) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("BrainIndustrial", id)), NotFoundWithResponse, response)
}
return object, nil
}
func (s *Brain_industrialService) DescribeBrainIndustrialPidProject(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAistudioClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListPidProjects"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"CurrentPage": 1,
"PageSize": 20,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
err = Error("ListPidProjects failed for " + response["Message"].(string))
return object, err
}
v, err := jsonpath.Get("$.PidProjectList", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.PidProjectList", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("BrainIndustrial", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if v.(map[string]interface{})["PidProjectId"].(string) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["CurrentPage"] = request["CurrentPage"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("BrainIndustrial", id)), NotFoundWithResponse, response)
}
return
}
func (s *Brain_industrialService) DescribeBrainIndustrialPidLoop(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAistudioClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetLoop"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"PidLoopId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
addDebug(action, response, request)
if IsExpectedErrorCodes(fmt.Sprintf("%v", response["Code"]), []string{"-106"}) {
err = WrapErrorf(Error(GetNotFoundMessage("BrainIndustrialPidLoop", id)), NotFoundMsg, ProviderERROR)
return object, err
}
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
err = Error("GetLoop failed for " + response["Message"].(string))
return object, err
}
v, err := jsonpath.Get("$.Data", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type BssOpenApiService struct {
client *connectivity.AliyunClient
}
func (s *BssOpenApiService) QueryAvailableInstances(id, productCode, productType, productTypeIntl string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewBssopenapiClient()
if err != nil {
return nil, WrapError(err)
}
action := "QueryAvailableInstances"
request := map[string]interface{}{
"Region": s.client.RegionId,
"InstanceIDs": id,
"ProductCode": productCode,
"ProductType": productType,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-14"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"NotApplicable"}) {
conn.Endpoint = String(connectivity.BssOpenAPIEndpointInternational)
if len(productTypeIntl) != 0 {
request["ProductType"] = productTypeIntl
}
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.Data.InstanceList", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data.InstanceList", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("Amqp", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["InstanceID"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("Amqp", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *BssOpenApiService) QueryAvailableInstance(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewBssopenapiClient()
if err != nil {
return nil, WrapError(err)
}
action := "QueryAvailableInstances"
request := map[string]interface{}{
"InstanceIDs": id,
"ProductCode": "vipcloudfw",
"ProductType": "vipcloudfw",
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-14"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"NotApplicable"}) {
conn.Endpoint = String(connectivity.BssOpenAPIEndpointInternational)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.Data.InstanceList", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data.InstanceList", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("Amqp", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["InstanceID"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudFirewall", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
package alicloud
import (
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/bssopenapi"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
const ModulesSizeLimit = 50
type BssopenapiService struct {
client *connectivity.AliyunClient
}
func (b *BssopenapiService) GetInstanceTypePrice(productCode, productType string, modules interface{}) ([]float64, error) {
var detailList []bssopenapi.ModuleDetail
switch modules := modules.(type) {
case []bssopenapi.GetPayAsYouGoPriceModuleList:
request := bssopenapi.CreateGetPayAsYouGoPriceRequest()
request.ProductCode = productCode
request.ProductType = productType
for {
if len(modules) < ModulesSizeLimit {
tmp := modules
request.ModuleList = &tmp
} else {
tmp := modules[:ModulesSizeLimit]
modules = modules[ModulesSizeLimit:]
request.ModuleList = &tmp
}
data, err := b.getPayAsYouGoData(request)
if err != nil {
return nil, WrapError(err)
}
detailList = append(detailList, data.ModuleDetails.ModuleDetail...)
if len(*request.ModuleList) < ModulesSizeLimit {
break
}
}
case []bssopenapi.GetSubscriptionPriceModuleList:
request := bssopenapi.CreateGetSubscriptionPriceRequest()
request.ProductCode = productCode
request.ProductType = productType
request.ServicePeriodQuantity = requests.NewInteger(1)
request.ServicePeriodUnit = "Month"
request.Quantity = requests.NewInteger(1)
for {
if len(modules) < ModulesSizeLimit {
tmp := modules
request.ModuleList = &tmp
} else {
tmp := modules[:ModulesSizeLimit]
modules = modules[ModulesSizeLimit:]
request.ModuleList = &tmp
}
data, err := b.getSubscriptionData(request)
if err != nil {
return nil, WrapError(err)
}
detailList = append(detailList, data.ModuleDetails.ModuleDetail...)
if len(*request.ModuleList) < ModulesSizeLimit {
break
}
}
}
var priceList []float64
for _, module := range detailList {
priceList = append(priceList, module.OriginalCost)
}
return priceList, nil
}
func (b *BssopenapiService) getSubscriptionData(request *bssopenapi.GetSubscriptionPriceRequest) (*bssopenapi.DataInGetSubscriptionPrice, error) {
request.OrderType = "NewOrder"
request.SubscriptionType = "Subscription"
request.RegionId = string(connectivity.Hangzhou)
var response *bssopenapi.GetSubscriptionPriceResponse
err := resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := b.client.WithBssopenapiClient(func(client *bssopenapi.Client) (interface{}, error) {
return client.GetSubscriptionPrice(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"NotApplicable"}) {
request.RegionId = string(connectivity.APSouthEast1)
request.Domain = connectivity.BssOpenAPIEndpointInternational
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response = raw.(*bssopenapi.GetSubscriptionPriceResponse)
return nil
})
if err != nil {
return nil, WrapError(err)
}
if !response.Success {
return nil, WrapError(Error("Api:GetSubscriptionPrice Modules:%v RequestId:%s Code:%s Message:%s",
request.ModuleList, response.RequestId, response.Code, response.Message))
}
if len(response.Data.ModuleDetails.ModuleDetail) == 0 {
return nil, WrapError(Error("Api:GetSubscriptionPrice Modules:%v RequestId:%s the moduleDetails length is 0!",
request.ModuleList, response.RequestId))
}
return &response.Data, nil
}
func (b *BssopenapiService) getPayAsYouGoData(request *bssopenapi.GetPayAsYouGoPriceRequest) (*bssopenapi.DataInGetPayAsYouGoPrice, error) {
request.SubscriptionType = "PayAsYouGo"
request.RegionId = string(connectivity.Hangzhou)
var response *bssopenapi.GetPayAsYouGoPriceResponse
err := resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := b.client.WithBssopenapiClient(func(client *bssopenapi.Client) (interface{}, error) {
return client.GetPayAsYouGoPrice(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"NotApplicable"}) {
request.RegionId = string(connectivity.APSouthEast1)
request.Domain = connectivity.BssOpenAPIEndpointInternational
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response = raw.(*bssopenapi.GetPayAsYouGoPriceResponse)
return nil
})
if err != nil {
return nil, WrapError(err)
}
if !response.Success {
return nil, WrapError(Error("Api:GetPayAsYouGoPrice Modules:%v RequestId:%s Code:%s Message:%s",
request.ModuleList, response.RequestId, response.Code, response.Message))
}
if len(response.Data.ModuleDetails.ModuleDetail) == 0 {
return nil, WrapError(Error("Api:GetPayAsYouGoPrice Modules:%v RequestId:%s the moduleDetails length is 0!",
request.ModuleList, response.RequestId))
}
return &response.Data, nil
}
package alicloud
import (
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type CasService struct {
client *connectivity.AliyunClient
}
func (s *CasService) DescribeSslCertificatesServiceCertificate(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCasClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeUserCertificateDetail"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"CertId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-07-13"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
if _, idExist := response["Id"]; !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("Cas.Sertificate", id)), NotFoundWithResponse, response)
}
return object, nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"strings"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cassandra"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type CassandraService struct {
client *connectivity.AliyunClient
}
func (s *CassandraService) DescribeCassandraCluster(id string) (object cassandra.Cluster, err error) {
cluster := cassandra.Cluster{}
request := cassandra.CreateDescribeClusterRequest()
request.RegionId = s.client.RegionId
request.ClusterId = id
raw, err := s.client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.DescribeCluster(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"Cluster.NotFound"}) {
return cluster, WrapErrorf(Error(GetNotFoundMessage("Cassandra", id)), NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return cluster, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cassandra.DescribeClusterResponse)
return response.Cluster, nil
}
func (s *CassandraService) CassandraClusterStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCassandraCluster(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.Status == failState {
return object, object.Status, WrapError(Error(FailedToReachTargetStatus, object.Status))
}
}
return object, object.Status, nil
}
}
func (s *CassandraService) DescribeCassandraDataCenter(id string) (object cassandra.DescribeDataCenterResponse, err error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := cassandra.CreateDescribeDataCenterRequest()
request.RegionId = s.client.RegionId
request.ClusterId = parts[1]
request.DataCenterId = parts[0]
raw, err := s.client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.DescribeDataCenter(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"Cluster.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("CassandraDataCenter", id)), NotFoundMsg, ProviderERROR)
return
}
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cassandra.DescribeDataCenterResponse)
return *response, nil
}
func (s *CassandraService) CassandraDataCenterStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCassandraDataCenter(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.Status == failState {
return object, object.Status, WrapError(Error(FailedToReachTargetStatus, object.Status))
}
}
return object, object.Status, nil
}
}
func (s *CassandraService) DescribeIpWhitelist(id string) (object cassandra.DescribeIpWhitelistResponse, err error) {
request := cassandra.CreateDescribeIpWhitelistRequest()
request.RegionId = s.client.RegionId
request.ClusterId = id
raw, err := s.client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.DescribeIpWhitelist(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cassandra.DescribeIpWhitelistResponse)
return *response, nil
}
func (s *CassandraService) DescribeClusterDataCenter(id string) (object cassandra.DataCenter, err error) {
request := cassandra.CreateDescribeDataCentersRequest()
request.RegionId = s.client.RegionId
request.ClusterId = id
raw, err := s.client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.DescribeDataCenters(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cassandra.DescribeDataCentersResponse)
for _, dc := range response.DataCenters.DataCenter {
if dc.CommodityInstance == id {
return dc, nil
}
}
return
}
func (s *CassandraService) DescribeSecurityGroups(id string) (object cassandra.DescribeSecurityGroupsResponse, err error) {
request := cassandra.CreateDescribeSecurityGroupsRequest()
request.RegionId = s.client.RegionId
request.ClusterId = id
raw, err := s.client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.DescribeSecurityGroups(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cassandra.DescribeSecurityGroupsResponse)
return *response, nil
}
func (s *CassandraService) DescribeCassandraEndpoints(id string) (object cassandra.DescribeContactPointsResponse, err error) {
parts := strings.Split(id, ":")
request := cassandra.CreateDescribeContactPointsRequest()
request.RegionId = s.client.RegionId
request.ClusterId = parts[len(parts)-1]
raw, err := s.client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.DescribeContactPoints(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cassandra.DescribeContactPointsResponse)
return *response, nil
}
func (s *CassandraService) setInstanceTags(d *schema.ResourceData) error {
if !d.HasChange("tags") {
return nil
}
oraw, nraw := d.GetChange("tags")
o := oraw.(map[string]interface{})
n := nraw.(map[string]interface{})
create, remove := s.diffTags(s.tagsFromMap(o), s.tagsFromMap(n))
if len(remove) > 0 {
var tagKey []string
for _, v := range remove {
tagKey = append(tagKey, v.Key)
}
request := cassandra.CreateUnTagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.TagKey = &tagKey
request.RegionId = s.client.RegionId
raw, err := s.client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.UnTagResources(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
if len(create) > 0 {
request := cassandra.CreateTagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.Tag = &create
request.RegionId = s.client.RegionId
raw, err := s.client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.TagResources(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
d.SetPartial("tags")
return nil
}
func (s *CassandraService) diffTags(oldTags, newTags []cassandra.TagResourcesTag) ([]cassandra.TagResourcesTag, []cassandra.TagResourcesTag) {
// First, we're creating everything we have
create := make(map[string]interface{})
for _, t := range newTags {
create[t.Key] = t.Value
}
// Build the list of what to remove
var remove []cassandra.TagResourcesTag
for _, t := range oldTags {
old, ok := create[t.Key]
if !ok || old != t.Value {
// Delete it!
remove = append(remove, t)
}
}
return s.tagsFromMap(create), remove
}
func (s *CassandraService) tagsFromMap(m map[string]interface{}) []cassandra.TagResourcesTag {
result := make([]cassandra.TagResourcesTag, 0, len(m))
for k, v := range m {
result = append(result, cassandra.TagResourcesTag{
Key: k,
Value: v.(string),
})
}
return result
}
func (s *CassandraService) tagsToMap(tags []cassandra.Tag) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !s.ignoreTag(t) {
result[t.Key] = t.Value
}
}
return result
}
func (s *CassandraService) ignoreTag(t cassandra.Tag) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, t.Key)
ok, _ := regexp.MatchString(v, t.Key)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific t %s (val: %s), ignoring.\n", t.Key, t.Value)
return true
}
}
return false
}
func (s *CassandraService) DescribeAccounts(id string) (object cassandra.DescribeAccountsResponse, err error) {
request := cassandra.CreateDescribeAccountsRequest()
request.RegionId = s.client.RegionId
request.ClusterId = id
raw, err := s.client.WithCassandraClient(func(cassandraClient *cassandra.Client) (interface{}, error) {
return cassandraClient.DescribeAccounts(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cassandra.DescribeAccountsResponse)
return *response, nil
}
func (s *CassandraService) DescribeCassandraBackupPlan(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCdsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeBackupPlans"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ClusterId": parts[0],
}
idExist := false
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Cluster.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Cassandra:BackupPlan", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.BackupPlans.BackupPlan", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.BackupPlans.BackupPlan", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("Cassandra", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if v.(map[string]interface{})["DataCenterId"].(string) == parts[1] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("Cassandra", id)), NotFoundWithResponse, response)
}
return object, nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cbn"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type CbnService struct {
client *connectivity.AliyunClient
}
func (s *CbnService) DescribeCenFlowlog(id string) (object cbn.FlowLog, err error) {
request := cbn.CreateDescribeFlowlogsRequest()
request.RegionId = s.client.RegionId
request.FlowLogId = id
var raw interface{}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DescribeFlowlogs(request)
})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
response, _ := raw.(*cbn.DescribeFlowlogsResponse)
if len(response.FlowLogs.FlowLog) < 1 {
err = WrapErrorf(Error(GetNotFoundMessage("CenFlowlog", id)), NotFoundMsg, ProviderERROR)
return
}
return response.FlowLogs.FlowLog[0], nil
}
func (s *CbnService) WaitForCenFlowlog(id string, expected map[string]interface{}, isDelete bool, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeCenFlowlog(id)
if err != nil {
if NotFoundError(err) {
if isDelete {
return nil
}
} else {
return WrapError(err)
}
}
ready, current, err := checkWaitForReady(object, expected)
if err != nil {
return WrapError(err)
}
if ready {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, current, expected, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *CbnService) DescribeCenInstance(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCbnClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeCens"
request := map[string]interface{}{}
filterMapList := make([]map[string]interface{}, 0)
filterMapList = append(filterMapList, map[string]interface{}{
"Key": "CenId",
"Value": []string{id},
})
request["Filter"] = filterMapList
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Cens.Cen", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Cens.Cen", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CEN", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["CenId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("CEN", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *CbnService) CenInstanceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCenInstance(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *CbnService) setResourceTags(d *schema.ResourceData, resourceType string) error {
oldItems, newItems := d.GetChange("tags")
added := make([]cbn.TagResourcesTag, 0)
for key, value := range newItems.(map[string]interface{}) {
added = append(added, cbn.TagResourcesTag{
Key: key,
Value: value.(string),
})
}
removed := make([]string, 0)
for key, _ := range oldItems.(map[string]interface{}) {
removed = append(removed, key)
}
if len(removed) > 0 {
request := cbn.CreateUntagResourcesRequest()
request.RegionId = s.client.RegionId
request.ResourceId = &[]string{d.Id()}
request.ResourceType = resourceType
request.TagKey = &removed
raw, err := s.client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.UntagResources(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
request := cbn.CreateTagResourcesRequest()
request.RegionId = s.client.RegionId
request.ResourceId = &[]string{d.Id()}
request.ResourceType = resourceType
request.Tag = &added
raw, err := s.client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.TagResources(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
return nil
}
func (s *CbnService) DescribeCenRouteMap(id string) (object cbn.RouteMap, err error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := cbn.CreateDescribeCenRouteMapsRequest()
request.RegionId = s.client.RegionId
request.CenId = parts[0]
request.RouteMapId = parts[1]
var raw interface{}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DescribeCenRouteMaps(request)
})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
response, _ := raw.(*cbn.DescribeCenRouteMapsResponse)
if len(response.RouteMaps.RouteMap) < 1 {
err = WrapErrorf(Error(GetNotFoundMessage("CenRouteMap", id)), NotFoundMsg, ProviderERROR)
return
}
return response.RouteMaps.RouteMap[0], nil
}
func (s *CbnService) CenRouteMapStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCenRouteMap(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.Status == failState {
return object, object.Status, WrapError(Error(FailedToReachTargetStatus, object.Status))
}
}
return object, object.Status, nil
}
}
func (s *CbnService) DescribeCenPrivateZone(id string) (object cbn.PrivateZoneInfo, err error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := cbn.CreateDescribeCenPrivateZoneRoutesRequest()
request.RegionId = s.client.RegionId
request.AccessRegionId = parts[1]
request.CenId = parts[0]
var raw interface{}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DescribeCenPrivateZoneRoutes(request)
})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
response, _ := raw.(*cbn.DescribeCenPrivateZoneRoutesResponse)
if len(response.PrivateZoneInfos.PrivateZoneInfo) < 1 {
err = WrapErrorf(Error(GetNotFoundMessage("CenPrivateZone", id)), NotFoundMsg, ProviderERROR)
return
}
return response.PrivateZoneInfos.PrivateZoneInfo[0], nil
}
func (s *CbnService) CenPrivateZoneStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCenPrivateZone(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.Status == failState {
return object, object.Status, WrapError(Error(FailedToReachTargetStatus, object.Status))
}
}
return object, object.Status, nil
}
}
func (s *CbnService) DescribeCenVbrHealthCheck(id string) (object cbn.VbrHealthCheck, err error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := cbn.CreateDescribeCenVbrHealthCheckRequest()
request.RegionId = s.client.RegionId
request.VbrInstanceId = parts[0]
request.VbrInstanceRegionId = parts[1]
var raw interface{}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DescribeCenVbrHealthCheck(request)
})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
response, _ := raw.(*cbn.DescribeCenVbrHealthCheckResponse)
if len(response.VbrHealthChecks.VbrHealthCheck) < 1 {
err = WrapErrorf(Error(GetNotFoundMessage("CenVbrHealthCheck", id)), NotFoundMsg, ProviderERROR, response.RequestId)
return
}
return response.VbrHealthChecks.VbrHealthCheck[0], nil
}
func (s *CbnService) DescribeCenInstanceAttachment(id string) (object cbn.DescribeCenAttachedChildInstanceAttributeResponse, err error) {
parts, err := ParseResourceId(id, 4)
if err != nil {
err = WrapError(err)
return
}
request := cbn.CreateDescribeCenAttachedChildInstanceAttributeRequest()
request.RegionId = s.client.RegionId
request.ChildInstanceId = parts[1]
request.ChildInstanceRegionId = parts[3]
request.ChildInstanceType = parts[2]
request.CenId = parts[0]
var raw interface{}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DescribeCenAttachedChildInstanceAttribute(request)
})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ParameterCenInstanceId", "ParameterError", "ParameterInstanceId"}) {
err = WrapErrorf(Error(GetNotFoundMessage("CenInstanceAttachment", id)), NotFoundMsg, ProviderERROR)
return
}
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
response, _ := raw.(*cbn.DescribeCenAttachedChildInstanceAttributeResponse)
return *response, nil
}
func (s *CbnService) CenInstanceAttachmentStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCenInstanceAttachment(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.Status == failState {
return object, object.Status, WrapError(Error(FailedToReachTargetStatus, object.Status))
}
}
return object, object.Status, nil
}
}
func (s *CbnService) DescribeCenBandwidthPackage(id string) (object cbn.CenBandwidthPackage, err error) {
request := cbn.CreateDescribeCenBandwidthPackagesRequest()
request.RegionId = s.client.RegionId
filters := make([]cbn.DescribeCenBandwidthPackagesFilter, 0)
filters = append(filters, cbn.DescribeCenBandwidthPackagesFilter{
Key: "CenBandwidthPackageId",
Value: &[]string{id},
})
request.Filter = &filters
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(11*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DescribeCenBandwidthPackages(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"AliyunGoClientFailure", "ServiceUnavailable", "Throttling", "Throttling.User"}) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"ParameterCenInstanceId"}) {
err = WrapErrorf(Error(GetNotFoundMessage("CenBandwidthPackage", id)), NotFoundMsg, ProviderERROR)
return resource.NonRetryableError(err)
}
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cbn.DescribeCenBandwidthPackagesResponse)
if len(response.CenBandwidthPackages.CenBandwidthPackage) < 1 {
err = WrapErrorf(Error(GetNotFoundMessage("CenBandwidthPackage", id)), NotFoundMsg, ProviderERROR, response.RequestId)
return resource.NonRetryableError(err)
}
object = response.CenBandwidthPackages.CenBandwidthPackage[0]
return nil
})
return object, WrapError(err)
}
func (s *CbnService) CenBandwidthPackageStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCenBandwidthPackage(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.Status == failState {
return object, object.Status, WrapError(Error(FailedToReachTargetStatus, object.Status))
}
}
return object, object.Status, nil
}
}
func (s *CbnService) SetResourceTags(d *schema.ResourceData, resourceType string) error {
if d.HasChange("tags") {
added, removed := parsingTags(d)
conn, err := s.client.NewCbnClient()
if err != nil {
return WrapError(err)
}
removedTagKeys := make([]string, 0)
for _, v := range removed {
if !ignoredTags(v, "") {
removedTagKeys = append(removedTagKeys, v)
}
}
if len(removedTagKeys) > 0 {
action := "UntagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": d.Id(),
}
for i, key := range removedTagKeys {
request[fmt.Sprintf("TagKey.%d", i+1)] = key
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
action := "TagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": d.Id(),
}
count := 1
for key, value := range added {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("tags")
}
return nil
}
func (s *CbnService) DescribeCenRouteService(id string) (object cbn.RouteServiceEntry, err error) {
parts, err := ParseResourceId(id, 4)
if err != nil {
err = WrapError(err)
return
}
request := cbn.CreateDescribeRouteServicesInCenRequest()
request.RegionId = s.client.RegionId
request.AccessRegionId = parts[3]
request.CenId = parts[0]
request.Host = parts[2]
request.HostRegionId = parts[1]
var raw interface{}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithCbnClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DescribeRouteServicesInCen(request)
})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cbn.DescribeRouteServicesInCenResponse)
if len(response.RouteServiceEntries.RouteServiceEntry) < 1 {
err = WrapErrorf(Error(GetNotFoundMessage("CenRouteService", id)), NotFoundMsg, ProviderERROR, response.RequestId)
return
}
return response.RouteServiceEntries.RouteServiceEntry[0], nil
}
func (s *CbnService) CenRouteServiceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCenRouteService(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.Status == failState {
return object, object.Status, WrapError(Error(FailedToReachTargetStatus, object.Status))
}
}
return object, object.Status, nil
}
}
func (s *CbnService) DescribeCenTransitRouter(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCbnClient()
parts, err := ParseResourceId(id, 2)
if err != nil {
return nil, WrapError(err)
}
action := "ListTransitRouters"
request := map[string]interface{}{
"Region_id": s.client.RegionId,
"CenId": parts[0],
"TransitRouterId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ParameterCenInstanceId"}) {
return nil, WrapErrorf(Error(GetNotFoundMessage("CEN Instance ID", id)), NotFoundMsg, ProviderERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.TransitRouters", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.TransitRouters", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CEN", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["TransitRouterId"].(string) != parts[1] {
return object, WrapErrorf(Error(GetNotFoundMessage("CEN", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *CbnService) CenTransitRouterStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCenTransitRouter(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *CbnService) DescribeCenTransitRouterPeerAttachment(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCbnClient()
if err != nil {
return nil, WrapError(err)
}
parts, err1 := ParseResourceId(id, 2)
if err1 != nil {
return nil, WrapError(err1)
}
action := "ListTransitRouterPeerAttachments"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"CenId": parts[0],
"TransitRouterAttachmentId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ParameterCenInstanceId", "IllegalParam.Region"}) {
return nil, WrapErrorf(Error(GetNotFoundMessage("CEN Instance ID", id)), NotFoundMsg, ProviderERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.TransitRouterAttachments", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.TransitRouterAttachments", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CEN", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["TransitRouterAttachmentId"].(string) != parts[1] {
return object, WrapErrorf(Error(GetNotFoundMessage("CEN", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *CbnService) CenTransitRouterPeerAttachmentStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCenTransitRouterPeerAttachment(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *CbnService) DescribeCenTransitRouterVbrAttachment(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCbnClient()
if err != nil {
return nil, WrapError(err)
}
parts, err1 := ParseResourceId(id, 2)
if err1 != nil {
return nil, WrapError(err1)
}
action := "ListTransitRouterVbrAttachments"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"CenId": parts[0],
"TransitRouterAttachmentId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"IllegalParam.Region"}) {
return nil, WrapErrorf(Error(GetNotFoundMessage("CEN Instance ID", id)), NotFoundMsg, ProviderERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.TransitRouterAttachments", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.TransitRouterAttachments", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CEN", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["TransitRouterAttachmentId"].(string) != parts[1] {
return object, WrapErrorf(Error(GetNotFoundMessage("CEN", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *CbnService) CenTransitRouterVbrAttachmentStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCenTransitRouterVbrAttachment(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *CbnService) DescribeCenTransitRouterVpcAttachment(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCbnClient()
if err != nil {
return nil, WrapError(err)
}
parts, err1 := ParseResourceId(id, 2)
if err1 != nil {
return nil, WrapError(err1)
}
action := "ListTransitRouterVpcAttachments"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"CenId": parts[0],
"TransitRouterAttachmentId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"IllegalParam.Region"}) {
return nil, WrapErrorf(Error(GetNotFoundMessage("CEN Instance ID", id)), NotFoundMsg, ProviderERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.TransitRouterAttachments", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.TransitRouterAttachments", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CEN", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["TransitRouterAttachmentId"].(string) != parts[1] {
return object, WrapErrorf(Error(GetNotFoundMessage("CEN", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *CbnService) CenTransitRouterVpcAttachmentStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCenTransitRouterVpcAttachment(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *CbnService) DescribeCenTransitRouterRouteEntry(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCbnClient()
if err != nil {
return nil, WrapError(err)
}
parts, err1 := ParseResourceId(id, 2)
if err1 != nil {
return nil, WrapError(err1)
}
action := "ListTransitRouterRouteEntries"
request := map[string]interface{}{
"TransitRouterRouteTableId": parts[0],
"TransitRouterRouteEntryIds": []string{parts[1]},
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidTransitRouterRouteTableId.NotFound"}) {
return nil, WrapErrorf(Error(GetNotFoundMessage("CEN TransitRouter RouteTable ID", id)), NotFoundMsg, ProviderERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.TransitRouterRouteEntries", response)
if err != nil {
if IsExpectedErrors(err, []string{"ParameterCenInstanceId"}) {
return nil, WrapErrorf(Error(GetNotFoundMessage("CEN Instance ID", id)), NotFoundMsg, ProviderERROR)
}
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.TransitRouterRouteEntries", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CEN", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["TransitRouterRouteEntryId"].(string) != parts[1] {
return object, WrapErrorf(Error(GetNotFoundMessage("CEN", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *CbnService) CenTransitRouterRouteEntryStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCenTransitRouterRouteEntry(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["TransitRouterRouteEntryStatus"]) == failState {
return object, fmt.Sprint(object["TransitRouterRouteEntryStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["TransitRouterRouteEntryStatus"])))
}
}
return object, fmt.Sprint(object["TransitRouterRouteEntryStatus"]), nil
}
}
func (s *CbnService) DescribeCenTransitRouterRouteTable(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCbnClient()
if err != nil {
return nil, WrapError(err)
}
parts, err1 := ParseResourceId(id, 2)
if err1 != nil {
return nil, WrapError(err1)
}
action := "ListTransitRouterRouteTables"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"TransitRouterId": parts[0],
"TransitRouterRouteTableIds": []string{parts[1]},
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidTransitRouterId.NotFound"}) {
return nil, WrapErrorf(Error(GetNotFoundMessage("CEN TransitRouter ID", id)), NotFoundMsg, ProviderERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.TransitRouterRouteTables", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.TransitRouterRouteTables", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CEN", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["TransitRouterRouteTableId"].(string) != parts[1] {
return object, WrapErrorf(Error(GetNotFoundMessage("CEN", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *CbnService) CenTransitRouterRouteTableStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCenTransitRouterRouteTable(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["TransitRouterRouteTableStatus"]) == failState {
return object, fmt.Sprint(object["TransitRouterRouteTableStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["TransitRouterRouteTableStatus"])))
}
}
return object, fmt.Sprint(object["TransitRouterRouteTableStatus"]), nil
}
}
func (s *CbnService) DescribeCenTransitRouterRouteTableAssociation(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCbnClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListTransitRouterRouteTableAssociations"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"TransitRouterAttachmentId": parts[0],
"TransitRouterRouteTableId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ParameterCenInstanceId"}) {
return nil, WrapErrorf(Error(GetNotFoundMessage("CEN Instance ID", id)), NotFoundMsg, ProviderERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.TransitRouterAssociations", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.TransitRouterAssociations", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CEN", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["TransitRouterAttachmentId"].(string) != parts[0] {
return object, WrapErrorf(Error(GetNotFoundMessage("CEN", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *CbnService) CenTransitRouterRouteTableAssociationStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCenTransitRouterRouteTableAssociation(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *CbnService) DescribeCenTransitRouterRouteTablePropagation(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCbnClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListTransitRouterRouteTablePropagations"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"TransitRouterAttachmentId": parts[0],
"TransitRouterRouteTableId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ParameterCenInstanceId"}) {
return nil, WrapErrorf(Error(GetNotFoundMessage("CEN Instance ID", id)), NotFoundMsg, ProviderERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.TransitRouterPropagations", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.TransitRouterPropagations", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CEN", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["TransitRouterAttachmentId"].(string) != parts[0] {
return object, WrapErrorf(Error(GetNotFoundMessage("CEN", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *CbnService) CenTransitRouterRouteTablePropagationStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCenTransitRouterRouteTablePropagation(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type CddcService struct {
client *connectivity.AliyunClient
}
func (s *CddcService) DescribeCddcDedicatedHostGroup(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCddcClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDedicatedHostGroups"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DedicatedHostGroupId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.DedicatedHostGroups.DedicatedHostGroups", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.DedicatedHostGroups.DedicatedHostGroups", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CDDC", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["DedicatedHostGroupId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("CDDC", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *CddcService) ListTagResources(id string, resourceType string) (object interface{}, err error) {
conn, err := s.client.NewCddcClient()
if err != nil {
return nil, WrapError(err)
}
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
action := "ListTagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": parts[1],
}
tags := make([]interface{}, 0)
var response map[string]interface{}
for {
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.TagResources", response)
if err != nil {
return resource.NonRetryableError(WrapErrorf(err, FailedGetAttributeMsg, id, "$.TagResources", response))
}
if v != nil {
tags = append(tags, v.([]interface{})...)
}
return nil
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
if response["NextToken"] == nil {
break
}
request["NextToken"] = response["NextToken"]
}
return tags, nil
}
func (s *CddcService) SetResourceTags(d *schema.ResourceData, resourceType string) error {
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
if d.HasChange("tags") {
added, removed := parsingTags(d)
conn, err := s.client.NewCddcClient()
if err != nil {
return WrapError(err)
}
removedTagKeys := make([]string, 0)
for _, v := range removed {
if !ignoredTags(v, "") {
removedTagKeys = append(removedTagKeys, v)
}
}
if len(removedTagKeys) > 0 {
action := "UntagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": parts[1],
}
for i, key := range removedTagKeys {
request[fmt.Sprintf("TagKey.%d", i+1)] = key
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
action := "TagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": parts[1],
}
count := 1
for key, value := range added {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("tags")
}
return nil
}
func (s *CddcService) DescribeCddcDedicatedHost(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCddcClient()
if err != nil {
return nil, WrapError(err)
}
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
action := "DescribeDedicatedHostAttribute"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DedicatedHostGroupId": parts[0],
"DedicatedHostId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDedicatedHostGroup.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("DedicatedHost", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
if fmt.Sprint(v.(map[string]interface{})["DedicatedHostId"]) != parts[1] {
return object, WrapErrorf(Error(GetNotFoundMessage("CDDC", id)), NotFoundWithResponse, response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *CddcService) CddcDedicatedHostStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCddcDedicatedHost(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["HostStatus"]) == failState {
return object, fmt.Sprint(object["HostStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["HostStatus"])))
}
}
return object, fmt.Sprint(object["HostStatus"]), nil
}
}
func (s *CddcService) DescribeCddcDedicatedHostAccount(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCddcClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDedicatedHosts"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DedicatedHostId": parts[0],
"PageSize": PageSizeMedium,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.DedicatedHosts.DedicatedHosts", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.DedicatedHosts.DedicatedHosts", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CDDC", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["AccountName"]) == parts[1] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("CDDC", id)), NotFoundWithResponse, response)
}
return
}
package alicloud
import (
"encoding/json"
"fmt"
"strings"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cdn"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
)
type CdnService struct {
client *connectivity.AliyunClient
}
func (c *CdnService) convertCdnSourcesToString(v []interface{}) (string, error) {
arrayMaps := make([]interface{}, len(v))
for i, vv := range v {
item := vv.(map[string]interface{})
arrayMaps[i] = map[string]interface{}{
"content": item["content"],
"port": item["port"],
"priority": formatInt(item["priority"]),
"type": item["type"],
"weight": formatInt(item["weight"]),
}
}
maps, err := json.Marshal(arrayMaps)
if err != nil {
return "", WrapError(err)
}
return string(maps), nil
}
func (c *CdnService) DescribeCdnDomainNew(id string) (*cdn.GetDomainDetailModel, error) {
model := &cdn.GetDomainDetailModel{}
request := cdn.CreateDescribeCdnDomainDetailRequest()
request.RegionId = c.client.RegionId
request.DomainName = id
raw, err := c.client.WithCdnClient_new(func(cdnClient *cdn.Client) (interface{}, error) {
return cdnClient.DescribeCdnDomainDetail(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDomain.NotFound", "ConfigNotFound"}) {
return model, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return model, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
domain, _ := raw.(*cdn.DescribeCdnDomainDetailResponse)
if domain.GetDomainDetailModel.DomainName != id {
return model, WrapErrorf(Error(GetNotFoundMessage("cdn_domain", id)), NotFoundMsg, ProviderERROR)
}
return &domain.GetDomainDetailModel, nil
}
func (c *CdnService) DescribeCdnDomainConfig(id string) (object interface{}, err error) {
var response map[string]interface{}
conn, err := c.client.NewCdnClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeCdnDomainConfigs"
parts := strings.Split(id, ":")
request := map[string]interface{}{
"RegionId": c.client.RegionId,
"DomainName": parts[0],
"FunctionNames": parts[1],
}
if len(parts) > 2 {
request["ConfigId"] = parts[2]
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDomain.NotFound"}) {
return object, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, request, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.DomainConfigs.DomainConfig", response)
if err != nil {
return object, WrapErrorf(Error(GetNotFoundMessage("cdn_domain_config", id)), DefaultErrorMsg, err)
}
if len(v.([]interface{})) == 0 {
return object, WrapErrorf(Error(GetNotFoundMessage("cdn_domain_config", id)), ResourceNotfound, response)
}
val := v.([]interface{})[0].(map[string]interface{})
return val, nil
}
func (c *CdnService) WaitForCdnDomain(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
time.Sleep(DefaultIntervalShort * time.Second)
for {
domain, err := c.DescribeCdnDomainNew(id)
if err != nil {
if NotFoundError(err) && status == Deleted {
break
}
return WrapError(err)
}
if domain.DomainStatus == string(status) {
break
}
time.Sleep(DefaultIntervalShort * time.Second)
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, domain.DomainStatus, status, ProviderERROR)
}
}
return nil
}
func (c *CdnService) DescribeDomainCertificateInfo(id string) (certInfo cdn.CertInfo, err error) {
request := cdn.CreateDescribeDomainCertificateInfoRequest()
request.RegionId = c.client.RegionId
request.DomainName = id
raw, err := c.client.WithCdnClient_new(func(cdnClient *cdn.Client) (interface{}, error) {
return cdnClient.DescribeDomainCertificateInfo(request)
})
if err != nil {
return certInfo, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cdn.DescribeDomainCertificateInfoResponse)
if len(response.CertInfos.CertInfo) <= 0 {
return certInfo, WrapErrorf(Error(GetNotFoundMessage("DomainCertificateInfo", id)), NotFoundMsg, ProviderERROR)
}
certInfo = response.CertInfos.CertInfo[0]
return
}
func (c *CdnService) WaitForServerCertificateNew(id string, serverCertificate string, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
certInfo, err := c.DescribeDomainCertificateInfo(id)
if err != nil {
return WrapError(err)
}
if strings.TrimSpace(certInfo.ServerCertificate) == strings.TrimSpace(serverCertificate) {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, strings.TrimSpace(certInfo.ServerCertificate), strings.TrimSpace(serverCertificate), ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (c *CdnService) DescribeTags(resourceId string, resourceType TagResourceType) (tags []cdn.TagItem, err error) {
request := cdn.CreateDescribeTagResourcesRequest()
request.RegionId = c.client.RegionId
request.ResourceType = string(resourceType)
request.ResourceId = &[]string{resourceId}
raw, err := c.client.WithCdnClient_new(func(cdnClient *cdn.Client) (interface{}, error) {
return cdnClient.DescribeTagResources(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, resourceId, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cdn.DescribeTagResourcesResponse)
if len(response.TagResources) < 1 {
return
}
for _, t := range response.TagResources {
tags = append(tags, t.Tag...)
}
return
}
func (c *CdnService) CdnDomainConfigRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
v, err := c.DescribeCdnDomainConfig(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
val := v.(map[string]interface{})
for _, failState := range failStates {
if fmt.Sprint(val["Status"]) == failState {
return val, fmt.Sprint(val["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(val["Status"])))
}
}
return val, fmt.Sprint(val["Status"]), nil
}
}
func (s *CdnService) DescribeCdnRealTimeLogDelivery(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCdnClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDomainRealtimeLogDelivery"
request := map[string]interface{}{
"Domain": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2018-05-10"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Domain.NotFound", "InternalError"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CDN:RealTimeLogDelivery", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *CdnService) CdnRealTimeLogDeliveryStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCdnRealTimeLogDelivery(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
package alicloud
import (
"fmt"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"strconv"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cbn"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
)
type CenService struct {
client *connectivity.AliyunClient
}
const DefaultCenTimeout = 60
const DefaultCenTimeoutLong = 180
const ChildInstanceTypeVpc = "VPC"
const ChildInstanceTypeVbr = "VBR"
const ChildInstanceTypeCcn = "CCN"
func (s *CenService) DescribeCenInstanceAttachment(id string) (*cbn.ChildInstance, error) {
c := &cbn.ChildInstance{}
request := cbn.CreateDescribeCenAttachedChildInstancesRequest()
request.RegionId = s.client.RegionId
cenId, instanceId, err := s.GetCenIdAndAnotherId(id)
if err != nil {
return c, WrapError(err)
}
request.CenId = cenId
for pageNum := 1; ; pageNum++ {
request.PageNumber = requests.NewInteger(pageNum)
var raw interface{}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithCenClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DescribeCenAttachedChildInstances(request)
})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ParameterInstanceId"}) {
return nil, WrapErrorf(Error(GetNotFoundMessage("CEN Instance Attachment", instanceId)), NotFoundMsg, ProviderERROR)
}
return c, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), ProviderERROR)
}
response, _ := raw.(*cbn.DescribeCenAttachedChildInstancesResponse)
instanceList := response.ChildInstances.ChildInstance
for instanceNum := 0; instanceNum <= len(instanceList)-1; instanceNum++ {
if instanceList[instanceNum].ChildInstanceId == instanceId {
return &instanceList[instanceNum], nil
}
}
if pageNum*response.PageSize >= response.TotalCount {
return c, WrapErrorf(Error(GetNotFoundMessage("CEN Instance Attachment", instanceId)), NotFoundMsg, ProviderERROR)
}
}
}
func (s *CenService) WaitForCenInstanceAttachment(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeCenInstanceAttachment(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.Status == "Attached" {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.Status, status, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *CenService) DescribeCenBandwidthPackage(id string) (c cbn.CenBandwidthPackage, err error) {
request := cbn.CreateDescribeCenBandwidthPackagesRequest()
request.RegionId = s.client.RegionId
values := []string{id}
filters := []cbn.DescribeCenBandwidthPackagesFilter{{
Key: "CenBandwidthPackageId",
Value: &values,
}}
request.Filter = &filters
var raw interface{}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(10*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithCenClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DescribeCenBandwidthPackages(request)
})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ParameterCenInstanceId"}) {
return c, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return c, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*cbn.DescribeCenBandwidthPackagesResponse)
if len(response.CenBandwidthPackages.CenBandwidthPackage) <= 0 || response.CenBandwidthPackages.CenBandwidthPackage[0].CenBandwidthPackageId != id {
return c, WrapErrorf(Error(GetNotFoundMessage("CEN Bandwidth Package", id)), NotFoundMsg, ProviderERROR)
}
c = response.CenBandwidthPackages.CenBandwidthPackage[0]
return c, nil
}
func (s *CenService) WaitForCenBandwidthPackage(id string, status Status, bandwidth, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeCenBandwidthPackage(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.Status == string(status) && strconv.FormatInt(object.Bandwidth, 10) == strconv.Itoa(bandwidth) {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.Status, status, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *CenService) DescribeCenBandwidthPackageAttachment(id string) (c cbn.CenBandwidthPackage, err error) {
object, err := s.DescribeCenBandwidthPackage(id)
if err != nil {
return c, WrapError(err)
}
if len(object.CenIds.CenId) != 1 || object.Status != string(InUse) {
return c, WrapErrorf(Error(GetNotFoundMessage("CenBandwidthPackageAttachment", id)), NotFoundMsg, ProviderERROR)
}
return object, nil
}
func (s *CenService) WaitForCenBandwidthPackageAttachment(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeCenBandwidthPackageAttachment(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.Status == string(status) {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.Status, status, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *CenService) SetCenInterRegionBandwidthLimit(cenId, localRegionId, oppositeRegionId string, bandwidthLimit int) (err error) {
request := cbn.CreateSetCenInterRegionBandwidthLimitRequest()
request.RegionId = s.client.RegionId
request.CenId = cenId
request.LocalRegionId = localRegionId
request.OppositeRegionId = oppositeRegionId
request.BandwidthLimit = requests.NewInteger(bandwidthLimit)
raw, err := s.client.WithCenClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.SetCenInterRegionBandwidthLimit(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidOperation.CenInstanceStatus"}) {
return WrapError(err)
}
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cen_bandwidth_limit", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}
func (s *CenService) DescribeCenBandwidthLimit(id string) (c cbn.CenInterRegionBandwidthLimit, err error) {
request := cbn.CreateDescribeCenInterRegionBandwidthLimitsRequest()
request.RegionId = s.client.RegionId
paras, err := s.GetCenAndRegionIds(id)
if err != nil {
return c, WrapError(err)
}
cenId := paras[0]
localRegionId := paras[1]
oppositeRegionId := paras[2]
if strings.Compare(localRegionId, oppositeRegionId) > 0 {
localRegionId, oppositeRegionId = oppositeRegionId, localRegionId
}
request.CenId = cenId
for pageNum := 1; ; pageNum++ {
request.PageNumber = requests.NewInteger(pageNum)
request.PageSize = requests.NewInteger(PageSizeLarge)
var raw interface{}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(10*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithCenClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DescribeCenInterRegionBandwidthLimits(request)
})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return c, WrapErrorf(err, DefaultErrorMsg, "alicloud_cen_bandwidth_limit", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cbn.DescribeCenInterRegionBandwidthLimitsResponse)
cenBandwidthLimitList := response.CenInterRegionBandwidthLimits.CenInterRegionBandwidthLimit
for limitNum := 0; limitNum <= len(cenBandwidthLimitList)-1; limitNum++ {
ifMatch := cenBandwidthLimitList[limitNum].LocalRegionId == localRegionId && cenBandwidthLimitList[limitNum].OppositeRegionId == oppositeRegionId
if !ifMatch {
ifMatch = cenBandwidthLimitList[limitNum].LocalRegionId == oppositeRegionId && cenBandwidthLimitList[limitNum].OppositeRegionId == localRegionId
}
if ifMatch {
return cenBandwidthLimitList[limitNum], nil
}
}
if pageNum*response.PageSize >= response.TotalCount {
return c, WrapErrorf(Error(GetNotFoundMessage("CenBandwidthLimit", id)), NotFoundMsg, ProviderERROR)
}
}
}
func (s *CenService) CenBandwidthLimitStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCenBandwidthLimit(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.Status == failState {
return object, object.Status, WrapError(Error(FailedToReachTargetStatus, object.Status))
}
}
return object, object.Status, nil
}
}
func (s *CenService) CreateCenRouteEntryParas(vtbId string) (childInstanceId string, instanceType string, err error) {
vpcService := VpcService{s.client}
//Query VRouterId and judge whether it is a vbr
vtb1, err := vpcService.QueryRouteTableById(vtbId)
if err != nil {
return childInstanceId, instanceType, WrapError(err)
}
if strings.HasPrefix(vtb1.VRouterId, "vbr") {
return vtb1.VRouterId, ChildInstanceTypeVbr, nil
}
//if the VRouterId belonged to a VPC, get the VPC ID
vtb2, err := vpcService.DescribeRouteTable(vtbId)
if err != nil {
return childInstanceId, instanceType, WrapError(err)
}
return fmt.Sprint(vtb2["VpcId"]), ChildInstanceTypeVpc, nil
}
func (s *CenService) DescribeCenRouteEntry(id string) (c cbn.PublishedRouteEntry, err error) {
parts, err := ParseResourceId(id, 3)
if err != nil {
return c, WrapError(err)
}
cenId := parts[0]
vtbId := parts[1]
cidr := parts[2]
childInstanceId, childInstanceType, err := s.CreateCenRouteEntryParas(vtbId)
if err != nil {
return c, WrapError(err)
}
request := cbn.CreateDescribePublishedRouteEntriesRequest()
request.RegionId = s.client.RegionId
request.CenId = cenId
request.ChildInstanceId = childInstanceId
request.ChildInstanceType = childInstanceType
request.ChildInstanceRegionId = s.client.RegionId
request.ChildInstanceRouteTableId = vtbId
request.DestinationCidrBlock = cidr
var raw interface{}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithCenClient(func(cbnClient *cbn.Client) (interface{}, error) {
return cbnClient.DescribePublishedRouteEntries(request)
})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ParameterIllegal", "ParameterIllegal.CenInstanceId", "Instance.NotExist"}) {
return c, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return c, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*cbn.DescribePublishedRouteEntriesResponse)
if len(response.PublishedRouteEntries.PublishedRouteEntry) <= 0 || response.PublishedRouteEntries.PublishedRouteEntry[0].PublishStatus == string(NOPUBLISHED) {
return c, WrapErrorf(Error(GetNotFoundMessage("CenRouteEntries", id)), NotFoundMsg, ProviderERROR)
}
c = response.PublishedRouteEntries.PublishedRouteEntry[0]
return c, nil
}
func (s *CenService) WaitForCenRouterEntry(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeCenRouteEntry(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.PublishStatus == string(status) {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.PublishStatus, string(status), ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *CenService) GetCenIdAndAnotherId(id string) (string, string, error) {
parts := strings.Split(id, COLON_SEPARATED)
if len(parts) != 2 {
return "", "", fmt.Errorf("invalid resource id")
}
return parts[0], parts[1], nil
}
func (s *CenService) GetCenAndRegionIds(id string) (retString []string, err error) {
parts := strings.Split(id, COLON_SEPARATED)
if len(parts) != 3 {
return retString, fmt.Errorf("invalid resource id")
}
return parts, nil
}
func (s *CenService) CenInstanceAttachmentStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCenInstanceAttachment(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.Status == failState {
return object, object.Status, WrapError(Error(FailedToReachTargetStatus, object.Status))
}
}
return object, object.Status, nil
}
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type ClickhouseService struct {
client *connectivity.AliyunClient
}
func (s *ClickhouseService) DescribeClickHouseDbCluster(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewClickhouseClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDBClusterAttribute"
request := map[string]interface{}{
"DBClusterId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.DBCluster", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.DBCluster", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *ClickhouseService) ClickHouseDbClusterStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeClickHouseDbCluster(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["DBClusterStatus"].(string) == failState {
return object, object["DBClusterStatus"].(string), WrapError(Error(FailedToReachTargetStatus, object["DBClusterStatus"].(string)))
}
}
return object, object["DBClusterStatus"].(string), nil
}
}
func (s *ClickhouseService) DescribeClickHouseAccount(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewClickhouseClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeAccounts"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"AccountName": parts[1],
"DBClusterId": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"IncorrectAccountStatus", "IncorrectDBInstanceState"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("ClickHouse", id)), NotFoundWithResponse, response)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Accounts.Account", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Accounts.Account", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ClickHouse", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["AccountName"]) != parts[1] {
return object, WrapErrorf(Error(GetNotFoundMessage("ClickHouse", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *ClickhouseService) ClickhouseStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeClickHouseAccount(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
if object != nil {
for _, failState := range failStates {
if object["AccountStatus"].(string) == failState {
return object, object["AccountStatus"].(string), WrapError(Error(FailedToReachTargetStatus, object["AccountStatus"].(string)))
}
}
return object, object["AccountStatus"].(string), nil
}
return nil, "", WrapErrorf(Error(GetNotFoundMessage("ClickHouse:Account", id)), NotFoundMsg, ProviderERROR)
}
}
func (s *ClickhouseService) DescribeDBClusterAccessWhiteList(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewClickhouseClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDBClusterAccessWhiteList"
request := map[string]interface{}{
"DBClusterId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.DBClusterAccessWhiteList.IPArray", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *ClickhouseService) DescribeClickHouseBackupPolicy(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewClickhouseClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeBackupPolicy"
request := map[string]interface{}{
"DBClusterId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("ClickHouse", id)), NotFoundWithResponse, response)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *ClickhouseService) ClickHouseBackupPolicyStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeClickHouseBackupPolicy(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Switch"]) == failState {
return object, fmt.Sprint(object["Switch"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Switch"])))
}
}
return object, fmt.Sprint(object["Switch"]), nil
}
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type CloudauthService struct {
client *connectivity.AliyunClient
}
func (s *CloudauthService) DescribeCloudauthFaceConfig(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCloudauthClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeFaceConfig"
request := map[string]interface{}{
"Lang": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-07"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Items", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Items", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("Cloudauth", id)), NotFoundWithResponse, response)
} else {
for _, obj := range v.([]interface{}) {
if fmt.Sprint(obj.(map[string]interface{})["BizType"]) == id {
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
}
return object, WrapErrorf(Error(GetNotFoundMessage("Cloudauth", id)), NotFoundWithResponse, response)
}
}
package alicloud
import (
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type CloudfwService struct {
client *connectivity.AliyunClient
}
func (s *CloudfwService) DescribeCloudFirewallControlPolicy(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCloudfwClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeControlPolicy"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"AclUuid": parts[0],
"Direction": parts[1],
"CurrentPage": 1,
"PageSize": 100,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-07"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Policys", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Policys", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudFirewall", id)), NotFoundWithResponse, response)
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type CloudphoneService struct {
client *connectivity.AliyunClient
}
func (s *CloudphoneService) DescribeEcpKeyPair(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCloudphoneClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListKeyPairs"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"KeyPairName": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-12-30"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.KeyPairs.KeyPair", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.KeyPairs.KeyPair", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ECP", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["KeyPairName"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ECP", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type CloudssoService struct {
client *connectivity.AliyunClient
}
func (s *CloudssoService) GetDirectory(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCloudssoClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetDirectory"
request := map[string]interface{}{
"DirectoryId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Directory"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudSSO:Directory", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Directory", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Directory", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *CloudssoService) GetMFAAuthenticationStatus(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCloudssoClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetMFAAuthenticationStatus"
request := map[string]interface{}{
"DirectoryId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Directory"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudSSO:Directory", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *CloudssoService) GetSCIMSynchronizationStatus(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCloudssoClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetSCIMSynchronizationStatus"
request := map[string]interface{}{
"DirectoryId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Directory"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudSSO:Directory", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *CloudssoService) GetDirectoryTasks(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCloudssoClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListTasks"
request := map[string]interface{}{
"DirectoryId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Directory"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudSSO:Directory", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Tasks", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *CloudssoService) GetExternalSAMLIdentityProvider(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCloudssoClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetExternalSAMLIdentityProvider"
request := map[string]interface{}{
"DirectoryId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Directory"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudSSO:Directory", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.SAMLIdentityProviderConfiguration", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.SAMLIdentityProviderConfiguration", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *CloudssoService) DescribeCloudSsoDirectory(id string) (object map[string]interface{}, err error) {
getDirectoryObject, err := s.GetDirectory(id)
getMFAAuthenticationStatusObject, err := s.GetMFAAuthenticationStatus(id)
if err != nil {
return nil, err
}
getSCIMSynchronizationStatusObject, err := s.GetSCIMSynchronizationStatus(id)
if err != nil {
return nil, err
}
getExternalSAMLIdentityProviderObject, err := s.GetExternalSAMLIdentityProvider(id)
if err != nil {
return nil, err
}
getDirectoryObject["MFAAuthenticationStatus"] = getMFAAuthenticationStatusObject["MFAAuthenticationStatus"]
getDirectoryObject["SCIMSynchronizationStatus"] = getSCIMSynchronizationStatusObject["SCIMSynchronizationStatus"]
getDirectoryObject["SAMLIdentityProviderConfiguration"] = getExternalSAMLIdentityProviderObject
return getDirectoryObject, nil
}
func (s *CloudssoService) DescribeCloudSsoScimServerCredential(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCloudssoClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListSCIMServerCredentials"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"DirectoryId": parts[0],
}
idExist := false
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Directory"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudSSO:SCIMServerCredential", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.SCIMServerCredentials", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.SCIMServerCredentials", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudSSO", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["CredentialId"]) == parts[1] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudSSO", id)), NotFoundWithResponse, response)
}
return object, nil
}
func (s *CloudssoService) DescribeCloudSsoGroup(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCloudssoClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetGroup"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"DirectoryId": parts[0],
"GroupId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Group"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudSSO:Group", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Group", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Group", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *CloudssoService) DescribeCloudSsoUser(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCloudssoClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetUser"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"DirectoryId": parts[0],
"UserId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.User"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudSSO:User", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.User", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.User", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *CloudssoService) ListMFADevicesForUser(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCloudssoClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListMFADevicesForUser"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"DirectoryId": parts[0],
"UserId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Directory", "EntityNotExists.User"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudSSO:User", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.MFADevices", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *CloudssoService) DescribeCloudSsoAccessConfiguration(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCloudssoClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetAccessConfiguration"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"AccessConfigurationId": parts[1],
"DirectoryId": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.AccessConfiguration"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudSSO:AccessConfiguration", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.AccessConfiguration", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.AccessConfiguration", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *CloudssoService) ListPermissionPoliciesInAccessConfiguration(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCloudssoClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListPermissionPoliciesInAccessConfiguration"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"AccessConfigurationId": parts[1],
"DirectoryId": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.AccessConfiguration"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudSSO:AccessConfiguration", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
return response, nil
}
func (s *CloudssoService) DescribeCloudSsoUserAttachment(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCloudssoClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListGroupMembers"
parts, err := ParseResourceId(id, 3)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"DirectoryId": parts[0],
"GroupId": parts[1],
"MaxResults": PageSizeLarge,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Directory", "EntityNotExists.Group"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudSSO:UserAttachment", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.GroupMembers", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.GroupMembers", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudSSO", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["UserId"]) == parts[2] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudSSO", id)), NotFoundWithResponse, response)
}
return
}
func (s *CloudssoService) DescribeCloudSsoAccessAssignment(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCloudssoClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListAccessAssignments"
parts, err := ParseResourceId(id, 6)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"DirectoryId": parts[0],
"AccessConfigurationId": parts[1],
"TargetType": parts[2],
"TargetId": parts[3],
"PrincipalType": parts[4],
"PrincipalId": parts[5],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Directory"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudSSO:AccessAttachment", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.AccessAssignments", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.AccessAssignments", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudSSO", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["PrincipalId"]) != parts[5] {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudSSO", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *CloudssoService) GetTaskStatus(directoryId, taskId string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCloudssoClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetTaskStatus"
request := map[string]interface{}{
"DirectoryId": directoryId,
"TaskId": taskId,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Task"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudSSO", fmt.Sprint(directoryId, ":", taskId))), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, fmt.Sprint(directoryId, ":", taskId), action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.TaskStatus", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, fmt.Sprint(directoryId, ":", taskId), "$.TaskStatus", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *CloudssoService) CloudssoServiceAccessAssignmentStateRefreshFunc(directoryId, taskId string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.GetTaskStatus(directoryId, taskId)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprintf(directoryId, ":", taskId)))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *CloudssoService) DescribeCloudSsoAccessConfigurationProvisioning(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCloudssoClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListAccessConfigurationProvisionings"
parts, err := ParseResourceId(id, 4)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"AccessConfigurationId": parts[1],
"DirectoryId": parts[0],
"TargetId": parts[3],
"TargetType": parts[2],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.AccessConfigurationProvisioning"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudSSO:AccessConfigurationProvisioning", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.AccessConfigurationProvisionings", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.AccessConfigurationProvisionings", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudSSO", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["TargetId"]) != parts[3] {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudSSO", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *CloudssoService) CloudssoServiceAccessConfigurationProvisioningStateRefreshFunc(directoryId, taskId string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.GetTaskStatus(directoryId, taskId)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprintf(directoryId, ":", taskId)))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *CloudssoService) CloudssoServicAccessConfigurationProvisioning(directoryId, accessConfigurationId, targetType, targetId string) (err error) {
var response map[string]interface{}
action := "ProvisionAccessConfiguration"
request := make(map[string]interface{})
conn, err := s.client.NewCloudssoClient()
if err != nil {
return WrapError(err)
}
request["DirectoryId"] = directoryId
request["AccessConfigurationId"] = accessConfigurationId
request["TargetType"] = targetType
request["TargetId"] = targetId
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"OperationConflict.Task"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_cloud_sso_access_configuration_provisioning", action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Tasks", response)
if err != nil || len(v.([]interface{})) < 1 {
return WrapErrorf(err, IdMsg, fmt.Sprint(directoryId, ":", accessConfigurationId, ":", targetType, ":", targetId))
}
response = v.([]interface{})[0].(map[string]interface{})
_, err = s.GetTaskStatus(fmt.Sprint(request["DirectoryId"]), fmt.Sprint(response["TaskId"]))
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
stateConf := BuildStateConf([]string{}, []string{"Success"}, 10*time.Minute, 5*time.Second, s.CloudssoServiceAccessConfigurationProvisioningStateRefreshFunc(fmt.Sprint(request["DirectoryId"]), fmt.Sprint(response["TaskId"]), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, fmt.Sprint(directoryId, ":", accessConfigurationId, ":", targetType, ":", targetId))
}
return nil
}
func (s *CloudssoService) DescribeCloudSsoAccessConfigurationProvisionings(directoryId, accessConfigurationId string) (objects []map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCloudssoClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListAccessConfigurationProvisionings"
request := map[string]interface{}{
"AccessConfigurationId": accessConfigurationId,
"DirectoryId": directoryId,
"MaxResults": PageSizeMedium,
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return objects, WrapErrorf(err, DataDefaultErrorMsg, "alicloud_cloud_sso_access_configuration", action, AlibabaCloudSdkGoERROR)
}
resp, err := jsonpath.Get("$.AccessConfigurationProvisionings", response)
if err != nil {
return objects, WrapErrorf(err, FailedGetAttributeMsg, action, "$.AccessConfigurationProvisionings", response)
}
result, _ := resp.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
objects = append(objects, item)
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
return objects, nil
}
package alicloud
import (
"encoding/json"
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"strconv"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cms"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type CmsService struct {
client *connectivity.AliyunClient
}
type IspCities []map[string]string
func (s *CmsService) BuildCmsCommonRequest(region string) *requests.CommonRequest {
request := requests.NewCommonRequest()
return request
}
func (s *CmsService) BuildCmsAlarmRequest(id string) *requests.CommonRequest {
request := s.BuildCmsCommonRequest(s.client.RegionId)
request.QueryParams["Id"] = id
return request
}
func (s *CmsService) DescribeAlarm(id string) (alarm cms.AlarmInDescribeMetricRuleList, err error) {
request := cms.CreateDescribeMetricRuleListRequest()
request.RuleIds = id
wait := incrementalWait(3*time.Second, 5*time.Second)
var response *cms.DescribeMetricRuleListResponse
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithCmsClient(func(cmsClient *cms.Client) (interface{}, error) {
return cmsClient.DescribeMetricRuleList(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*cms.DescribeMetricRuleListResponse)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InternalError", "ResourceNotFound"}) {
return alarm, WrapErrorf(Error(GetNotFoundMessage("Alarm Rule", id)), NotFoundWithResponse, response)
}
return alarm, err
}
if len(response.Alarms.Alarm) < 1 {
return alarm, GetNotFoundErrorFromString(GetNotFoundMessage("Alarm Rule", id))
}
return response.Alarms.Alarm[0], nil
}
func (s *CmsService) WaitForCmsAlarm(id string, enabled bool, timeout int) error {
if timeout <= 0 {
timeout = DefaultTimeout
}
for {
alarm, err := s.DescribeAlarm(id)
if err != nil {
return err
}
if alarm.EnableState == enabled {
break
}
timeout = timeout - DefaultIntervalShort
if timeout <= 0 {
return GetTimeErrorFromString(GetTimeoutMessage("Alarm", strconv.FormatBool(enabled)))
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *CmsService) BuildJsonWebhook(webhook string) string {
if webhook != "" {
return fmt.Sprintf("{\"method\":\"post\",\"url\":\"%s\"}", webhook)
}
return ""
}
func (s *CmsService) ExtractWebhookFromJson(webhookJson string) (string, error) {
byt := []byte(webhookJson)
var dat map[string]interface{}
if err := json.Unmarshal(byt, &dat); err != nil {
return "", err
}
return dat["url"].(string), nil
}
func (s *CmsService) DescribeSiteMonitor(id, keyword string) (siteMonitor cms.SiteMonitor, err error) {
listRequest := cms.CreateDescribeSiteMonitorListRequest()
listRequest.Keyword = keyword
listRequest.TaskId = id
var raw interface{}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithCmsClient(func(cmsClient *cms.Client) (interface{}, error) {
return cmsClient.DescribeSiteMonitorList(listRequest)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ExceedingQuota"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return siteMonitor, WrapError(err)
}
list := raw.(*cms.DescribeSiteMonitorListResponse)
if len(list.SiteMonitors.SiteMonitor) < 1 {
return siteMonitor, GetNotFoundErrorFromString(GetNotFoundMessage("Site Monitor", id))
}
for _, v := range list.SiteMonitors.SiteMonitor {
if v.TaskName == keyword || v.TaskId == id {
return v, nil
}
}
return siteMonitor, GetNotFoundErrorFromString(GetNotFoundMessage("Site Monitor", id))
}
func (s *CmsService) GetIspCities(id string) (ispCities IspCities, err error) {
request := cms.CreateDescribeSiteMonitorAttributeRequest()
request.TaskId = id
var raw interface{}
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithCmsClient(func(cmsClient *cms.Client) (interface{}, error) {
return cmsClient.DescribeSiteMonitorAttribute(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser, "ExceedingQuota"}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return nil, WrapError(err)
}
response := raw.(*cms.DescribeSiteMonitorAttributeResponse)
ispCity := response.SiteMonitors.IspCities.IspCity
var list []map[string]string
for _, element := range ispCity {
list = append(list, map[string]string{"city": element.City, "isp": element.Isp})
}
return list, nil
}
func (s *CmsService) DescribeCmsAlarmContact(id string) (object cms.Contact, err error) {
request := cms.CreateDescribeContactListRequest()
request.RegionId = s.client.RegionId
request.ContactName = id
raw, err := s.client.WithCmsClient(func(cmsClient *cms.Client) (interface{}, error) {
return cmsClient.DescribeContactList(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ContactNotExists", "ResourceNotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("CmsAlarmContact", id)), NotFoundMsg, ProviderERROR)
return
}
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cms.DescribeContactListResponse)
if response.Code != "200" {
err = Error("DescribeContactList failed for " + response.Message)
return
}
if len(response.Contacts.Contact) < 1 {
err = WrapErrorf(Error(GetNotFoundMessage("CmsAlarmContact", id)), NotFoundMsg, ProviderERROR, response.RequestId)
return
}
return response.Contacts.Contact[0], nil
}
func (s *CmsService) DescribeCmsAlarmContactGroup(id string) (object cms.ContactGroup, err error) {
request := cms.CreateDescribeContactGroupListRequest()
request.RegionId = s.client.RegionId
request.PageNumber = requests.NewInteger(1)
request.PageSize = requests.NewInteger(20)
for {
var raw interface{}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithCmsClient(func(cmsClient *cms.Client) (interface{}, error) {
return cmsClient.DescribeContactGroupList(request)
})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ContactGroupNotExists", "ResourceNotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("CmsAlarmContactGroup", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*cms.DescribeContactGroupListResponse)
if response.Code != "200" {
err = Error("DescribeContactGroupList failed for " + response.Message)
return object, err
}
if len(response.ContactGroupList.ContactGroup) < 1 {
err = WrapErrorf(Error(GetNotFoundMessage("CmsAlarmContactGroup", id)), NotFoundMsg, ProviderERROR, response.RequestId)
return object, err
}
for _, object := range response.ContactGroupList.ContactGroup {
if object.Name == id {
return object, nil
}
}
if len(response.ContactGroupList.ContactGroup) < PageSizeMedium {
break
}
if page, err := getNextpageNumber(request.PageNumber); err != nil {
return object, WrapError(err)
} else {
request.PageNumber = page
}
}
err = WrapErrorf(Error(GetNotFoundMessage("CmsAlarmContactGroup", id)), NotFoundMsg, ProviderERROR)
return
}
func (s *CmsService) DescribeCmsGroupMetricRule(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCmsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeMetricRuleList"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"RuleIds": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(6*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"ExceedingQuota", "Throttling.User"}) {
wait()
return resource.RetryableError(err)
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if IsExpectedErrors(err, []string{"GroupMetricRuleNotExists", "ResourceNotFound", "ResourceNotFoundError"}) {
err = WrapErrorf(Error(GetNotFoundMessage("CmsGroupMetricRule", id)), NotFoundMsg, ProviderERROR)
return object, err
}
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
err = Error("DescribeMetricRuleList failed for " + response["Message"].(string))
return object, err
}
v, err := jsonpath.Get("$.Alarms.Alarm", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Alarms.Alarm", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudMonitorService", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["RuleId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudMonitorService", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *CmsService) SetResourceTags(d *schema.ResourceData, resourceType string) error {
if d.HasChange("tags") {
added, removed := parsingTags(d)
conn, err := s.client.NewCmsClient()
if err != nil {
return WrapError(err)
}
removedTagKeys := make([]string, 0)
for _, v := range removed {
if !ignoredTags(v, "") {
removedTagKeys = append(removedTagKeys, v)
}
}
if len(removedTagKeys) > 0 {
action := "RemoveTags"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"GroupIds.1": d.Id(),
}
oraw, _ := d.GetChange("tags")
removedTags := oraw.(map[string]interface{})
count := 1
for _, key := range removedTagKeys {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = removedTags[key]
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
action := "AddTags"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"GroupIds.1": d.Id(),
}
count := 1
for key, value := range added {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("tags")
}
return nil
}
func (s *CmsService) DescribeCmsMonitorGroup(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCmsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeMonitorGroups"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"GroupId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
addDebug(action, response, request)
if IsExpectedErrorCodes(fmt.Sprintf("%v", response["Code"]), []string{"GroupsNotExists", "ResourceNotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("CmsMonitorGroup", id)), NotFoundMsg, ProviderERROR)
return object, err
}
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
err = Error("DescribeMonitorGroups failed for " + response["Message"].(string))
return object, err
}
v, err := jsonpath.Get("$.Resources.Resource", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Resources.Resource", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudMonitorService", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(formatInt(v.([]interface{})[0].(map[string]interface{})["GroupId"])) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudMonitorService", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *CmsService) DescribeCmsMonitorGroupInstances(id string) (object []map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCmsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeMonitorGroupInstances"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"GroupId": id,
}
request["PageSize"] = PageSizeMedium
request["PageNumber"] = 1
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ResourceNotFound", "ResourceNotFoundError"}) {
err = WrapErrorf(Error(GetNotFoundMessage("CmsMonitorGroupInstances", id)), NotFoundMsg, ProviderERROR)
return object, err
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.Resources.Resource", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Resources.Resource", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CmsMonitorGroupInstances", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
object = append(object, v.(map[string]interface{}))
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
return object, nil
}
func (s *CmsService) DescribeCmsMetricRuleTemplate(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCmsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeMetricRuleTemplateAttribute"
request := map[string]interface{}{
"TemplateId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ResourceNotFound"}) {
return nil, WrapErrorf(Error(GetNotFoundMessage("CloudMonitorService:MetricRuleTemplate", id)), NotFoundMsg, ProviderERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.Resource", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Resource", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *CmsService) DescribeCmsDynamicTagGroup(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewCmsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDynamicTagRuleList"
request := map[string]interface{}{
"TagRegionId": s.client.RegionId,
"PageSize": PageSizeLarge,
"PageNumber": 1,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.TagGroupList.TagGroup", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.TagGroupList.TagGroup", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudMonitorService", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["DynamicTagRuleId"]) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudMonitorService", id)), NotFoundWithResponse, response)
}
return
}
package alicloud
import (
"encoding/json"
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type ConfigService struct {
client *connectivity.AliyunClient
}
func (s *ConfigService) DescribeConfigRule(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewConfigClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetConfigRule"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ConfigRuleId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2020-09-07"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ConfigRuleNotExists", "Invalid.ConfigRuleId.Value"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Config:Rule", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.ConfigRule", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ConfigRule", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *ConfigService) DescribeConfigDeliveryChannel(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewConfigClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDeliveryChannels"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DeliveryChannelIds": id,
}
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-01-08"), StringPointer("AK"), request, nil, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"AccountNotExisted", "DeliveryChannelNotExists"}) {
err = WrapErrorf(Error(GetNotFoundMessage("ConfigDeliveryChannel", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.DeliveryChannels", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.DeliveryChannels", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("Config", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["DeliveryChannelId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("Config", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *ConfigService) DescribeConfigConfigurationRecorder(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewConfigClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeConfigurationRecorder"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
}
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-01-08"), StringPointer("AK"), request, nil, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"AccountNotExisted"}) {
err = WrapErrorf(Error(GetNotFoundMessage("ConfigConfigurationRecorder", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.ConfigurationRecorder", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ConfigurationRecorder", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *ConfigService) ConfigConfigurationRecorderStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeConfigConfigurationRecorder(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["ConfigurationRecorderStatus"].(string) == failState {
return object, object["ConfigurationRecorderStatus"].(string), WrapError(Error(FailedToReachTargetStatus, object["ConfigurationRecorderStatus"].(string)))
}
}
return object, object["ConfigurationRecorderStatus"].(string), nil
}
}
func (s *ConfigService) convertAggregatorAccountsToString(v []interface{}) (string, error) {
arrayMaps := make([]interface{}, len(v))
for i, vv := range v {
item := vv.(map[string]interface{})
arrayMaps[i] = map[string]interface{}{
"AccountId": item["account_id"],
"AccountName": item["account_name"],
"AccountType": item["account_type"],
}
}
maps, err := json.Marshal(arrayMaps)
if err != nil {
return "", WrapError(err)
}
return string(maps), nil
}
func (s *ConfigService) DescribeConfigAggregator(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewConfigClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetAggregator"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"AggregatorId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2020-09-07"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Invalid.AggregatorId.Value"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Config:Aggregator", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Aggregator", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Aggregator", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *ConfigService) ConfigAggregatorStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeConfigAggregator(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["AggregatorStatus"]) == failState {
return object, fmt.Sprint(object["AggregatorStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["AggregatorStatus"])))
}
}
return object, fmt.Sprint(object["AggregatorStatus"]), nil
}
}
func (s *ConfigService) DescribeConfigAggregateConfigRule(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewConfigClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetAggregateConfigRule"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"AggregatorId": parts[0],
"ConfigRuleId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2020-09-07"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ConfigRuleNotExists", "Invalid.AggregatorId.Value", "Invalid.ConfigRuleId.Value"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Config:AggregateConfigRule", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.ConfigRule", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ConfigRule", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *ConfigService) DescribeConfigAggregateCompliancePack(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewConfigClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetAggregateCompliancePack"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"CompliancePackId": parts[1],
"AggregatorId": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2020-09-07"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Invalid.AggregatorId.Value", "Invalid.CompliancePackId.Value"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Config:AggregateCompliancePack", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.CompliancePack", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.CompliancePack", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *ConfigService) ConfigAggregateCompliancePackStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeConfigAggregateCompliancePack(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *ConfigService) DescribeConfigCompliancePack(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewConfigClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetCompliancePack"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"CompliancePackId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2020-09-07"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Invalid.CompliancePackId.Value"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Config:CompliancePack", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.CompliancePack", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.CompliancePack", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *ConfigService) ConfigCompliancePackStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeConfigCompliancePack(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *ConfigService) ConfigAggregateConfigRuleStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeConfigAggregateConfigRule(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["ConfigRuleState"]) == failState {
return object, fmt.Sprint(object["ConfigRuleState"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["ConfigRuleState"])))
}
}
return object, fmt.Sprint(object["ConfigRuleState"]), nil
}
}
func (s *ConfigService) ConfigRuleStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeConfigRule(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["ConfigRuleState"]) == failState {
return object, fmt.Sprint(object["ConfigRuleState"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["ConfigRuleState"])))
}
}
return object, fmt.Sprint(object["ConfigRuleState"]), nil
}
}
func (s *ConfigService) StopConfigRule(id string) (err error) {
var response map[string]interface{}
conn, err := s.client.NewConfigClient()
if err != nil {
return WrapError(err)
}
action := "StopConfigRules"
request := map[string]interface{}{
"ConfigRuleIds": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-01-08"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
return nil
}
func (s *ConfigService) ActiveConfigRule(id string) (err error) {
var response map[string]interface{}
conn, err := s.client.NewConfigClient()
if err != nil {
return WrapError(err)
}
action := "ActiveConfigRules"
request := map[string]interface{}{
"ConfigRuleIds": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-01-08"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
return nil
}
func (s *ConfigService) ActiveAggregateConfigRules(id, aggregatorId string) (err error) {
var response map[string]interface{}
conn, err := s.client.NewConfigClient()
if err != nil {
return WrapError(err)
}
action := "ActiveAggregateConfigRules"
request := map[string]interface{}{
"ConfigRuleIds": id,
"AggregatorId": aggregatorId,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2020-09-07"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
return nil
}
func (s *ConfigService) DeactiveAggregateConfigRules(id, aggregatorId string) (err error) {
var response map[string]interface{}
conn, err := s.client.NewConfigClient()
if err != nil {
return WrapError(err)
}
action := "DeactiveAggregateConfigRules"
request := map[string]interface{}{
"ConfigRuleIds": id,
"AggregatorId": aggregatorId,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2020-09-07"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"encoding/json"
"fmt"
"strings"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cr"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type CrService struct {
client *connectivity.AliyunClient
}
type crCreateNamespaceRequestPayload struct {
Namespace struct {
Namespace string `json:"Namespace"`
} `json:"Namespace"`
}
type crUpdateNamespaceRequestPayload struct {
Namespace struct {
AutoCreate bool `json:"AutoCreate"`
DefaultVisibility string `json:"DefaultVisibility"`
} `json:"Namespace"`
}
type crDescribeNamespaceResponse struct {
RequestId string `json:"requestId"`
Data struct {
Namespace struct {
Namespace string `json:"namespace"`
AuthorizeType string `json:"authorizeType"`
DefaultVisibility string `json:"defaultVisibility"`
AutoCreate bool `json:"autoCreate"`
NamespaceStatus string `json:"namespaceStatus"`
} `json:"namespace"`
} `json:"data"`
}
type crDescribeNamespaceListResponse struct {
RequestId string `json:"requestId"`
Data struct {
Namespace []struct {
Namespace string `json:"namespace"`
AuthorizeType string `json:"authorizeType"`
NamespaceStatus string `json:"namespaceStatus"`
} `json:"namespaces"`
} `json:"data"`
}
const (
RepoTypePublic = "PUBLIC"
RepoTypePrivate = "PRIVATE"
)
type crCreateRepoRequestPayload struct {
Repo struct {
RepoNamespace string `json:"RepoNamespace"`
RepoName string `json:"RepoName"`
Summary string `json:"Summary"`
Detail string `json:"Detail"`
RepoType string `json:"RepoType"`
} `json:"Repo"`
}
type crUpdateRepoRequestPayload struct {
Repo struct {
Summary string `json:"Summary"`
Detail string `json:"Detail"`
RepoType string `json:"RepoType"`
} `json:"Repo"`
}
type crDescribeRepoResponse struct {
RequestId string `json:"requestId"`
Data struct {
Repo struct {
Summary string `json:"summary"`
Detail string `json:"detail"`
RepoNamespace string `json:"repoNamespace"`
RepoName string `json:"repoName"`
RepoType string `json:"repoType"`
RepoDomainList struct {
Public string `json:"public"`
Internal string `json:"internal"`
Vpc string `json:"vpc"`
}
} `json:"repo"`
} `json:"data"`
}
type crDescribeReposResponse struct {
RequestId string `json:"requestId"`
Data struct {
Repos []crRepo `json:"repos"`
Total int `json:"total"`
PageSize int `json:"pageSize"`
Page int `json:"page"`
} `json:"data"`
}
type crRepo struct {
Summary string `json:"summary"`
RepoNamespace string `json:"repoNamespace"`
RepoName string `json:"repoName"`
RepoType string `json:"repoType"`
RegionId string `json:"regionId"`
RepoDomainList struct {
Public string `json:"public"`
Internal string `json:"internal"`
Vpc string `json:"vpc"`
} `json:"repoDomainList"`
}
type crDescribeRepoTagsResponse struct {
RequestId string `json:"requestId"`
Data struct {
Tags []crTag `json:"tags"`
Total int `json:"total"`
PageSize int `json:"pageSize"`
Page int `json:"page"`
} `json:"data"`
}
type crTag struct {
ImageId string `json:"imageId"`
Digest string `json:"digest"`
Tag string `json:"tag"`
Status string `json:"status"`
ImageUpdate int `json:"imageUpdate"`
ImageCreate int `json:"imageCreate"`
ImageSize int `json:"imageSize"`
}
func (c *CrService) DescribeCrNamespace(id string) (*cr.GetNamespaceResponse, error) {
response := &cr.GetNamespaceResponse{}
request := cr.CreateGetNamespaceRequest()
request.RegionId = c.client.RegionId
request.Namespace = id
var err error
raw, err := c.client.WithCrClient(func(crClient *cr.Client) (interface{}, error) {
return crClient.GetNamespace(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"NAMESPACE_NOT_EXIST"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ = raw.(*cr.GetNamespaceResponse)
return response, nil
}
func (c *CrService) WaitForCRNamespace(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := c.DescribeCrNamespace(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
var response crDescribeNamespaceResponse
err = json.Unmarshal(object.GetHttpContentBytes(), &response)
if err != nil {
return WrapError(err)
}
if response.Data.Namespace.Namespace == id && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, response.Data.Namespace.Namespace, id, ProviderERROR)
}
}
}
func (c *CrService) DescribeCrRepo(id string) (*cr.GetRepoResponse, error) {
response := &cr.GetRepoResponse{}
sli := strings.Split(id, SLASH_SEPARATED)
repoNamespace := sli[0]
repoName := sli[1]
request := cr.CreateGetRepoRequest()
request.RegionId = c.client.RegionId
request.RepoNamespace = repoNamespace
request.RepoName = repoName
raw, err := c.client.WithCrClient(func(crClient *cr.Client) (interface{}, error) {
return crClient.GetRepo(request)
})
response, _ = raw.(*cr.GetRepoResponse)
if err != nil {
if IsExpectedErrors(err, []string{"REPO_NOT_EXIST"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
return response, nil
}
func (c *CrService) WaitForCrRepo(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := c.DescribeCrRepo(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
var response crDescribeRepoResponse
err = json.Unmarshal(object.GetHttpContentBytes(), &response)
if err != nil {
return WrapError(err)
}
respId := response.Data.Repo.RepoNamespace + SLASH_SEPARATED + response.Data.Repo.RepoName
if respId == id && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, respId, id, ProviderERROR)
}
}
}
func (c *CrService) InstanceStatusRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
resp, err := c.DescribeCrEEInstance(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if resp.InstanceStatus == failState {
return resp, resp.InstanceStatus, WrapError(Error(FailedToReachTargetStatus, resp.InstanceStatus))
}
}
return resp, resp.InstanceStatus, nil
}
}
func (s *CrService) DescribeCrEndpointAclPolicy(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAcrClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetInstanceEndpoint"
parts, err := ParseResourceId(id, 3)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"EndpointType": parts[1],
"InstanceId": parts[0],
}
idExist := false
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.AclEntries", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.AclEntries", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CR", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["Entry"]) == parts[2] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("CR", id)), NotFoundWithResponse, response)
}
return object, nil
}
func (s *CrService) DescribeCrEndpointAclService(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAcrClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetInstanceEndpoint"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"EndpointType": parts[1],
"InstanceId": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *CrService) CrEndpointAclServiceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCrEndpointAclService(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *CrService) DescribeCrChartNamespace(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAcrClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetChartNamespace"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"InstanceId": parts[0],
"NamespaceName": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if IsExpectedErrorCodes(fmt.Sprint(response["Code"]), []string{"CHART_NAMESPACE_NOT_EXIST"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CR", id)), NotFoundWithResponse, response)
}
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *CrService) DescribeCrChartRepository(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAcrClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetChartRepository"
parts, err := ParseResourceId(id, 3)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RepoName": parts[2],
"RepoNamespaceName": parts[1],
"InstanceId": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if IsExpectedErrorCodes(fmt.Sprint(response["Code"]), []string{"CHART_REPO_NOT_EXIST"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CR", id)), NotFoundWithResponse, response)
}
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"errors"
"fmt"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cr_ee"
)
func (c *CrService) ListCrEEInstances(pageNo int, pageSize int) (*cr_ee.ListInstanceResponse, error) {
response := &cr_ee.ListInstanceResponse{}
request := cr_ee.CreateListInstanceRequest()
request.RegionId = c.client.RegionId
request.PageNo = requests.NewInteger(pageNo)
request.PageSize = requests.NewInteger(pageSize)
action := request.GetActionName()
raw, err := c.client.WithCrEEClient(func(creeClient *cr_ee.Client) (interface{}, error) {
return creeClient.ListInstance(request)
})
if err != nil {
return response, WrapErrorf(err, DataDefaultErrorMsg, "ListInstance", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, raw, request.RpcRequest, request)
response, _ = raw.(*cr_ee.ListInstanceResponse)
if !response.ListInstanceIsSuccess {
return response, WrapErrorf(errors.New(response.Code), DataDefaultErrorMsg, "ListInstance", action, AlibabaCloudSdkGoERROR)
}
return response, nil
}
func (c *CrService) DescribeCrEEInstance(instanceId string) (*cr_ee.GetInstanceResponse, error) {
response := &cr_ee.GetInstanceResponse{}
request := cr_ee.CreateGetInstanceRequest()
request.RegionId = c.client.RegionId
request.InstanceId = instanceId
action := request.GetActionName()
err := resource.Retry(6*time.Second, func() *resource.RetryError {
raw, err := c.client.WithCrEEClient(func(creeClient *cr_ee.Client) (interface{}, error) {
return creeClient.GetInstance(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"INSTANCE_NOT_EXIST"}) {
time.Sleep(time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, raw, request.RpcRequest, request)
response, _ = raw.(*cr_ee.GetInstanceResponse)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"INSTANCE_NOT_EXIST"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, instanceId, action, AlibabaCloudSdkGoERROR)
}
if !response.GetInstanceIsSuccess {
if response.Code == "INSTANCE_NOT_EXIST" {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(fmt.Errorf("%v", response), NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, nil
}
func (c *CrService) GetCrEEInstanceUsage(instanceId string) (*cr_ee.GetInstanceUsageResponse, error) {
response := &cr_ee.GetInstanceUsageResponse{}
request := cr_ee.CreateGetInstanceUsageRequest()
request.RegionId = c.client.RegionId
request.InstanceId = instanceId
action := request.GetActionName()
raw, err := c.client.WithCrEEClient(func(creeClient *cr_ee.Client) (interface{}, error) {
return creeClient.GetInstanceUsage(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"INSTANCE_NOT_EXIST"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, instanceId, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, raw, request.RpcRequest, request)
response, _ = raw.(*cr_ee.GetInstanceUsageResponse)
if !response.GetInstanceUsageIsSuccess {
if response.Code == "INSTANCE_NOT_EXIST" {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(fmt.Errorf("%v", response), NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, nil
}
func (c *CrService) ListCrEEInstanceEndpoint(instanceId string) (*cr_ee.ListInstanceEndpointResponse, error) {
response := &cr_ee.ListInstanceEndpointResponse{}
request := cr_ee.CreateListInstanceEndpointRequest()
request.RegionId = c.client.RegionId
request.InstanceId = instanceId
action := request.GetActionName()
wait := incrementalWait(3*time.Second, 3*time.Second)
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := c.client.WithCrEEClient(func(creeClient *cr_ee.Client) (interface{}, error) {
return creeClient.ListInstanceEndpoint(request)
})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, raw, request.RpcRequest, request)
response, _ = raw.(*cr_ee.ListInstanceEndpointResponse)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"INSTANCE_NOT_EXIST"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, instanceId, action, AlibabaCloudSdkGoERROR)
}
if !response.ListInstanceEndpointIsSuccess {
if response.Code == "INSTANCE_NOT_EXIST" {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(fmt.Errorf("%v", response), NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, nil
}
func (c *CrService) ListCrEENamespaces(instanceId string, pageNo int, pageSize int) (*cr_ee.ListNamespaceResponse, error) {
response := &cr_ee.ListNamespaceResponse{}
request := cr_ee.CreateListNamespaceRequest()
request.RegionId = c.client.RegionId
request.InstanceId = instanceId
request.PageNo = requests.NewInteger(pageNo)
request.PageSize = requests.NewInteger(pageSize)
action := request.GetActionName()
raw, err := c.client.WithCrEEClient(func(creeClient *cr_ee.Client) (interface{}, error) {
return creeClient.ListNamespace(request)
})
if err != nil {
return response, WrapErrorf(err, DataDefaultErrorMsg, instanceId, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, raw, request.RpcRequest, request)
response, _ = raw.(*cr_ee.ListNamespaceResponse)
if !response.ListNamespaceIsSuccess {
return response, WrapErrorf(errors.New(response.Code), DataDefaultErrorMsg, instanceId, action, AlibabaCloudSdkGoERROR)
}
return response, nil
}
func (c *CrService) DescribeCrEENamespace(id string) (*cr_ee.GetNamespaceResponse, error) {
response := &cr_ee.GetNamespaceResponse{}
parts, err := ParseResourceId(id, 2)
if err != nil {
return response, WrapError(err)
}
request := cr_ee.CreateGetNamespaceRequest()
request.RegionId = c.client.RegionId
request.InstanceId = parts[0]
request.NamespaceName = parts[1]
action := request.GetActionName()
raw, err := c.client.WithCrEEClient(func(creeClient *cr_ee.Client) (interface{}, error) {
return creeClient.GetNamespace(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"NAMESPACE_NOT_EXIST"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, raw, request.RpcRequest, request)
response, _ = raw.(*cr_ee.GetNamespaceResponse)
if !response.GetNamespaceIsSuccess {
if response.Code == "NAMESPACE_NOT_EXIST" {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(fmt.Errorf("%v", response), NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, nil
}
func (c *CrService) DeleteCrEENamespace(id string) (*cr_ee.DeleteNamespaceResponse, error) {
response := &cr_ee.DeleteNamespaceResponse{}
parts, err := ParseResourceId(id, 2)
if err != nil {
return response, WrapError(err)
}
request := cr_ee.CreateDeleteNamespaceRequest()
request.RegionId = c.client.RegionId
request.InstanceId = parts[0]
request.NamespaceName = parts[1]
action := request.GetActionName()
raw, err := c.client.WithCrEEClient(func(creeClient *cr_ee.Client) (interface{}, error) {
return creeClient.DeleteNamespace(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"NAMESPACE_NOT_EXIST"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, raw, request.RpcRequest, request)
response, _ = raw.(*cr_ee.DeleteNamespaceResponse)
if !response.DeleteNamespaceIsSuccess {
if response.Code == "NAMESPACE_NOT_EXIST" {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(fmt.Errorf("%v", response), NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, nil
}
func (c *CrService) WaitForCrEENamespace(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
parts, err := ParseResourceId(id, 2)
if err != nil {
return WrapError(err)
}
for {
resp, err := c.DescribeCrEENamespace(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if resp.NamespaceName == parts[1] && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, resp.NamespaceName, parts[1], ProviderERROR)
}
time.Sleep(3 * time.Second)
}
}
func (c *CrService) ListCrEERepos(instanceId string, namespace string, pageNo int, pageSize int) (*cr_ee.ListRepositoryResponse, error) {
response := &cr_ee.ListRepositoryResponse{}
request := cr_ee.CreateListRepositoryRequest()
request.RegionId = c.client.RegionId
request.InstanceId = instanceId
request.RepoNamespaceName = namespace
request.RepoStatus = "ALL"
request.PageNo = requests.NewInteger(pageNo)
request.PageSize = requests.NewInteger(pageSize)
action := request.GetActionName()
raw, err := c.client.WithCrEEClient(func(creeClient *cr_ee.Client) (interface{}, error) {
return creeClient.ListRepository(request)
})
if err != nil {
return response, WrapErrorf(err, DataDefaultErrorMsg, fmt.Sprint(instanceId, ":", namespace), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, raw, request.RpcRequest, request)
response, _ = raw.(*cr_ee.ListRepositoryResponse)
if !response.ListRepositoryIsSuccess {
return response, WrapErrorf(errors.New(response.Code), DataDefaultErrorMsg, fmt.Sprint(instanceId, ":", namespace), action, AlibabaCloudSdkGoERROR)
}
return response, nil
}
func (c *CrService) DescribeCrEERepo(id string) (*cr_ee.GetRepositoryResponse, error) {
response := &cr_ee.GetRepositoryResponse{}
parts, err := ParseResourceId(id, 3)
if err != nil {
return response, WrapError(err)
}
request := cr_ee.CreateGetRepositoryRequest()
request.RegionId = c.client.RegionId
request.InstanceId = parts[0]
request.RepoNamespaceName = parts[1]
request.RepoName = parts[2]
action := request.GetActionName()
raw, err := c.client.WithCrEEClient(func(creeClient *cr_ee.Client) (interface{}, error) {
return creeClient.GetRepository(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"REPO_NOT_EXIST"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, raw, request.RpcRequest, request)
response, _ = raw.(*cr_ee.GetRepositoryResponse)
if !response.GetRepositoryIsSuccess {
if response.Code == "REPO_NOT_EXIST" {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(fmt.Errorf("%v", response), NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, nil
}
func (c *CrService) DeleteCrEERepo(id, repoId string) (*cr_ee.DeleteRepositoryResponse, error) {
response := &cr_ee.DeleteRepositoryResponse{}
parts, err := ParseResourceId(id, 3)
if err != nil {
return response, WrapError(err)
}
request := cr_ee.CreateDeleteRepositoryRequest()
request.RegionId = c.client.RegionId
request.InstanceId = parts[0]
request.RepoId = repoId
action := request.GetActionName()
raw, err := c.client.WithCrEEClient(func(creeClient *cr_ee.Client) (interface{}, error) {
return creeClient.DeleteRepository(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"REPO_NOT_EXIST"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, raw, request.RpcRequest, request)
response, _ = raw.(*cr_ee.DeleteRepositoryResponse)
if !response.DeleteRepositoryIsSuccess {
if response.Code == "REPO_NOT_EXIST" {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(fmt.Errorf("%v", response), NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, nil
}
func (c *CrService) WaitForCrEERepo(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
parts, err := ParseResourceId(id, 3)
if err != nil {
return WrapError(err)
}
for {
resp, err := c.DescribeCrEERepo(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if resp.RepoName == parts[2] && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, resp.RepoName, parts[2], ProviderERROR)
}
time.Sleep(3 * time.Second)
}
}
func (c *CrService) ListCrEERepoTags(instanceId string, repoId string, pageNo int, pageSize int) (*cr_ee.ListRepoTagResponse, error) {
response := &cr_ee.ListRepoTagResponse{}
request := cr_ee.CreateListRepoTagRequest()
request.RegionId = c.client.RegionId
request.InstanceId = instanceId
request.RepoId = repoId
request.PageNo = requests.NewInteger(pageNo)
request.PageSize = requests.NewInteger(pageSize)
action := request.GetActionName()
raw, err := c.client.WithCrEEClient(func(creeClient *cr_ee.Client) (interface{}, error) {
return creeClient.ListRepoTag(request)
})
if err != nil {
return response, WrapErrorf(err, DataDefaultErrorMsg, fmt.Sprint(instanceId, ":", repoId), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, raw, request.RpcRequest, request)
response, _ = raw.(*cr_ee.ListRepoTagResponse)
if !response.ListRepoTagIsSuccess {
return response, WrapErrorf(errors.New(response.Code), DataDefaultErrorMsg, fmt.Sprint(instanceId, ":", repoId), action, AlibabaCloudSdkGoERROR)
}
return response, nil
}
func (c *CrService) DescribeCrEESyncRule(id string) (*cr_ee.SyncRulesItem, error) {
parts, err := ParseResourceId(id, 3)
if err != nil {
return nil, WrapError(err)
}
instanceId := parts[0]
namespace := parts[1]
syncRuleId := parts[2]
pageNo := 1
for {
response := &cr_ee.ListRepoSyncRuleResponse{}
request := cr_ee.CreateListRepoSyncRuleRequest()
request.RegionId = c.client.RegionId
request.InstanceId = instanceId
request.NamespaceName = namespace
request.PageNo = requests.NewInteger(pageNo)
request.PageSize = requests.NewInteger(PageSizeLarge)
raw, err := c.client.WithCrEEClient(func(creeClient *cr_ee.Client) (interface{}, error) {
return creeClient.ListRepoSyncRule(request)
})
if err != nil {
return nil, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*cr_ee.ListRepoSyncRuleResponse)
if !response.ListRepoSyncRuleIsSuccess {
return nil, WrapErrorf(fmt.Errorf("%v", response), DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
for _, rule := range response.SyncRules {
if rule.SyncRuleId == syncRuleId && rule.LocalInstanceId == instanceId {
return &rule, nil
}
}
if len(response.SyncRules) < PageSizeLarge {
return nil, WrapErrorf(errors.New("sync rule not found"), NotFoundMsg, AlibabaCloudSdkGoERROR)
}
pageNo++
}
}
package alicloud
import (
"fmt"
"log"
"regexp"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/alibabacloud-go/tea/tea"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"encoding/base64"
"encoding/json"
"github.com/alibabacloud-go/cs-20151215/v2/client"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/denverdino/aliyungo/common"
"github.com/denverdino/aliyungo/cs"
)
type CsService struct {
client *connectivity.AliyunClient
}
type CsClient struct {
client *client.Client
}
type Component struct {
ComponentName string `json:"component_name"`
Version string `json:"version"`
NextVersion string `json:"next_version"`
CanUpgrade bool `json:"can_upgrade"`
Required bool `json:"required"`
Status string `json:"status"`
ErrMessage string `json:"err_message"`
}
const (
COMPONENT_AUTO_SCALER = "cluster-autoscaler"
COMPONENT_DEFAULT_VRESION = "v1.0.0"
SCALING_CONFIGURATION_NAME = "kubernetes_autoscaler_autogen"
DefaultECSTag = "k8s.aliyun.com"
DefaultClusterTag = "ack.aliyun.com"
RECYCLE_MODE_LABEL = "k8s.io/cluster-autoscaler/node-template/label/policy"
DefaultAutoscalerTag = "k8s.io/cluster-autoscaler"
SCALING_GROUP_NAME = "sg-%s-%s"
DEFAULT_COOL_DOWN_TIME = 300
RELEASE_MODE = "release"
RECYCLE_MODE = "recycle"
PRIORITY_POLICY = "PRIORITY"
COST_OPTIMIZED_POLICY = "COST_OPTIMIZED"
BALANCE_POLICY = "BALANCE"
UpgradeClusterTimeout = 30 * time.Minute
)
var (
ATTACH_SCRIPT_WITH_VERSION = `#!/bin/sh
curl http://aliacs-k8s-%s.oss-%s.aliyuncs.com/public/pkg/run/attach/%s/attach_node.sh | bash -s -- --openapi-token %s --ess true `
NETWORK_ADDON_NAMES = []string{"terway", "kube-flannel-ds", "terway-eni", "terway-eniip"}
)
func (s *CsService) GetContainerClusterByName(name string) (cluster cs.ClusterType, err error) {
name = Trim(name)
invoker := NewInvoker()
var clusters []cs.ClusterType
err = invoker.Run(func() error {
raw, e := s.client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
return csClient.DescribeClusters(name)
})
if e != nil {
return e
}
clusters, _ = raw.([]cs.ClusterType)
return nil
})
if err != nil {
return cluster, fmt.Errorf("Describe cluster failed by name %s: %#v.", name, err)
}
if len(clusters) < 1 {
return cluster, GetNotFoundErrorFromString(GetNotFoundMessage("Container Cluster", name))
}
for _, c := range clusters {
if c.Name == name {
return c, nil
}
}
return cluster, GetNotFoundErrorFromString(GetNotFoundMessage("Container Cluster", name))
}
func (s *CsService) GetContainerClusterAndCertsByName(name string) (*cs.ClusterType, *cs.ClusterCerts, error) {
cluster, err := s.GetContainerClusterByName(name)
if err != nil {
return nil, nil, err
}
var certs cs.ClusterCerts
invoker := NewInvoker()
err = invoker.Run(func() error {
raw, e := s.client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
return csClient.GetClusterCerts(cluster.ClusterID)
})
if e != nil {
return e
}
certs, _ = raw.(cs.ClusterCerts)
return nil
})
if err != nil {
return nil, nil, err
}
return &cluster, &certs, nil
}
func (s *CsService) DescribeContainerApplication(clusterName, appName string) (app cs.GetProjectResponse, err error) {
appName = Trim(appName)
cluster, certs, err := s.GetContainerClusterAndCertsByName(clusterName)
if err != nil {
return app, err
}
raw, err := s.client.WithCsProjectClient(cluster.ClusterID, cluster.MasterURL, *certs, func(csProjectClient *cs.ProjectClient) (interface{}, error) {
return csProjectClient.GetProject(appName)
})
app, _ = raw.(cs.GetProjectResponse)
if err != nil {
if IsExpectedErrors(err, []string{"Not Found"}) {
return app, GetNotFoundErrorFromString(GetNotFoundMessage("Container Application", appName))
}
return app, fmt.Errorf("Getting Application failed by name %s: %#v.", appName, err)
}
if app.Name != appName {
return app, GetNotFoundErrorFromString(GetNotFoundMessage("Container Application", appName))
}
return
}
func (s *CsService) WaitForContainerApplication(clusterName, appName string, status Status, timeout int) error {
if timeout <= 0 {
timeout = DefaultTimeout
}
for {
app, err := s.DescribeContainerApplication(clusterName, appName)
if err != nil {
return err
}
if strings.ToLower(app.CurrentState) == strings.ToLower(string(status)) {
break
}
timeout = timeout - DefaultIntervalShort
if timeout <= 0 {
return GetTimeErrorFromString(fmt.Sprintf("Waitting for container application %s is timeout and current status is %s.", string(status), app.CurrentState))
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *CsService) DescribeCsKubernetes(id string) (cluster *cs.KubernetesClusterDetail, err error) {
invoker := NewInvoker()
var requestInfo *cs.Client
var response interface{}
if err := invoker.Run(func() error {
raw, err := s.client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
return csClient.DescribeKubernetesClusterDetail(id)
})
response = raw
return err
}); err != nil {
if IsExpectedErrors(err, []string{"ErrorClusterNotFound"}) {
return cluster, WrapErrorf(err, NotFoundMsg, DenverdinoAliyungo)
}
return cluster, WrapErrorf(err, DefaultErrorMsg, id, "DescribeKubernetesCluster", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["ClusterId"] = id
addDebug("DescribeKubernetesCluster", response, requestInfo, requestMap)
}
cluster, _ = response.(*cs.KubernetesClusterDetail)
if cluster.ClusterId != id {
return cluster, WrapErrorf(Error(GetNotFoundMessage("CsKubernetes", id)), NotFoundMsg, ProviderERROR)
}
return
}
// This function returns the latest addon status information
func (s *CsClient) DescribeCsKubernetesAddonStatus(clusterId string, addonName string) (*Component, error) {
result := &Component{}
resp, err := s.client.DescribeClusterAddonsUpgradeStatus(&clusterId, &client.DescribeClusterAddonsUpgradeStatusRequest{
ComponentIds: []*string{tea.String(addonName)},
})
if err != nil {
return nil, WrapErrorf(err, DefaultErrorMsg, ResourceAlicloudCSKubernetesAddon, "DescribeClusterAddonsUpgradeStatus", err)
}
addon, ok := resp.Body[addonName]
if !ok {
return nil, WrapErrorf(Error(ResourceNotfound), DefaultErrorMsg, ResourceAlicloudCSKubernetesAddon, "DescribeClusterAddonsUpgradeStatus")
}
addonInfo := addon.(map[string]interface{})["addon_info"]
tasks := addon.(map[string]interface{})["tasks"]
result.Version = addonInfo.(map[string]interface{})["version"].(string)
result.CanUpgrade = addon.(map[string]interface{})["can_upgrade"].(bool)
result.Status = tasks.(map[string]interface{})["status"].(string)
if message, ok := tasks.(map[string]interface{})["message"]; ok {
result.ErrMessage = message.(string)
}
return result, nil
}
// This function returns the latest multiple addons status information
func (s *CsClient) DescribeCsKubernetesAllAddonsStatus(clusterId string, addons []*string) (map[string]*Component, error) {
addonsStatus := make(map[string]*Component)
resp, err := s.client.DescribeClusterAddonsUpgradeStatus(&clusterId, &client.DescribeClusterAddonsUpgradeStatusRequest{
ComponentIds: addons,
})
if err != nil {
return nil, WrapErrorf(err, DefaultErrorMsg, ResourceAlicloudCSKubernetesAddon, "DescribeClusterAddonsUpgradeStatus", err)
}
for name, status := range resp.Body {
c := &Component{}
addonInfo := status.(map[string]interface{})["addon_info"]
tasks := status.(map[string]interface{})["tasks"]
c.Version = addonInfo.(map[string]interface{})["version"].(string)
c.CanUpgrade = status.(map[string]interface{})["can_upgrade"].(bool)
c.Status = tasks.(map[string]interface{})["status"].(string)
if message, ok := tasks.(map[string]interface{})["message"]; ok {
c.ErrMessage = message.(string)
}
addonsStatus[name] = c
}
return addonsStatus, nil
}
// This function returns all available addons metadata of the cluster
func (s *CsClient) DescribeClusterAddonsMetadata(clusterId string) (map[string]*Component, error) {
result := make(map[string]*Component)
resp, err := s.client.DescribeClusterAddonsVersion(&clusterId)
if err != nil {
return nil, WrapErrorf(err, DefaultErrorMsg, ResourceAlicloudCSKubernetesAddon, "DescribeClusterAddonsVersion", err)
}
for name, addon := range resp.Body {
fields := addon.(map[string]interface{})
version := fields["version"].(string)
nextVersion := fields["next_version"].(string)
canUpgrade := fields["can_upgrade"].(bool)
required := fields["required"].(bool)
c := &Component{
ComponentName: name,
Version: version,
NextVersion: nextVersion,
CanUpgrade: canUpgrade,
Required: required,
}
result[name] = c
}
return result, nil
}
func (s *CsClient) DescribeCsKubernetesAddon(id string) (*Component, error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
return nil, WrapError(err)
}
clusterId := parts[0]
addonName := parts[1]
addonsMetadata, err := s.DescribeClusterAddonsMetadata(clusterId)
if err != nil {
return nil, err
}
addonStatus, err := s.DescribeCsKubernetesAddonStatus(clusterId, addonName)
if err != nil {
return nil, WrapErrorf(err, DefaultErrorMsg, ResourceAlicloudCSKubernetesAddon, "DescribeCsKubernetesAddonStatus", err)
}
// Update some fields
if addon, existed := addonsMetadata[addonName]; existed {
addon.Version = addonStatus.Version
addon.Status = addonStatus.Status
addon.CanUpgrade = addonStatus.CanUpgrade
addon.ErrMessage = addonStatus.ErrMessage
return addon, nil
}
return nil, WrapErrorf(Error(ResourceNotfound), DefaultErrorMsg, ResourceAlicloudCSKubernetesAddon, "DescribeCsKubernetesAddon")
}
func (s *CsClient) CsKubernetesAddonStateRefreshFunc(clusterId string, addonName string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCsKubernetesAddonStatus(clusterId, addonName)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.Status == failState {
return object, object.Status, WrapError(Error(FailedToReachTargetStatusWithResponse, object.Status, object.ErrMessage))
}
}
return object, object.Status, nil
}
}
func (s *CsClient) installAddon(d *schema.ResourceData) error {
clusterId := d.Get("cluster_id").(string)
body := make([]*client.InstallClusterAddonsRequestBody, 0)
b := &client.InstallClusterAddonsRequestBody{
Name: tea.String(d.Get("name").(string)),
Version: tea.String(d.Get("version").(string)),
}
body = append(body, b)
creationArgs := &client.InstallClusterAddonsRequest{
Body: body,
}
_, err := s.client.InstallClusterAddons(&clusterId, creationArgs)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceAlicloudCSKubernetesAddon, "installAddon", err)
}
return nil
}
func (s *CsClient) upgradeAddon(d *schema.ResourceData) error {
clusterId := d.Get("cluster_id").(string)
body := make([]*client.UpgradeClusterAddonsRequestBody, 0)
b := &client.UpgradeClusterAddonsRequestBody{
ComponentName: tea.String(d.Get("name").(string)),
NextVersion: tea.String(d.Get("version").(string)),
}
body = append(body, b)
upgradeArgs := &client.UpgradeClusterAddonsRequest{
Body: body,
}
_, err := s.client.UpgradeClusterAddons(&clusterId, upgradeArgs)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceAlicloudCSKubernetesAddon, "upgradeAddon", err)
}
return nil
}
func (s *CsClient) uninstallAddon(d *schema.ResourceData) error {
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
clusterId := parts[0]
body := make([]*client.UnInstallClusterAddonsRequestAddons, 0)
b := &client.UnInstallClusterAddonsRequestAddons{
Name: tea.String(parts[1]),
}
body = append(body, b)
uninstallArgs := &client.UnInstallClusterAddonsRequest{
Addons: body,
}
_, err = s.client.UnInstallClusterAddons(&clusterId, uninstallArgs)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ResourceAlicloudCSKubernetesAddon, "uninstallAddon", err)
}
return nil
}
// This function returns the status of all available addons of the cluster
func (s *CsClient) DescribeCsKubernetesAllAvailableAddons(clusterId string) (map[string]*Component, error) {
availableAddons, err := s.DescribeClusterAddonsMetadata(clusterId)
if err != nil {
return nil, err
}
queryList := make([]*string, 0)
for name := range availableAddons {
queryList = append(queryList, tea.String(name))
}
status, err := s.DescribeCsKubernetesAllAddonsStatus(clusterId, queryList)
if err != nil {
return nil, WrapErrorf(err, DefaultErrorMsg, ResourceAlicloudCSKubernetesAddon, "DescribeCsKubernetesExistedAddons", err)
}
for name, addon := range availableAddons {
if _, ok := status[name]; !ok {
continue
}
addon.Version = status[name].Version
addon.Status = status[name].Status
addon.CanUpgrade = status[name].CanUpgrade
addon.ErrMessage = status[name].ErrMessage
}
return availableAddons, nil
}
func (s *CsService) DescribeCsKubernetesNodePool(id string) (nodePool *cs.NodePoolDetail, err error) {
invoker := NewInvoker()
var requestInfo *cs.Client
var response interface{}
parts, err := ParseResourceId(id, 2)
if err != nil {
return nil, WrapError(err)
}
clusterId := parts[0]
nodePoolId := parts[1]
if err := invoker.Run(func() error {
raw, err := s.client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
return csClient.DescribeNodePoolDetail(clusterId, nodePoolId)
})
response = raw
return err
}); err != nil {
if e, ok := err.(*common.Error); ok {
for _, code := range []int{400} {
if e.StatusCode == code {
return nil, WrapErrorf(err, NotFoundMsg, DenverdinoAliyungo)
}
}
}
return nil, WrapErrorf(err, DefaultErrorMsg, nodePoolId, "DescribeNodePool", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["ClusterId"] = clusterId
requestMap["NodePoolId"] = nodePoolId
addDebug("DescribeNodepool", response, requestInfo, requestMap)
}
nodePool, _ = response.(*cs.NodePoolDetail)
if nodePool.NodePoolId != nodePoolId {
return nil, WrapErrorf(Error(GetNotFoundMessage("CsNodePool", nodePoolId)), NotFoundMsg, ProviderERROR)
}
return
}
func (s *CsService) WaitForCsKubernetes(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeCsKubernetes(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.ClusterId == id && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.ClusterId, id, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *CsService) DescribeCsManagedKubernetes(id string) (cluster *cs.KubernetesClusterDetail, err error) {
var requestInfo *cs.Client
invoker := NewInvoker()
var response interface{}
if err := invoker.Run(func() error {
raw, err := s.client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
return csClient.DescribeKubernetesClusterDetail(id)
})
response = raw
return err
}); err != nil {
if IsExpectedErrors(err, []string{"ErrorClusterNotFound"}) {
return cluster, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return cluster, WrapErrorf(err, DefaultErrorMsg, id, "DescribeKubernetesCluster", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["Id"] = id
addDebug("DescribeKubernetesCluster", response, requestInfo, requestMap, map[string]interface{}{"Id": id})
}
cluster, _ = response.(*cs.KubernetesClusterDetail)
if cluster.ClusterId != id {
return cluster, WrapErrorf(Error(GetNotFoundMessage("CSManagedKubernetes", id)), NotFoundMsg, ProviderERROR)
}
return
}
func (s *CsService) WaitForCSManagedKubernetes(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeCsManagedKubernetes(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.ClusterId == id && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.ClusterId, id, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *CsService) CsKubernetesInstanceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCsKubernetes(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if string(object.State) == failState {
return object, string(object.State), WrapError(Error(FailedToReachTargetStatus, string(object.State)))
}
}
return object, string(object.State), nil
}
}
func (s *CsService) CsKubernetesNodePoolStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCsKubernetesNodePool(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if string(object.State) == failState {
return object, string(object.State), WrapError(Error(FailedToReachTargetStatus, string(object.State)))
}
}
return object, string(object.State), nil
}
}
func (s *CsService) CsManagedKubernetesInstanceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCsManagedKubernetes(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if string(object.State) == failState {
return object, string(object.State), WrapError(Error(FailedToReachTargetStatus, string(object.State)))
}
}
return object, string(object.State), nil
}
}
func (s *CsService) CsServerlessKubernetesInstanceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCsServerlessKubernetes(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if string(object.State) == failState {
return object, string(object.State), WrapError(Error(FailedToReachTargetStatus, string(object.State)))
}
}
return object, string(object.State), nil
}
}
func (s *CsService) DescribeCsServerlessKubernetes(id string) (*cs.ServerlessClusterResponse, error) {
cluster := &cs.ServerlessClusterResponse{}
var requestInfo *cs.Client
invoker := NewInvoker()
var response interface{}
if err := invoker.Run(func() error {
raw, err := s.client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
requestInfo = csClient
return csClient.DescribeServerlessKubernetesCluster(id)
})
response = raw
return err
}); err != nil {
if IsExpectedErrors(err, []string{"ErrorClusterNotFound"}) {
return cluster, WrapErrorf(err, NotFoundMsg, DenverdinoAliyungo)
}
return cluster, WrapErrorf(err, DefaultErrorMsg, id, "DescribeServerlessKubernetesCluster", DenverdinoAliyungo)
}
if debugOn() {
requestMap := make(map[string]interface{})
requestMap["Id"] = id
addDebug("DescribeServerlessKubernetesCluster", response, requestInfo, requestMap, map[string]interface{}{"Id": id})
}
cluster, _ = response.(*cs.ServerlessClusterResponse)
if cluster != nil && cluster.ClusterId != id {
return cluster, WrapErrorf(Error(GetNotFoundMessage("CSServerlessKubernetes", id)), NotFoundMsg, ProviderERROR)
}
return cluster, nil
}
func (s *CsService) WaitForCSServerlessKubernetes(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeCsServerlessKubernetes(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.ClusterId == id && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.ClusterId, id, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *CsService) tagsToMap(tags []cs.Tag) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !s.ignoreTag(t) {
result[t.Key] = t.Value
}
}
return result
}
func (s *CsService) ignoreTag(t cs.Tag) bool {
filter := []string{"^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, t.Key)
ok, _ := regexp.MatchString(v, t.Key)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific t %s (val: %s), ignoring.\n", t.Key, t.Value)
return true
}
}
return false
}
func (s *CsService) GetPermanentToken(clusterId string) (string, error) {
describeClusterTokensResponse, err := s.client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
return csClient.DescribeClusterTokens(clusterId)
})
if err != nil {
return "", WrapError(fmt.Errorf("failed to get permanent token,because of %v", err))
}
tokens, ok := describeClusterTokensResponse.([]*cs.ClusterTokenResponse)
if ok != true {
return "", WrapError(fmt.Errorf("failed to parse ClusterTokenResponse of cluster %s", clusterId))
}
permanentTokens := make([]string, 0)
for _, token := range tokens {
if token.Expired == 0 && token.IsActive == 1 {
permanentTokens = append(permanentTokens, token.Token)
break
}
}
// create a new token
if len(permanentTokens) == 0 {
createClusterTokenResponse, err := s.client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
clusterTokenReqeust := &cs.ClusterTokenReqeust{}
clusterTokenReqeust.IsPermanently = true
return csClient.CreateClusterToken(clusterId, clusterTokenReqeust)
})
if err != nil {
return "", WrapError(fmt.Errorf("failed to create permanent token,because of %v", err))
}
token, ok := createClusterTokenResponse.(*cs.ClusterTokenResponse)
if ok != true {
return "", WrapError(fmt.Errorf("failed to parse token of %s", clusterId))
}
return token.Token, nil
}
return permanentTokens[0], nil
}
// GetUserData of cluster
func (s *CsService) GetUserData(clusterId string, labels string, taints string) (string, error) {
token, err := s.GetPermanentToken(clusterId)
if err != nil {
return "", err
}
if labels == "" {
labels = fmt.Sprintf("%s=true", DefaultECSTag)
} else {
labels = fmt.Sprintf("%s,%s=true", labels, DefaultECSTag)
}
cluster, err := s.DescribeCsKubernetes(clusterId)
if err != nil {
return "", WrapError(fmt.Errorf("failed to describe cs kuberentes cluster,because of %v", err))
}
extra_options := make([]string, 0)
if len(labels) > 0 || len(taints) > 0 {
if len(labels) != 0 {
extra_options = append(extra_options, fmt.Sprintf("--labels %s", labels))
}
if len(taints) != 0 {
extra_options = append(extra_options, fmt.Sprintf("--taints %s", taints))
}
}
if network, err := GetKubernetesNetworkName(cluster); err == nil && network != "" {
extra_options = append(extra_options, fmt.Sprintf("--network %s", network))
}
extra_options_in_line := strings.Join(extra_options, " ")
version := cluster.CurrentVersion
region := cluster.RegionId
return base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf(ATTACH_SCRIPT_WITH_VERSION+extra_options_in_line, region, region, version, token))), nil
}
func (s *CsService) UpgradeCluster(clusterId string, args *cs.UpgradeClusterArgs) error {
invoker := NewInvoker()
err := invoker.Run(func() error {
_, e := s.client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
return nil, csClient.UpgradeCluster(clusterId, args)
})
if e != nil {
return e
}
return nil
})
if err != nil {
return WrapError(err)
}
state, upgradeError := s.WaitForUpgradeCluster(clusterId, "Upgrade")
if state == cs.Task_Status_Success && upgradeError == nil {
return nil
}
// if upgrade failed cancel the task
err = invoker.Run(func() error {
_, e := s.client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
return nil, csClient.CancelUpgradeCluster(clusterId)
})
if e != nil {
return e
}
return nil
})
if err != nil {
return WrapError(upgradeError)
}
if state, err := s.WaitForUpgradeCluster(clusterId, "CancelUpgrade"); err != nil || state != cs.Task_Status_Success {
log.Printf("[WARN] %s ACK Cluster cancel upgrade error: %#v", clusterId, err)
}
return WrapError(upgradeError)
}
func (s *CsService) WaitForUpgradeCluster(clusterId string, action string) (string, error) {
err := resource.Retry(UpgradeClusterTimeout, func() *resource.RetryError {
resp, err := s.client.WithCsClient(func(csClient *cs.Client) (interface{}, error) {
return csClient.QueryUpgradeClusterResult(clusterId)
})
if err != nil || resp == nil {
return resource.RetryableError(err)
}
upgradeResult := resp.(*cs.UpgradeClusterResult)
if upgradeResult.UpgradeStep == cs.UpgradeStep_Success {
return nil
}
if upgradeResult.UpgradeStep == cs.UpgradeStep_Pause && upgradeResult.UpgradeStatus.Failed == "true" {
msg := ""
events := upgradeResult.UpgradeStatus.Events
if len(events) > 0 {
msg = events[len(events)-1].Message
}
return resource.NonRetryableError(fmt.Errorf("faild to %s cluster, error: %s", action, msg))
}
return resource.RetryableError(fmt.Errorf("%s cluster state not matched", action))
})
if err == nil {
log.Printf("[INFO] %s ACK Cluster %s successed", action, clusterId)
return cs.Task_Status_Success, nil
}
return cs.Task_Status_Failed, WrapError(err)
}
func GetKubernetesNetworkName(cluster *cs.KubernetesClusterDetail) (network string, err error) {
metadata := make(map[string]interface{})
if err := json.Unmarshal([]byte(cluster.MetaData), &metadata); err != nil {
return "", fmt.Errorf("unmarshal metaData failed. error: %s", err)
}
for _, name := range NETWORK_ADDON_NAMES {
if _, ok := metadata[fmt.Sprintf("%s%s", name, "Version")]; ok {
return name, nil
}
}
return "", fmt.Errorf("no network addon found")
}
func (s *CsClient) DescribeUserPermission(uid string) ([]*client.DescribeUserPermissionResponseBody, error) {
body, err := s.client.DescribeUserPermission(tea.String(uid))
if err != nil {
return nil, err
}
return body.Body, err
}
func (s *CsClient) DescribeCsAutoscalingConfig(id string) (*client.CreateAutoscalingConfigRequest, error) {
request := &client.CreateAutoscalingConfigRequest{
CoolDownDuration: tea.String("10m"),
UnneededDuration: tea.String("10m"),
UtilizationThreshold: tea.String("0.5"),
GpuUtilizationThreshold: tea.String("0.5"),
ScanInterval: tea.String("30s"),
}
return request, nil
}
// Package alicloud common functions used by datahub
package alicloud
import (
"strings"
"time"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/aliyun/aliyun-datahub-sdk-go/datahub"
)
type DatahubService struct {
client *connectivity.AliyunClient
}
func (s *DatahubService) DescribeDatahubProject(id string) (*datahub.GetProjectResult, error) {
var requestInfo *datahub.DataHub
project := &datahub.GetProjectResult{}
raw, err := s.client.WithDataHubClient(func(dataHubClient datahub.DataHubApi) (interface{}, error) {
requestInfo = dataHubClient.(*datahub.DataHub)
return dataHubClient.GetProject(id)
})
if err != nil {
if isDatahubNotExistError(err) {
return project, WrapErrorf(err, NotFoundMsg, AliyunDatahubSdkGo)
}
return project, WrapErrorf(err, DefaultErrorMsg, id, "GetProject", AliyunDatahubSdkGo)
}
if debugOn() {
requestMap := make(map[string]string)
requestMap["ProjectName"] = id
addDebug("GetProject", raw, requestInfo, requestMap)
}
project, _ = raw.(*datahub.GetProjectResult)
if project == nil {
return project, WrapErrorf(Error(GetNotFoundMessage("DatahubProject", id)), NotFoundMsg, ProviderERROR)
}
return project, nil
}
func (s *DatahubService) WaitForDatahubProject(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeDatahubProject(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if time.Now().After(deadline) {
objstringfy, err := convertArrayObjectToJsonString(object)
if err != nil {
return WrapError(err)
}
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, objstringfy, id, ProviderERROR)
}
}
}
func (s *DatahubService) DescribeDatahubSubscription(id string) (*datahub.GetSubscriptionResult, error) {
subscription := &datahub.GetSubscriptionResult{}
parts, err := ParseResourceId(id, 3)
if err != nil {
return subscription, WrapError(err)
}
projectName, topicName, subId := parts[0], parts[1], parts[2]
var requestInfo *datahub.DataHub
raw, err := s.client.WithDataHubClient(func(dataHubClient datahub.DataHubApi) (interface{}, error) {
requestInfo = dataHubClient.(*datahub.DataHub)
return dataHubClient.GetSubscription(projectName, topicName, subId)
})
if err != nil {
if isDatahubNotExistError(err) {
return subscription, WrapErrorf(err, NotFoundMsg, AliyunDatahubSdkGo)
}
return subscription, WrapErrorf(err, DefaultErrorMsg, id, "GetSubscription", AliyunDatahubSdkGo)
}
if debugOn() {
requestMap := make(map[string]string)
requestMap["ProjectName"] = projectName
requestMap["TopicName"] = topicName
requestMap["SubId"] = subId
addDebug("GetProject", raw, requestInfo, requestMap)
}
subscription, _ = raw.(*datahub.GetSubscriptionResult)
if subscription == nil || subscription.TopicName != topicName || subscription.SubId != subId {
return subscription, WrapErrorf(Error(GetNotFoundMessage("DatahubSubscription", id)), NotFoundMsg, ProviderERROR)
}
return subscription, nil
}
func (s *DatahubService) WaitForDatahubSubscription(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
parts, err := ParseResourceId(id, 3)
if err != nil {
return WrapError(err)
}
topicName, subId := parts[1], parts[2]
for {
object, err := s.DescribeDatahubSubscription(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.TopicName == topicName && object.SubId == subId && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.TopicName+":"+object.SubId, parts[1]+":"+parts[2], ProviderERROR)
}
}
}
func (s *DatahubService) DescribeDatahubTopic(id string) (*datahub.GetTopicResult, error) {
topic := &datahub.GetTopicResult{}
parts, err := ParseResourceId(id, 2)
if err != nil {
return topic, WrapError(err)
}
projectName, topicName := parts[0], parts[1]
var requestInfo *datahub.DataHub
raw, err := s.client.WithDataHubClient(func(dataHubClient datahub.DataHubApi) (interface{}, error) {
requestInfo = dataHubClient.(*datahub.DataHub)
return dataHubClient.GetTopic(projectName, topicName)
})
if err != nil {
if isDatahubNotExistError(err) {
return topic, WrapErrorf(err, NotFoundMsg, AliyunDatahubSdkGo)
}
return topic, WrapErrorf(err, DefaultErrorMsg, id, "GetTopic", AliyunDatahubSdkGo)
}
if debugOn() {
requestMap := make(map[string]string)
requestMap["ProjectName"] = projectName
requestMap["TopicName"] = topicName
addDebug("GetTopic", raw, requestInfo, requestMap)
}
topic, _ = raw.(*datahub.GetTopicResult)
if topic == nil {
return topic, WrapErrorf(Error(GetNotFoundMessage("DatahubTopic", id)), NotFoundMsg, ProviderERROR)
}
return topic, nil
}
func (s *DatahubService) WaitForDatahubTopic(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
parts, err := ParseResourceId(id, 2)
if err != nil {
return WrapError(err)
}
projectName, topicName := parts[0], parts[1]
for {
object, err := s.DescribeDatahubTopic(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.ProjectName == projectName && object.TopicName == topicName && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.ProjectName+":"+object.TopicName, id, ProviderERROR)
}
}
}
func convUint64ToDate(t uint64) string {
return time.Unix(int64(t), 0).Format("2006-01-02 15:04:05")
}
func getNow() string {
return time.Now().Format("2006-01-02 15:04:05")
}
func getRecordSchema(typeMap map[string]interface{}) (recordSchema *datahub.RecordSchema) {
recordSchema = datahub.NewRecordSchema()
for k, v := range typeMap {
recordSchema.AddField(datahub.Field{Name: string(k), Type: datahub.FieldType(v.(string))})
}
return recordSchema
}
func isRetryableDatahubError(err error) bool {
if e, ok := err.(*datahub.DatahubClientError); ok && e.StatusCode >= 500 {
return true
}
return false
}
// It is proactive defense to the case that SDK extends new datahub objects.
const (
DoesNotExist = "does not exist"
)
func isDatahubNotExistError(err error) bool {
return IsExpectedErrors(err, []string{datahub.NoSuchProject, datahub.NoSuchTopic, datahub.NoSuchShard, datahub.NoSuchSubscription, DoesNotExist})
}
func isTerraformTestingDatahubObject(name string) bool {
prefixes := []string{
"tf_testAcc",
"tf_test_",
"testAcc",
}
for _, prefix := range prefixes {
if strings.HasPrefix(strings.ToLower(name), strings.ToLower(prefix)) {
return true
}
}
return false
}
func getDefaultRecordSchemainMap() map[string]interface{} {
return map[string]interface{}{
"string_field": "STRING",
}
}
func recordSchemaToMap(fields []datahub.Field) map[string]string {
result := make(map[string]string)
for _, f := range fields {
result[f.Name] = f.Type.String()
}
return result
}
package alicloud
import (
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type DataworksPublicService struct {
client *connectivity.AliyunClient
}
func (s *DataworksPublicService) DescribeDataWorksFolder(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDataworkspublicClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetFolder"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"FolderId": parts[0],
"ProjectId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-05-18"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Data", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data", response)
}
object = v.(map[string]interface{})
if len(object) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("dataworks", id)), NotFoundWithResponse, response)
}
return object, nil
}
func (s *DataworksPublicService) GetFolder(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDataworkspublicClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetFolder"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"FolderId": parts[0],
"ProjectId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-05-18"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Data", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type DbfsService struct {
client *connectivity.AliyunClient
}
func (s *DbfsService) DescribeDbfsInstance(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDbfsClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListDbfs"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"PageNumber": 1,
"PageSize": PageSizeLarge,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-18"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.DBFSInfo", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.DBFSInfo", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("DBFS", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["FsId"]) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("DBFS", id)), NotFoundWithResponse, response)
}
return
}
func (s *DbfsService) DbfsInstanceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeDbfsInstance(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
package alicloud
import (
"encoding/json"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type DcdnService struct {
client *connectivity.AliyunClient
}
func (s *DcdnService) convertSourcesToString(v []interface{}) (string, error) {
arrayMaps := make([]interface{}, len(v))
for i, vv := range v {
item := vv.(map[string]interface{})
arrayMaps[i] = map[string]interface{}{
"Content": item["content"],
"Port": item["port"],
"Priority": item["priority"],
"Type": item["type"],
"Weight": item["weight"],
}
}
maps, err := json.Marshal(arrayMaps)
if err != nil {
return "", WrapError(err)
}
return string(maps), nil
}
func (s *DcdnService) DescribeDcdnDomainCertificateInfo(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDcdnClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDcdnDomainCertificateInfo"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DomainName": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.CertInfos.CertInfo", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.CertInfos.CertInfo", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("DCDN", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["DomainName"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("DCDN", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *DcdnService) DescribeDcdnDomain(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDcdnClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDcdnDomainDetail"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DomainName": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDomain.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("DcdnDomain", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.DomainDetail", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.DomainDetail", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *DcdnService) DcdnDomainStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeDcdnDomain(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["DomainStatus"].(string) == failState {
return object, object["DomainStatus"].(string), WrapError(Error(FailedToReachTargetStatus, object["DomainStatus"].(string)))
}
}
return object, object["DomainStatus"].(string), nil
}
}
func (s *DcdnService) DescribeDcdnDomainConfig(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDcdnClient()
if err != nil {
return nil, WrapError(err)
}
parts, err := ParseResourceId(id, 3)
if err != nil {
err = WrapError(err)
return
}
action := "DescribeDcdnDomainConfigs"
request := map[string]interface{}{
"DomainName": parts[0],
"FunctionNames": parts[1],
}
if parts[2] != "" {
request["ConfigId"] = parts[2]
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDomain.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("DcdnDomainConfig", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.DomainConfigs.DomainConfig", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.DomainConfigs.DomainConfig", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("DCDN:DomainConfig", id)), NotFoundWithResponse, response)
} else if len(v.([]interface{})) > 0 {
object = v.([]interface{})[0].(map[string]interface{})
}
return object, nil
}
func (s *DcdnService) DcdnDomainConfigStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeDcdnDomainConfig(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["Status"].(string) == failState {
return object, object["Status"].(string), WrapError(Error(FailedToReachTargetStatus, object["Status"].(string)))
}
}
return object, object["Status"].(string), nil
}
}
package alicloud
import (
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ddosbgp"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
)
type DdosbgpService struct {
client *connectivity.AliyunClient
}
func (s *DdosbgpService) DescribeDdosbgpInstance(id string) (v ddosbgp.Instance, err error) {
request := ddosbgp.CreateDescribeInstanceListRequest()
request.RegionId = s.client.RegionId
request.DdosRegionId = s.client.RegionId
request.InstanceIdList = "[\"" + id + "\"]"
request.PageNo = "1"
request.PageSize = "10"
raw, err := s.client.WithDdosbgpClient(func(ddosbgpClient *ddosbgp.Client) (interface{}, error) {
return ddosbgpClient.DescribeInstanceList(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InstanceNotFound"}) {
return v, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return v, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ddosbgp.DescribeInstanceListResponse)
if len(response.InstanceList) == 0 || response.InstanceList[0].InstanceId != id {
return v, WrapErrorf(Error(GetNotFoundMessage("Ddosbgp Instance", id)), NotFoundMsg, ProviderERROR)
}
v = response.InstanceList[0]
return
}
func (s *DdosbgpService) DescribeDdosbgpInstanceSpec(id string, region string) (v ddosbgp.InstanceSpec, err error) {
request := ddosbgp.CreateDescribeInstanceSpecsRequest()
request.InstanceIdList = "[\"" + id + "\"]"
request.DdosRegionId = region
request.RegionId = region
raw, err := s.client.WithDdosbgpClient(func(ddosbgpClient *ddosbgp.Client) (interface{}, error) {
return ddosbgpClient.DescribeInstanceSpecs(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InstanceNotFound", "InvalidInstance"}) {
return v, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return v, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
resp, _ := raw.(*ddosbgp.DescribeInstanceSpecsResponse)
if len(resp.InstanceSpecs) == 0 || resp.InstanceSpecs[0].InstanceId != id {
return v, WrapErrorf(Error(GetNotFoundMessage("DdosbgpInstanceSpec", id)), NotFoundMsg, ProviderERROR)
}
v = resp.InstanceSpecs[0]
return v, WrapError(err)
}
func (s *DdosbgpService) WaitForDdosbgpInstance(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeDdosbgpInstance(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
} else if strings.ToLower(object.Status) == strings.ToLower(string(status)) {
//TODO
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.Status, status, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
package alicloud
import (
"encoding/json"
"strconv"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/bssopenapi"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ddoscoo"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type DdoscooService struct {
client *connectivity.AliyunClient
}
func (s *DdoscooService) DescribeDdoscooInstance(id string) (v ddoscoo.Instance, err error) {
request := ddoscoo.CreateDescribeInstancesRequest()
request.RegionId = "cn-hangzhou"
request.InstanceIds = &[]string{id}
request.PageNumber = "1"
request.PageSize = "10"
raw, err := s.client.WithDdoscooClient(func(ddoscooClient *ddoscoo.Client) (interface{}, error) {
return ddoscooClient.DescribeInstances(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InstanceNotFound"}) {
return v, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return v, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ddoscoo.DescribeInstancesResponse)
if len(response.Instances) == 0 || response.Instances[0].InstanceId != id {
return v, WrapErrorf(Error(GetNotFoundMessage("Ddoscoo Instance", id)), NotFoundMsg, ProviderERROR)
}
v = response.Instances[0]
return
}
// 创建实例后轮询查询直到创建成功
func (s *DdoscooService) DdosStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeDdoscooInstance(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
status := ""
if object.Status == 1 {
status = string(Available)
} else {
status = string(Unavailable)
}
return object, status, nil
}
}
func (s *DdoscooService) DescribeDdoscooInstanceSpec(d *schema.ResourceData) (v ddoscoo.InstanceSpec, err error) {
request := ddoscoo.CreateDescribeInstanceSpecsRequest()
request.RegionId = "cn-hangzhou"
id := d.Id()
request.InstanceIds = &[]string{id}
raw, err := s.client.WithDdoscooClient(func(ddoscooClient *ddoscoo.Client) (interface{}, error) {
return ddoscooClient.DescribeInstanceSpecs(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InstanceNotFound", "ddos_coop3301"}) {
return v, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return v, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
resp, _ := raw.(*ddoscoo.DescribeInstanceSpecsResponse)
if len(resp.InstanceSpecs) == 0 || resp.InstanceSpecs[0].InstanceId != id {
return v, WrapErrorf(Error(GetNotFoundMessage("DdoscooInstanceSpec", id)), NotFoundMsg, ProviderERROR)
}
v = resp.InstanceSpecs[0]
return v, WrapError(err)
}
func (s *DdoscooService) UpdateDdoscooInstanceName(instanceId string, name string) error {
request := ddoscoo.CreateModifyInstanceRemarkRequest()
request.RegionId = "cn-hangzhou"
request.InstanceId = instanceId
request.Remark = name
raw, err := s.client.WithDdoscooClient(func(ddoscooClient *ddoscoo.Client) (interface{}, error) {
return ddoscooClient.ModifyInstanceRemark(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, instanceId, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}
func (s *DdoscooService) UpdateInstanceSpec(schemaName string, specName string, d *schema.ResourceData, meta interface{}) error {
request := bssopenapi.CreateModifyInstanceRequest()
request.RegionId = s.client.RegionId
if d.Get("product_type").(string) == "ddoscoo_intl" {
request.RegionId = "ap-southeast-1"
} else {
request.RegionId = "cn-hangzhou"
}
request.InstanceId = d.Id()
request.ProductCode = "ddos"
request.ProductType = d.Get("product_type").(string)
request.SubscriptionType = "Subscription"
o, n := d.GetChange(schemaName)
oi, _ := strconv.Atoi(o.(string))
ni, _ := strconv.Atoi(n.(string))
if ni < oi {
request.ModifyType = "Downgrade"
} else {
request.ModifyType = "Upgrade"
}
request.Parameter = &[]bssopenapi.ModifyInstanceParameter{
{
Code: specName,
Value: d.Get(schemaName).(string),
},
}
raw, err := s.client.WithBssopenapiClient(func(bssopenapiClient *bssopenapi.Client) (interface{}, error) {
return bssopenapiClient.ModifyInstance(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*bssopenapi.ModifyInstanceResponse)
if !response.Success {
return WrapError(Error(response.Message))
}
return nil
}
func (s *DdoscooService) convertRulesToString(v []interface{}) (string, error) {
arrayMaps := make([]ddoscoo.Rule, len(v))
for i, vv := range v {
item := vv.(map[string]interface{})
arrayMaps[i] = ddoscoo.Rule{
Priority: item["priority"].(int),
RegionId: item["region_id"].(string),
Status: item["status"].(int),
Type: item["type"].(string),
Value: item["value"].(string),
ValueType: item["value_type"].(int),
}
}
maps, err := json.Marshal(arrayMaps)
if err != nil {
return "", WrapError(err)
}
return string(maps), nil
}
func (s *DdoscooService) DescribeDdoscooSchedulerRule(id string) (object ddoscoo.SchedulerRule, err error) {
request := ddoscoo.CreateDescribeSchedulerRulesRequest()
request.RegionId = s.client.RegionId
request.RuleName = id
request.PageSize = requests.NewInteger(10)
raw, err := s.client.WithDdoscooClient(func(ddoscooClient *ddoscoo.Client) (interface{}, error) {
return ddoscooClient.DescribeSchedulerRules(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ddoscoo.DescribeSchedulerRulesResponse)
if len(response.SchedulerRules) < 1 {
err = WrapErrorf(Error(GetNotFoundMessage("DdoscooSchedulerRule", id)), NotFoundMsg, ProviderERROR)
return
}
return response.SchedulerRules[0], nil
}
func (s *DdoscooService) DescribeDdoscooDomainResource(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDdoscooClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDomainResource"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"Domain": id,
"PageNumber": 1,
"PageSize": 10,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.WebRules", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.WebRules", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("DdosCoo", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["Domain"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("DdosCoo", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *DdoscooService) DescribeDdoscooPort(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDdoscooClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribePort"
parts, err := ParseResourceId(id, 3)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"FrontendPort": parts[1],
"FrontendProtocol": parts[2],
"InstanceId": parts[0],
"PageNumber": 1,
"PageSize": 10,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.NetworkRules", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.NetworkRules", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("DdosCoo", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["FrontendProtocol"].(string) != parts[2] {
return object, WrapErrorf(Error(GetNotFoundMessage("DdosCoo", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type DevopsRdcService struct {
client *connectivity.AliyunClient
}
func (s *DevopsRdcService) ListUserOrganization(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDevopsrdcClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListUserOrganization"
request := map[string]interface{}{}
idExist := false
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-03"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Object", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Object", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("RDC", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["Id"]) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("RDC", id)), NotFoundWithResponse, response)
}
return object, nil
}
func (s *DevopsRdcService) DescribeRdcOrganization(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDevopsrdcClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListUserOrganization"
request := map[string]interface{}{}
idExist := false
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-03"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Object", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Object", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("RDC", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["Id"]) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("RDC", id)), NotFoundWithResponse, response)
}
return object, nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type DfsService struct {
client *connectivity.AliyunClient
}
func (s *DfsService) DescribeDfsAccessGroup(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAlidfsClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetAccessGroup"
request := map[string]interface{}{
"InputRegionId": s.client.RegionId,
"AccessGroupId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-06-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidParameter.AccessGroupNotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("DFS:AccessGroup", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.AccessGroup", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.AccessGroup", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *DfsService) GetAccessGroup(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAlidfsClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetAccessGroup"
request := map[string]interface{}{
"InputRegionId": s.client.RegionId,
"AccessGroupId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-06-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidParameter.AccessGroupNotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("DFS:AccessGroup", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.AccessGroup", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.AccessGroup", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *DfsService) DescribeDfsFileSystem(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAlidfsClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetFileSystem"
request := map[string]interface{}{
"InputRegionId": s.client.RegionId,
"FileSystemId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-06-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidParameter.FileSystemNotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("DFS:FileSystem", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.FileSystem", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.FileSystem", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *DfsService) DescribeDfsAccessRule(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAlidfsClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetAccessRule"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"AccessGroupId": parts[0],
"AccessRuleId": parts[1],
}
request["InputRegionId"] = s.client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-06-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidParameter.AccessRuleNotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("DFS:AccessRule", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.AccessRule", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.AccessRule", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *DfsService) DescribeDfsMountPoint(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewAlidfsClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetMountPoint"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"InputRegionId": s.client.RegionId,
"FileSystemId": parts[0],
"MountPointId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-06-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidParameter.MountPointNotFound", "InvalidParameter.FileSystemNotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("DFS:MountPoint", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.MountPoint", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.MountPoint", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type DgService struct {
client *connectivity.AliyunClient
}
func (s *DgService) DescribeDatabaseGatewayGateway(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDgClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetUserGateways"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"PageSize": PageSizeLarge,
"PageNumber": 1,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-27"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
m, err := jsonpath.Get("$.Data", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data", response)
}
v, err := convertJsonStringToList(m.(string))
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if len(v) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("DatabaseGateway", id)), NotFoundWithResponse, response)
}
for _, v := range v {
if fmt.Sprint(v.(map[string]interface{})["gatewayId"]) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("DatabaseGateway", id)), NotFoundWithResponse, response)
}
return
}
func (s *DgService) GetUserGatewayInstances(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDgClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetUserGatewayInstances"
request := map[string]interface{}{
"GatewayId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-03-27"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
m, err := jsonpath.Get("$.Data", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data", response)
}
v, err := convertJsonStringToList(m.(string))
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if len(v) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("DatabaseGateway", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v[0].(map[string]interface{})["gatewayId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("DatabaseGateway", id)), NotFoundWithResponse, response)
}
}
return object, nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type DmService struct {
client *connectivity.AliyunClient
}
func (s *DmService) DescribeDirectMailReceivers(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDmClient()
if err != nil {
return nil, WrapError(err)
}
action := "QueryReceiverByParam"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"PageSize": 20,
"PageNo": 1,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-11-23"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.data.receiver", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.data.receiver", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("DirectMail", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if v.(map[string]interface{})["ReceiverId"].(string) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["PageNo"] = request["PageNo"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("DirectMail", id)), NotFoundWithResponse, response)
}
return
}
func (s *DmService) DescribeDirectMailDomain(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDmClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescDomain"
request := map[string]interface{}{
"DomainId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-11-23"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDomainId.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("DirectMail:Domain", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *DmService) DescDomain(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDmClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescDomain"
request := map[string]interface{}{
"DomainId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-11-23"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDomainId.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("DirectMail:Domain", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *DmService) DescribeDirectMailMailAddress(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDmClient()
if err != nil {
return nil, WrapError(err)
}
action := "QueryMailAddressByParam"
request := map[string]interface{}{
"PageSize": PageSizeLarge,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-11-23"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.data.mailAddress", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.data.mailAddress", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("DirectMail", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["MailAddressId"]) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("DirectMail", id)), NotFoundWithResponse, response)
}
return
}
func (s *DmService) DescribeDirectMailTag(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDmClient()
if err != nil {
return nil, WrapError(err)
}
action := "QueryTagByParam"
request := map[string]interface{}{
"PageSize": 10,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-11-23"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidTag.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("DirectMail:Tag", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.data.tag", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.data.tag", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("DirectMail", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["TagId"]) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("DirectMail", id)), NotFoundWithResponse, response)
}
return
}
package alicloud
import (
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
)
type Dms_enterpriseService struct {
client *connectivity.AliyunClient
}
func (s *Dms_enterpriseService) DescribeDmsEnterpriseInstance(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDmsenterpriseClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetInstance"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"Host": parts[0],
"Port": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-11-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InstanceNoEnoughNumber"}) {
err = WrapErrorf(Error(GetNotFoundMessage("DmsEnterpriseInstance", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Instance", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Instance", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *Dms_enterpriseService) DescribeDmsEnterpriseUser(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDmsenterpriseClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetUser"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"Uid": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-11-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.User", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.User", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"reflect"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/alidns"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type DnsService struct {
client *connectivity.AliyunClient
}
func (s *DnsService) DescribeDns(id string) (*alidns.DescribeDomainInfoResponse, error) {
response := &alidns.DescribeDomainInfoResponse{}
request := alidns.CreateDescribeDomainInfoRequest()
request.RegionId = s.client.RegionId
request.DomainName = id
raw, err := s.client.WithDnsClient(func(dnsClient *alidns.Client) (interface{}, error) {
return dnsClient.DescribeDomainInfo(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDomainName.NoExist"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ = raw.(*alidns.DescribeDomainInfoResponse)
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
if response.DomainName != id {
return nil, WrapErrorf(Error(GetNotFoundMessage("Dns", id)), NotFoundMsg, ProviderERROR)
}
return response, nil
}
func (dns *DnsService) DescribeDnsGroup(id string) (alidns.DomainGroup, error) {
var group alidns.DomainGroup
request := alidns.CreateDescribeDomainGroupsRequest()
request.RegionId = dns.client.RegionId
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)
for {
raw, err := dns.client.WithDnsClient(func(dnsClient *alidns.Client) (interface{}, error) {
return dnsClient.DescribeDomainGroups(request)
})
if err != nil {
return group, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*alidns.DescribeDomainGroupsResponse)
groups := response.DomainGroups.DomainGroup
for _, domainGroup := range groups {
if domainGroup.GroupId == id {
return domainGroup, nil
}
}
if len(groups) < PageSizeLarge {
break
}
if page, err := getNextpageNumber(request.PageNumber); err != nil {
return group, WrapError(err)
} else {
request.PageNumber = page
}
}
return group, WrapErrorf(Error(GetNotFoundMessage("DnsGroup", id)), NotFoundMsg, ProviderERROR)
}
func (dns *DnsService) DescribeDnsRecord(id string) (*alidns.DescribeDomainRecordInfoResponse, error) {
response := &alidns.DescribeDomainRecordInfoResponse{}
request := alidns.CreateDescribeDomainRecordInfoRequest()
request.RecordId = id
request.RegionId = dns.client.RegionId
raw, err := dns.client.WithDnsClient(func(dnsClient *alidns.Client) (interface{}, error) {
return dnsClient.DescribeDomainRecordInfo(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"DomainRecordNotBelongToUser", "InvalidRR.NoExist"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*alidns.DescribeDomainRecordInfoResponse)
if response.RecordId != id {
return response, WrapErrorf(Error(GetNotFoundMessage("DnsRecord", id)), NotFoundMsg, ProviderERROR)
}
return response, nil
}
func (s *DnsService) DescribeDnsInstance(id string) (object alidns.DescribeDnsProductInstanceResponse, err error) {
request := alidns.CreateDescribeDnsProductInstanceRequest()
request.RegionId = s.client.RegionId
request.InstanceId = id
raw, err := s.client.WithDnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.DescribeDnsProductInstance(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDnsProduct"}) {
err = WrapErrorf(Error(GetNotFoundMessage("DnsInstance", id)), NotFoundMsg, ProviderERROR)
return
}
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*alidns.DescribeDnsProductInstanceResponse)
return *response, nil
}
func (s *DnsService) DescribeAlidnsDomainAttachment(id string) (object alidns.DescribeInstanceDomainsResponse, err error) {
request := alidns.CreateDescribeInstanceDomainsRequest()
request.RegionId = s.client.RegionId
request.InstanceId = id
raw, err := s.client.WithDnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.DescribeInstanceDomains(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDnsProduct"}) {
err = WrapErrorf(Error(GetNotFoundMessage("DnsDomainAttachment", id)), NotFoundMsg, ProviderERROR)
return
}
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*alidns.DescribeInstanceDomainsResponse)
if len(response.InstanceDomains) < 1 {
err = WrapErrorf(Error(GetNotFoundMessage("DnsDomainAttachment", id)), NotFoundMsg, ProviderERROR)
return
}
return *response, nil
}
func (s *DnsService) WaitForAlidnsDomainAttachment(id string, expected map[string]interface{}, isDelete bool, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeAlidnsDomainAttachment(id)
if err != nil {
if NotFoundError(err) {
if isDelete {
return nil
}
} else {
return WrapError(err)
}
}
domainNames := make(map[string]interface{}, 0)
for _, v := range object.InstanceDomains {
domainNames[v.DomainName] = v.DomainName
}
exceptDomainNames := make(map[string]interface{}, 0)
for _, v := range expected {
for _, vv := range v.([]interface{}) {
exceptDomainNames[vv.(string)] = vv.(string)
}
}
if reflect.DeepEqual(domainNames, exceptDomainNames) {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, "", expected, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *DnsService) ListTagResources(id string) (object alidns.ListTagResourcesResponse, err error) {
request := alidns.CreateListTagResourcesRequest()
request.RegionId = s.client.RegionId
request.ResourceType = "DOMAIN"
request.ResourceId = &[]string{id}
raw, err := s.client.WithDnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.ListTagResources(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*alidns.ListTagResourcesResponse)
return *response, nil
}
func (s *DnsService) SetResourceTags(d *schema.ResourceData, resourceType string) error {
oldItems, newItems := d.GetChange("tags")
added := make([]alidns.TagResourcesTag, 0)
for key, value := range newItems.(map[string]interface{}) {
added = append(added, alidns.TagResourcesTag{
Key: key,
Value: value.(string),
})
}
removed := make([]string, 0)
for key, _ := range oldItems.(map[string]interface{}) {
removed = append(removed, key)
}
if len(removed) > 0 {
request := alidns.CreateUntagResourcesRequest()
request.RegionId = s.client.RegionId
request.ResourceId = &[]string{d.Id()}
request.ResourceType = resourceType
request.TagKey = &removed
raw, err := s.client.WithDnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.UntagResources(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
request := alidns.CreateTagResourcesRequest()
request.RegionId = s.client.RegionId
request.ResourceId = &[]string{d.Id()}
request.ResourceType = resourceType
request.Tag = &added
raw, err := s.client.WithDnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.TagResources(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
return nil
}
func (s *DnsService) DescribeDnsDomain(id string) (object alidns.DescribeDomainInfoResponse, err error) {
request := alidns.CreateDescribeDomainInfoRequest()
request.RegionId = s.client.RegionId
request.DomainName = id
raw, err := s.client.WithDnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.DescribeDomainInfo(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDomainName.NoExist"}) {
err = WrapErrorf(Error(GetNotFoundMessage("DnsDomain", id)), NotFoundMsg, ProviderERROR)
return
}
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*alidns.DescribeDomainInfoResponse)
return *response, nil
}
package alicloud
import (
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/drds"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type DrdsService struct {
client *connectivity.AliyunClient
}
func (s *DrdsService) DescribeDrdsInstance(id string) (*drds.DescribeDrdsInstanceResponse, error) {
response := &drds.DescribeDrdsInstanceResponse{}
request := drds.CreateDescribeDrdsInstanceRequest()
request.RegionId = s.client.RegionId
request.DrdsInstanceId = id
raw, err := s.client.WithDrdsClient(func(drdsClient *drds.Client) (interface{}, error) {
return drdsClient.DescribeDrdsInstance(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDrdsInstanceId.NotFound"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*drds.DescribeDrdsInstanceResponse)
if response.Data.Status == "5" {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, nil
}
func (s *DrdsService) DrdsInstanceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeDrdsInstance(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.Data.Status == failState {
return object, object.Data.Status, WrapError(Error(FailedToReachTargetStatus, object.Data.Status))
}
}
return object, object.Data.Status, nil
}
}
func (s *DrdsService) WaitDrdsInstanceConfigEffect(id string, item map[string]string, timeout time.Duration) error {
deadline := time.Now().Add(timeout)
for {
effected := false
object, err := s.DescribeDrdsInstance(id)
if err != nil {
if NotFoundError(err) {
return WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return WrapError(err)
}
if value, ok := item["description"]; ok {
if object.Data.Description == value {
effected = true
}
}
if effected {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.Data, item, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type DtsService struct {
client *connectivity.AliyunClient
}
func (s *DtsService) DescribeDtsJobMonitorRule(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDtsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeJobMonitorRule"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DtsJobId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *DtsService) DescribeDtsSubscriptionJob(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDtsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDtsJobDetail"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DtsJobId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Forbidden.InstanceNotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("DTS:SubscriptionJob", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
if object["Status"] == "Starting" {
object["Status"] = "Normal"
}
return object, nil
}
func (s *DtsService) DtsSubscriptionJobStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeDtsSubscriptionJob(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *DtsService) DescribeDtsSynchronizationInstance(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDtsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDtsJobDetail"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DtsInstanceID": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Forbidden.InstanceNotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("DTS:SynchronizationInstance", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *DtsService) ListTagResources(id string, resourceType string) (object interface{}, err error) {
conn, err := s.client.NewDtsClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListTagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": id,
}
tags := make([]interface{}, 0)
var response map[string]interface{}
for {
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{Throttling}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.TagResources.TagResource", response)
if err != nil {
return resource.NonRetryableError(WrapErrorf(err, FailedGetAttributeMsg, id, "$.TagResources.TagResource", response))
}
if v != nil {
tags = append(tags, v.([]interface{})...)
}
return nil
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
if response["NextToken"] == nil {
break
}
request["NextToken"] = response["NextToken"]
}
return tags, nil
}
func (s *DtsService) SetResourceTags(d *schema.ResourceData, resourceType string) error {
if d.HasChange("tags") {
added, removed := parsingTags(d)
conn, err := s.client.NewDtsClient()
if err != nil {
return WrapError(err)
}
removedTagKeys := make([]string, 0)
for _, v := range removed {
if !ignoredTags(v, "") {
removedTagKeys = append(removedTagKeys, v)
}
}
if len(removedTagKeys) > 0 {
action := "UntagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": d.Get("dts_instance_id"),
}
for i, key := range removedTagKeys {
request[fmt.Sprintf("TagKey.%d", i+1)] = key
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
action := "TagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": d.Get("dts_instance_id"),
}
count := 1
for key, value := range added {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("tags")
}
return nil
}
func (s *DtsService) DescribeDtsSynchronizationJob(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDtsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDtsJobDetail"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DtsJobId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Forbidden.InstanceNotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("DTS:SynchronizationJob", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
// From startup to synchronizing, the resource goes through the pre-check and initialization phases.
// Because the initialization phase takes too long, and once it passes the pre-check, it can be considered that the task can be executed normally.
// Therefore, the initialization state is regarded as an equivalent synchronization state.
if object["Status"] == "synchronizing" || object["Status"] == "Initializing" {
object["Status"] = "Synchronizing"
}
return object, nil
}
func (s *DtsService) DescribeDtsJobDetail(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDtsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDtsJobDetail"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DtsJobId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Forbidden.InstanceNotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("DTS:SynchronizationJob", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *DtsService) DtsSynchronizationJobStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeDtsSynchronizationJob(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *DtsService) DescribeDtsConsumerChannel(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDtsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeConsumerChannel"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DtsInstanceId": parts[0],
"PageSize": PageSizeMedium,
"PageNumber": 1,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.ConsumerChannels", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ConsumerChannels", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("DTS", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["ConsumerGroupId"]) == parts[1] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("DTS", id)), NotFoundWithResponse, response)
}
return
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type EaisService struct {
client *connectivity.AliyunClient
}
func (s *EaisService) DescribeEaisInstance(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEaisClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeEais"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ElasticAcceleratedInstanceIds": "[\"" + id + "\"]",
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-24"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Instances.Instance", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Instances.Instance", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("EAIS", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["ElasticAcceleratedInstanceId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("EAIS", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *EaisService) EaisInstanceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeEaisInstance(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
package alicloud
import (
"fmt"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type EcdService struct {
client *connectivity.AliyunClient
}
func (s *EcdService) DescribeEcdPolicyGroup(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewGwsecdClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribePolicyGroups"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"PolicyGroupId": []string{id},
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.DescribePolicyGroups", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.DescribePolicyGroups", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ECD", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["PolicyGroupId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ECD", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func parsingResourceType(d *schema.ResourceData, resourceType string) ([]interface{}, []interface{}) {
oraw, nraw := d.GetChange(resourceType)
removed := oraw.(*schema.Set).List()
added := nraw.(*schema.Set).List()
return removed, added
}
func (s *EcdService) setAuthAccessPolicyRules(d *schema.ResourceData, request map[string]interface{}, resourceType string) error {
if d.HasChange(resourceType) {
removed, added := parsingResourceType(d, resourceType)
if len(removed) > 0 {
action := "ModifyPolicyGroup"
conn, err := s.client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
req := map[string]interface{}{
"PolicyGroupId": d.Id(),
}
var response map[string]interface{}
for authorizeAccessPolicyRulesPtr, authorizeAccessPolicyRules := range removed {
authorizeAccessPolicyRulesArg := authorizeAccessPolicyRules.(map[string]interface{})
req["RevokeAccessPolicyRule."+fmt.Sprint(authorizeAccessPolicyRulesPtr+1)+".CidrIp"] = authorizeAccessPolicyRulesArg["cidr_ip"]
req["RevokeAccessPolicyRule."+fmt.Sprint(authorizeAccessPolicyRulesPtr+1)+".Description"] = authorizeAccessPolicyRulesArg["description"]
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, req, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
for authorizeAccessPolicyRulesPtr, authorizeAccessPolicyRules := range added {
authorizeAccessPolicyRulesArg := authorizeAccessPolicyRules.(map[string]interface{})
request["AuthorizeAccessPolicyRule."+fmt.Sprint(authorizeAccessPolicyRulesPtr+1)+".CidrIp"] = authorizeAccessPolicyRulesArg["cidr_ip"]
request["AuthorizeAccessPolicyRule."+fmt.Sprint(authorizeAccessPolicyRulesPtr+1)+".Description"] = authorizeAccessPolicyRulesArg["description"]
}
}
}
return nil
}
func (s *EcdService) setAuthSecurityPolicyRules(d *schema.ResourceData, request map[string]interface{}, resourceType string) error {
if d.HasChange(resourceType) {
removed, added := parsingResourceType(d, resourceType)
if len(removed) > 0 {
action := "ModifyPolicyGroup"
conn, err := s.client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
req := map[string]interface{}{
"PolicyGroupId": d.Id(),
}
var response map[string]interface{}
for authorizeSecurityPolicyRulesPtr, authorizeSecurityPolicyRules := range removed {
authorizeSecurityPolicyRulesArg := authorizeSecurityPolicyRules.(map[string]interface{})
req["RevokeSecurityPolicyRule."+fmt.Sprint(authorizeSecurityPolicyRulesPtr+1)+".CidrIp"] = authorizeSecurityPolicyRulesArg["cidr_ip"]
req["RevokeSecurityPolicyRule."+fmt.Sprint(authorizeSecurityPolicyRulesPtr+1)+".Description"] = authorizeSecurityPolicyRulesArg["description"]
req["RevokeSecurityPolicyRule."+fmt.Sprint(authorizeSecurityPolicyRulesPtr+1)+".IpProtocol"] = authorizeSecurityPolicyRulesArg["ip_protocol"]
req["RevokeSecurityPolicyRule."+fmt.Sprint(authorizeSecurityPolicyRulesPtr+1)+".Policy"] = authorizeSecurityPolicyRulesArg["policy"]
req["RevokeSecurityPolicyRule."+fmt.Sprint(authorizeSecurityPolicyRulesPtr+1)+".PortRange"] = authorizeSecurityPolicyRulesArg["port_range"]
req["RevokeSecurityPolicyRule."+fmt.Sprint(authorizeSecurityPolicyRulesPtr+1)+".Priority"] = authorizeSecurityPolicyRulesArg["priority"]
req["RevokeSecurityPolicyRule."+fmt.Sprint(authorizeSecurityPolicyRulesPtr+1)+".Type"] = authorizeSecurityPolicyRulesArg["type"]
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, req, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
for authorizeSecurityPolicyRulesPtr, authorizeSecurityPolicyRules := range added {
authorizeSecurityPolicyRulesArg := authorizeSecurityPolicyRules.(map[string]interface{})
request["AuthorizeSecurityPolicyRule."+fmt.Sprint(authorizeSecurityPolicyRulesPtr+1)+".CidrIp"] = authorizeSecurityPolicyRulesArg["cidr_ip"]
request["AuthorizeSecurityPolicyRule."+fmt.Sprint(authorizeSecurityPolicyRulesPtr+1)+".Description"] = authorizeSecurityPolicyRulesArg["description"]
request["AuthorizeSecurityPolicyRule."+fmt.Sprint(authorizeSecurityPolicyRulesPtr+1)+".IpProtocol"] = authorizeSecurityPolicyRulesArg["ip_protocol"]
request["AuthorizeSecurityPolicyRule."+fmt.Sprint(authorizeSecurityPolicyRulesPtr+1)+".Policy"] = authorizeSecurityPolicyRulesArg["policy"]
request["AuthorizeSecurityPolicyRule."+fmt.Sprint(authorizeSecurityPolicyRulesPtr+1)+".PortRange"] = authorizeSecurityPolicyRulesArg["port_range"]
request["AuthorizeSecurityPolicyRule."+fmt.Sprint(authorizeSecurityPolicyRulesPtr+1)+".Priority"] = authorizeSecurityPolicyRulesArg["priority"]
request["AuthorizeSecurityPolicyRule."+fmt.Sprint(authorizeSecurityPolicyRulesPtr+1)+".Type"] = authorizeSecurityPolicyRulesArg["type"]
}
}
}
return nil
}
func (s *EcdService) DescribeEcdSimpleOfficeSite(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewGwsecdClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeOfficeSites"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"OfficeSiteId": []string{id},
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.OfficeSites", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.OfficeSites", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ECD", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["OfficeSiteId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ECD", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *EcdService) EcdSimpleOfficeSiteStateRefreshFunc(id string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeEcdSimpleOfficeSite(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
return object, object["Status"].(string), nil
}
}
func (s *EcdService) DescribeEcdNasFileSystem(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewGwsecdClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeNASFileSystems"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"FileSystemId": []string{id},
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.FileSystems", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.FileSystems", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ECD", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["FileSystemId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ECD", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *EcdService) DescribeEcdNetworkPackage(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewGwsecdClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeNetworkPackages"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"NetworkPackageId": []string{id},
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.NetworkPackages", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.NetworkPackages", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ECD", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["NetworkPackageId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ECD", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *EcdService) EcdNasFileSystemStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeEcdNasFileSystem(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["FileSystemStatus"]) == failState {
return object, fmt.Sprint(object["FileSystemStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["FileSystemStatus"])))
}
}
return object, fmt.Sprint(object["FileSystemStatus"]), nil
}
}
func (s *EcdService) EcdNetworkPackageRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeEcdNetworkPackage(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["NetworkPackageStatus"]) == failState {
return object, fmt.Sprint(object["NetworkPackageStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["FileSystemStatus"])))
}
}
return object, fmt.Sprint(object["NetworkPackageStatus"]), nil
}
}
func (s *EcdService) SetResourceTags(d *schema.ResourceData, resourceType string) error {
if d.HasChange("tags") {
added, removed := parsingTags(d)
conn, err := s.client.NewGwsecdClient()
if err != nil {
return WrapError(err)
}
removedTagKeys := make([]string, 0)
for _, v := range removed {
if !ignoredTags(v, "") {
removedTagKeys = append(removedTagKeys, v)
}
}
if len(removedTagKeys) > 0 {
action := "UntagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId": []string{d.Id()},
}
for i, key := range removedTagKeys {
request[fmt.Sprintf("TagKey.%d", i+1)] = key
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
action := "TagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId": []string{d.Id()},
}
count := 1
for key, value := range added {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("tags")
}
return nil
}
func (s *EcdService) DescribeEcdDesktop(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewGwsecdClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDesktops"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DesktopId.1": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Desktops", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Desktops", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ECD", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["DesktopId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ECD", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *EcdService) EcdDesktopStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeEcdDesktop(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["DesktopStatus"]) == failState {
return object, fmt.Sprint(object["DesktopStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["DesktopStatus"])))
}
}
return object, fmt.Sprint(object["DesktopStatus"]), nil
}
}
func (s *EcdService) EcdDesktopDesktopTypeRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeEcdDesktop(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["DesktopType"]) == failState {
return object, fmt.Sprint(object["DesktopType"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["DesktopType"])))
}
}
return object, fmt.Sprint(object["DesktopType"]), nil
}
}
func (s *EcdService) EcdDesktopChargeTypeFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeEcdDesktop(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(convertEcdDesktopPaymentTypeResponse(object["ChargeType"])) == failState {
return object, fmt.Sprint(object["ChargeType"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(convertEcdDesktopPaymentTypeResponse(object["DesktopStatus"]))))
}
}
return object, fmt.Sprint(convertEcdDesktopPaymentTypeResponse(object["ChargeType"])), nil
}
}
func (s *EcdService) DescribeEcdImage(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewGwsecdClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeImages"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ImageId": []string{id},
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Images", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Images", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ECD", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["ImageId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ECD", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *EcdService) EcdImageStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeEcdImage(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *EcdService) DescribeEcdCommand(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewGwsecdClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeInvocations"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"InvokeId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-09-30"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Invocations", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Invocations", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ECD", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["InvokeId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ECD", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *EcdService) EcdCommandStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeEcdCommand(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["InvocationStatus"]) == failState {
return object, fmt.Sprint(object["InvocationStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["InvocationStatus"])))
}
}
return object, fmt.Sprint(object["InvocationStatus"]), nil
}
}
package alicloud
import (
"encoding/json"
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/alibaba-cloud-sdk-go/services/eci"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type EciService struct {
client *connectivity.AliyunClient
}
func (s *EciService) DescribeEciImageCache(id string) (object eci.DescribeImageCachesImageCache0, err error) {
request := eci.CreateDescribeImageCachesRequest()
request.RegionId = s.client.RegionId
request.ImageCacheId = id
raw, err := s.client.WithEciClient(func(eciClient *eci.Client) (interface{}, error) {
return eciClient.DescribeImageCaches(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*eci.DescribeImageCachesResponse)
if len(response.ImageCaches) < 1 {
err = WrapErrorf(Error(GetNotFoundMessage("EciImageCache", id)), NotFoundMsg, ProviderERROR)
return
}
return response.ImageCaches[0], nil
}
func (s *EciService) EciImageCacheStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeEciImageCache(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.Status == failState {
return object, object.Status, WrapError(Error(FailedToReachTargetStatus, object.Status))
}
}
return object, object.Status, nil
}
}
func (s *EciService) DescribeEciContainerGroup(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEciClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeContainerGroups"
jsonId, err := json.Marshal([]string{id})
if err != nil {
return nil, WrapError(err)
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ContainerGroupIds": string(jsonId),
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-08-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidParameter.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("EciContainerGroup", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.ContainerGroups", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ContainerGroups", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ECIOpenAPI", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["ContainerGroupId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ECIOpenAPI", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *EciService) EciContainerGroupStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeEciContainerGroup(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["Status"].(string) == failState {
return object, object["Status"].(string), WrapError(Error(FailedToReachTargetStatus, object["Status"].(string)))
}
}
return object, object["Status"].(string), nil
}
}
func (s *EciService) DescribeEciVirtualNode(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEciClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeVirtualNodes"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-08-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.VirtualNodes", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.VirtualNodes", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ECI", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["VirtualNodeId"]) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("ECI", id)), NotFoundWithResponse, response)
}
return
}
func (s *EciService) EciVirtualNodeStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeEciVirtualNode(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
package alicloud
import (
"encoding/json"
"fmt"
"log"
"regexp"
"strings"
"time"
"strconv"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type EcsService struct {
client *connectivity.AliyunClient
}
func (s *EcsService) JudgeRegionValidation(key, region string) error {
request := ecs.CreateDescribeRegionsRequest()
request.RegionId = s.client.RegionId
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeRegions(request)
})
if err != nil {
return fmt.Errorf("DescribeRegions got an error: %#v", err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
resp, _ := raw.(*ecs.DescribeRegionsResponse)
if resp == nil || len(resp.Regions.Region) < 1 {
return GetNotFoundErrorFromString("There is no any available region.")
}
var rs []string
for _, v := range resp.Regions.Region {
if v.RegionId == region {
return nil
}
rs = append(rs, v.RegionId)
}
return fmt.Errorf("'%s' is invalid. Expected on %v.", key, strings.Join(rs, ", "))
}
// DescribeZone validate zoneId is valid in region
func (s *EcsService) DescribeZone(id string) (zone map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEcsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeZones"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return zone, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Zones.Zone", response)
if err != nil {
return zone, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
if len(v.([]interface{})) < 1 {
return zone, WrapError(Error("There is no any availability zone in region %s.", s.client.RegionId))
}
zoneIds := []string{}
for _, z := range v.([]interface{}) {
tmp := z.(map[string]interface{})
if tmp["ZoneId"].(string) == id {
return tmp, nil
}
zoneIds = append(zoneIds, tmp["ZoneId"].(string))
}
return zone, WrapError(Error("availability_zone %s not exists in region %s, all zones are %s", id, s.client.RegionId, zoneIds))
}
func (s *EcsService) DescribeZones(d *schema.ResourceData) (zones []ecs.Zone, err error) {
request := ecs.CreateDescribeZonesRequest()
request.RegionId = s.client.RegionId
request.InstanceChargeType = d.Get("instance_charge_type").(string)
request.SpotStrategy = d.Get("spot_strategy").(string)
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeZones(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, "alicloud_instance_type_families", request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ecs.DescribeZonesResponse)
if len(response.Zones.Zone) < 1 {
return zones, WrapError(Error("There is no any availability zone in region %s.", s.client.RegionId))
}
if v, ok := d.GetOk("zone_id"); ok {
zoneIds := []string{}
for _, z := range response.Zones.Zone {
if z.ZoneId == v.(string) {
return []ecs.Zone{z}, nil
}
zoneIds = append(zoneIds, z.ZoneId)
}
return zones, WrapError(Error("availability_zone %s not exists in region %s, all zones are %s", v.(string), s.client.RegionId, zoneIds))
} else {
return response.Zones.Zone, nil
}
}
func (s *EcsService) DescribeInstance(id string) (instance ecs.Instance, err error) {
request := ecs.CreateDescribeInstancesRequest()
request.RegionId = s.client.RegionId
request.InstanceIds = convertListToJsonString([]interface{}{id})
var response *ecs.DescribeInstancesResponse
wait := incrementalWait(1*time.Second, 1*time.Second)
err = resource.Retry(10*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeInstances(request)
})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*ecs.DescribeInstancesResponse)
return nil
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
if len(response.Instances.Instance) < 1 {
return instance, WrapErrorf(Error(GetNotFoundMessage("Instance", id)), NotFoundMsg, ProviderERROR, response.RequestId)
}
return response.Instances.Instance[0], nil
}
func (s *EcsService) DescribeInstanceAttribute(id string) (instance ecs.DescribeInstanceAttributeResponse, err error) {
request := ecs.CreateDescribeInstanceAttributeRequest()
request.InstanceId = id
request.RegionId = s.client.RegionId
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeInstanceAttribute(request)
})
if err != nil {
return instance, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ecs.DescribeInstanceAttributeResponse)
if response.InstanceId != id {
return instance, WrapErrorf(Error(GetNotFoundMessage("Instance", id)), NotFoundMsg, ProviderERROR, response.RequestId)
}
return *response, nil
}
func (s *EcsService) DescribeInstanceSystemDisk(id, rg string) (disk ecs.Disk, err error) {
request := ecs.CreateDescribeDisksRequest()
request.InstanceId = id
request.DiskType = string(DiskTypeSystem)
request.RegionId = s.client.RegionId
// resource_group_id may cause failure to query the system disk of the instance, because the newly created instance may fail to query through the resource_group_id parameter, so temporarily remove this parameter.
// request.ResourceGroupId = rg
var response *ecs.DescribeDisksResponse
wait := incrementalWait(1*time.Second, 1*time.Second)
err = resource.Retry(10*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeDisks(request)
})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*ecs.DescribeDisksResponse)
return nil
})
if err != nil {
return disk, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
if len(response.Disks.Disk) < 1 || response.Disks.Disk[0].InstanceId != id {
return disk, WrapErrorf(Error(GetNotFoundMessage("Instance", id)), NotFoundMsg, ProviderERROR, response.RequestId)
}
return response.Disks.Disk[0], nil
}
// ResourceAvailable check resource available for zone
func (s *EcsService) ResourceAvailable(zone ecs.Zone, resourceType ResourceType) error {
for _, res := range zone.AvailableResourceCreation.ResourceTypes {
if res == string(resourceType) {
return nil
}
}
return WrapError(Error("%s is not available in %s zone of %s region", resourceType, zone.ZoneId, s.client.Region))
}
func (s *EcsService) DiskAvailable(zone map[string]interface{}, diskCategory DiskCategory) error {
for _, disk := range zone["AvailableDiskCategories"].(map[string]interface{})["DiskCategories"].([]interface{}) {
if disk.(string) == string(diskCategory) {
return nil
}
}
return WrapError(Error("%s is not available in %s zone of %s region", diskCategory, zone["ZoneId"], s.client.Region))
}
func (s *EcsService) JoinSecurityGroups(instanceId string, securityGroupIds []string) error {
request := ecs.CreateJoinSecurityGroupRequest()
request.InstanceId = instanceId
request.RegionId = s.client.RegionId
for _, sid := range securityGroupIds {
request.SecurityGroupId = sid
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.JoinSecurityGroup(request)
})
if err != nil && IsExpectedErrors(err, []string{"InvalidInstanceId.AlreadyExists"}) {
return WrapErrorf(err, DefaultErrorMsg, instanceId, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
return nil
}
func (s *EcsService) LeaveSecurityGroups(instanceId string, securityGroupIds []string) error {
request := ecs.CreateLeaveSecurityGroupRequest()
request.InstanceId = instanceId
request.RegionId = s.client.RegionId
for _, sid := range securityGroupIds {
request.SecurityGroupId = sid
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.LeaveSecurityGroup(request)
})
if err != nil && IsExpectedErrors(err, []string{"InvalidSecurityGroupId.NotFound"}) {
return WrapErrorf(err, DefaultErrorMsg, instanceId, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
return nil
}
func (s *EcsService) DescribeSecurityGroup(id string) (group ecs.DescribeSecurityGroupAttributeResponse, err error) {
request := ecs.CreateDescribeSecurityGroupAttributeRequest()
request.SecurityGroupId = id
request.RegionId = s.client.RegionId
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeSecurityGroupAttribute(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidSecurityGroupId.NotFound"}) {
err = WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ecs.DescribeSecurityGroupAttributeResponse)
if response.SecurityGroupId != id {
err = WrapErrorf(Error(GetNotFoundMessage("Security Group", id)), NotFoundMsg, ProviderERROR, response.RequestId)
return
}
return *response, nil
}
func (s *EcsService) DescribeSecurityGroupAttribute(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEcsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeSecurityGroupAttribute"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"SecurityGroupId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidSecurityGroupId.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS:SecurityGroup", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
if v.(map[string]interface{})["SecurityGroupId"] != id {
err = WrapErrorf(Error(GetNotFoundMessage("Security Group", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
return
}
object = v.(map[string]interface{})
return object, nil
}
func (s *EcsService) DescribeSecurityGroupRule(id string) (rule ecs.Permission, err error) {
parts, err := ParseResourceId(id, 8)
if err != nil {
return rule, WrapError(err)
}
groupId, direction, ipProtocol, portRange, nicType, cidr_ip, policy := parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6]
priority, err := strconv.Atoi(parts[7])
if err != nil {
return rule, WrapError(err)
}
request := ecs.CreateDescribeSecurityGroupAttributeRequest()
request.SecurityGroupId = groupId
request.Direction = direction
request.NicType = nicType
request.RegionId = s.client.RegionId
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeSecurityGroupAttribute(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidSecurityGroupId.NotFound"}) {
err = WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ecs.DescribeSecurityGroupAttributeResponse)
if response == nil {
return rule, GetNotFoundErrorFromString(GetNotFoundMessage("Security Group", groupId))
}
for _, ru := range response.Permissions.Permission {
if strings.ToLower(string(ru.IpProtocol)) == ipProtocol && ru.PortRange == portRange {
cidr := ru.SourceCidrIp
if direction == string(DirectionIngress) && cidr == "" {
cidr = ru.SourceGroupId
}
if direction == string(DirectionEgress) {
if cidr = ru.DestCidrIp; cidr == "" {
cidr = ru.DestGroupId
}
}
if cidr == cidr_ip && strings.ToLower(string(ru.Policy)) == policy && ru.Priority == strconv.Itoa(priority) {
return ru, nil
}
}
}
return rule, WrapErrorf(Error(GetNotFoundMessage("Security Group Rule", id)), NotFoundMsg, ProviderERROR, response.RequestId)
}
func (s *EcsService) DescribeAvailableResources(d *schema.ResourceData, meta interface{}, destination DestinationResource) (zoneId string, validZones []ecs.AvailableZone, requestId string, err error) {
client := meta.(*connectivity.AliyunClient)
// Before creating resources, check input parameters validity according available zone.
// If availability zone is nil, it will return all of supported resources in the current.
request := ecs.CreateDescribeAvailableResourceRequest()
request.RegionId = s.client.RegionId
request.DestinationResource = string(destination)
if destination == InstanceTypeResource {
if v, ok := d.GetOk("cpu_core_count"); ok && v.(int) > 0 {
request.Cores = requests.NewInteger(v.(int))
}
if v, ok := d.GetOk("memory_size"); ok && v.(float64) > 0 {
request.Memory = requests.NewFloat(v.(float64))
}
}
request.IoOptimized = string(IOOptimized)
if v, ok := d.GetOk("availability_zone"); ok && strings.TrimSpace(v.(string)) != "" {
zoneId = strings.TrimSpace(v.(string))
} else if v, ok := d.GetOk("vswitch_id"); ok && strings.TrimSpace(v.(string)) != "" {
vpcService := VpcService{s.client}
if vsw, err := vpcService.DescribeVSwitch(strings.TrimSpace(v.(string))); err == nil {
zoneId = vsw.ZoneId
}
}
if v, ok := d.GetOk("instance_charge_type"); ok && strings.TrimSpace(v.(string)) != "" {
request.InstanceChargeType = strings.TrimSpace(v.(string))
}
if v, ok := d.GetOk("spot_strategy"); ok && strings.TrimSpace(v.(string)) != "" {
request.SpotStrategy = strings.TrimSpace(v.(string))
}
if v, ok := d.GetOk("network_type"); ok && strings.TrimSpace(v.(string)) != "" {
request.NetworkCategory = strings.TrimSpace(v.(string))
}
if v, ok := d.GetOk("is_outdated"); ok && v.(bool) == true {
request.IoOptimized = string(NoneOptimized)
}
if v, ok := d.GetOk("system_disk_category"); ok && strings.TrimSpace(v.(string)) != "" {
request.SystemDiskCategory = strings.TrimSpace(v.(string))
}
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeAvailableResource(request)
})
if err != nil {
return "", nil, "", WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ecs.DescribeAvailableResourceResponse)
requestId = response.RequestId
if len(response.AvailableZones.AvailableZone) < 1 {
err = WrapError(Error("There are no available zones in the API DescribeAvailableResource response: %#v.", response))
return
}
valid := false
soldout := false
var expectedZones []string
for _, zone := range response.AvailableZones.AvailableZone {
if zone.Status == string(SoldOut) {
if zone.ZoneId == zoneId {
soldout = true
}
continue
}
if zoneId != "" && zone.ZoneId == zoneId {
valid = true
validZones = append(make([]ecs.AvailableZone, 1), zone)
break
}
expectedZones = append(expectedZones, zone.ZoneId)
validZones = append(validZones, zone)
}
if zoneId != "" {
if !valid {
err = WrapError(Error("Availability zone %s status is not available in the region %s. Expected availability zones: %s. \nDescribeAvailableResource response: %#v.",
zoneId, client.RegionId, strings.Join(expectedZones, ", "), response))
return
}
if soldout {
err = WrapError(Error("Availability zone %s status is sold out in the region %s. Expected availability zones: %s. \nDescribeAvailableResource response: %#v.",
zoneId, client.RegionId, strings.Join(expectedZones, ", "), response))
return
}
}
if len(validZones) <= 0 {
err = WrapError(Error("There is no availability resources in the region %s. Please choose another region. \nDescribeAvailableResource response: %#v.", client.RegionId, response))
return
}
return
}
func (s *EcsService) InstanceTypeValidation(targetType, zoneId string, validZones []ecs.AvailableZone) error {
mapInstanceTypeToZones := make(map[string]string)
var expectedInstanceTypes []string
for _, zone := range validZones {
if zoneId != "" && zoneId != zone.ZoneId {
continue
}
for _, r := range zone.AvailableResources.AvailableResource {
if r.Type == string(InstanceTypeResource) {
for _, t := range r.SupportedResources.SupportedResource {
if t.Status == string(SoldOut) {
continue
}
if targetType == t.Value {
return nil
}
if _, ok := mapInstanceTypeToZones[t.Value]; !ok {
expectedInstanceTypes = append(expectedInstanceTypes, t.Value)
mapInstanceTypeToZones[t.Value] = t.Value
}
}
}
}
}
if zoneId != "" {
return WrapError(Error("The instance type %s is solded out or is not supported in the zone %s. Expected instance types: %s", targetType, zoneId, strings.Join(expectedInstanceTypes, ", ")))
}
return WrapError(Error("The instance type %s is solded out or is not supported in the region %s. Expected instance types: %s", targetType, s.client.RegionId, strings.Join(expectedInstanceTypes, ", ")))
}
func (s *EcsService) QueryInstancesWithKeyPair(instanceIdsStr, keyPair string) (instanceIds []string, err error) {
action := "DescribeInstances"
var response map[string]interface{}
conn, err := s.client.NewEcsClient()
request := make(map[string]interface{})
request["RegionId"] = s.client.RegionId
request["PageSize"] = PageSizeLarge
request["PageNumber"] = 1
request["InstanceIds"] = instanceIdsStr
request["KeyPairName"] = keyPair
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, keyPair, action, AlibabaCloudSdkGoERROR)
return
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Instances.Instance", response)
if err != nil {
return instanceIds, WrapErrorf(err, FailedGetAttributeMsg, keyPair, "$.Instances.Instance", response)
}
if len(v.([]interface{})) > 0 {
for _, inst := range v.([]interface{}) {
instanceIds = append(instanceIds, inst.(map[string]interface{})["InstanceId"].(string))
}
}
if len(v.([]interface{})) < request["PageNumber"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
return
}
func (s *EcsService) DescribeKeyPair(id string) (keyPair ecs.KeyPair, err error) {
request := ecs.CreateDescribeKeyPairsRequest()
request.RegionId = s.client.RegionId
request.KeyPairName = id
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeKeyPairs(request)
})
if err != nil {
return keyPair, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
object, _ := raw.(*ecs.DescribeKeyPairsResponse)
if len(object.KeyPairs.KeyPair) < 1 || object.KeyPairs.KeyPair[0].KeyPairName != id {
return keyPair, WrapErrorf(Error(GetNotFoundMessage("KeyPair", id)), NotFoundMsg, ProviderERROR, object.RequestId)
}
return object.KeyPairs.KeyPair[0], nil
}
func (s *EcsService) DescribeEcsKeyPairAttachment(id string) (keyPair ecs.KeyPair, err error) {
index := strings.LastIndexByte(id, ':')
keyPairName := id[:index]
keyPair, err = s.DescribeKeyPair(keyPairName)
if err != nil {
return keyPair, WrapError(err)
}
if keyPair.KeyPairName != keyPairName {
err = WrapErrorf(Error(GetNotFoundMessage("KeyPairAttachment", id)), NotFoundMsg, ProviderERROR)
}
return keyPair, nil
}
func (s *EcsService) DescribeDisk(id string) (disk ecs.Disk, err error) {
request := ecs.CreateDescribeDisksRequest()
request.DiskIds = convertListToJsonString([]interface{}{id})
request.RegionId = s.client.RegionId
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeDisks(request)
})
if err != nil {
return disk, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*ecs.DescribeDisksResponse)
if len(response.Disks.Disk) < 1 || response.Disks.Disk[0].DiskId != id {
err = WrapErrorf(Error(GetNotFoundMessage("Disk", id)), NotFoundMsg, ProviderERROR, response.RequestId)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return response.Disks.Disk[0], nil
}
func (s *EcsService) DescribeEcsDiskAttachment(id string) (disk map[string]interface{}, err error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
return disk, WrapError(err)
}
disk, err = s.DescribeEcsDisk(parts[0])
if err != nil {
return disk, WrapError(err)
}
if disk["InstanceId"] != parts[1] && disk["Status"] != string(InUse) {
err = WrapErrorf(Error(GetNotFoundMessage("EcsDiskAttachment", id)), NotFoundMsg, ProviderERROR)
}
return
}
func (s *EcsService) DescribeDisksByType(instanceId string, diskType DiskType) (disk []ecs.Disk, err error) {
request := ecs.CreateDescribeDisksRequest()
request.RegionId = s.client.RegionId
if instanceId != "" {
request.InstanceId = instanceId
}
request.DiskType = string(diskType)
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeDisks(request)
})
if err != nil {
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
resp, _ := raw.(*ecs.DescribeDisksResponse)
if resp == nil {
return
}
return resp.Disks.Disk, nil
}
func (s *EcsService) DescribeTags(resourceId string, resourceType TagResourceType) (tags []ecs.Tag, err error) {
request := ecs.CreateDescribeTagsRequest()
request.RegionId = s.client.RegionId
request.ResourceType = string(resourceType)
request.ResourceId = resourceId
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeTags(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, resourceId, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ecs.DescribeTagsResponse)
if len(response.Tags.Tag) < 1 {
err = WrapErrorf(Error(GetNotFoundMessage("Tags", resourceId)), NotFoundMsg, ProviderERROR)
return
}
return response.Tags.Tag, nil
}
func (s *EcsService) DescribeImageById(id string) (image ecs.Image, err error) {
request := ecs.CreateDescribeImagesRequest()
request.RegionId = s.client.RegionId
request.ImageId = id
request.Status = fmt.Sprintf("%s,%s,%s,%s,%s", "Creating", "Waiting", "Available", "UnAvailable", "CreateFailed")
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeImages(request)
})
if err != nil {
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
resp, _ := raw.(*ecs.DescribeImagesResponse)
if resp == nil || len(resp.Images.Image) < 1 {
return image, GetNotFoundErrorFromString(GetNotFoundMessage("Image", id))
}
return resp.Images.Image[0], nil
}
func (s *EcsService) deleteImage(d *schema.ResourceData) error {
object, err := s.DescribeImageById(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return WrapError(err)
}
request := ecs.CreateDeleteImageRequest()
if force, ok := d.GetOk("force"); ok {
request.Force = requests.NewBoolean(force.(bool))
}
request.RegionId = s.client.RegionId
request.ImageId = object.ImageId
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DeleteImage(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutCreate), 3*time.Second, s.ImageStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
if v, ok := d.GetOk("delete_auto_snapshot"); ok && v.(bool) {
errs := map[string]error{}
for _, item := range object.DiskDeviceMappings.DiskDeviceMapping {
if item.SnapshotId == "" {
continue
}
request := ecs.CreateDeleteSnapshotRequest()
request.RegionId = s.client.RegionId
request.SnapshotId = item.SnapshotId
request.Force = requests.NewBoolean(true)
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DeleteSnapshot(request)
})
if err != nil {
errs[item.SnapshotId] = err
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
if len(errs) > 0 {
errParts := []string{"Errors while deleting associated snapshots:"}
for snapshotId, err := range errs {
errParts = append(errParts, fmt.Sprintf("%s: %s", snapshotId, err))
}
errParts = append(errParts, "These are no longer managed by Terraform and must be deleted manually.")
return WrapError(fmt.Errorf(strings.Join(errParts, "\n")))
}
}
return nil
}
func (s *EcsService) updateImage(d *schema.ResourceData) error {
d.Partial(true)
err := setTags(s.client, TagResourceImage, d)
if err != nil {
return WrapError(err)
} else {
d.SetPartial("tags")
}
request := ecs.CreateModifyImageAttributeRequest()
request.RegionId = s.client.RegionId
request.ImageId = d.Id()
if d.HasChange("description") || d.HasChange("name") || d.HasChange("image_name") {
if description, ok := d.GetOk("description"); ok {
request.Description = description.(string)
}
if imageName, ok := d.GetOk("image_name"); ok {
request.ImageName = imageName.(string)
} else {
if imageName, ok := d.GetOk("name"); ok {
request.ImageName = imageName.(string)
}
}
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.ModifyImageAttribute(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
d.SetPartial("name")
d.SetPartial("image_name")
d.SetPartial("description")
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
d.Partial(false)
return nil
}
func (s *EcsService) DescribeNetworkInterface(id string) (networkInterface ecs.NetworkInterfaceSet, err error) {
request := ecs.CreateDescribeNetworkInterfacesRequest()
request.RegionId = s.client.RegionId
eniIds := []string{id}
request.NetworkInterfaceId = &eniIds
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeNetworkInterfaces(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response := raw.(*ecs.DescribeNetworkInterfacesResponse)
if len(response.NetworkInterfaceSets.NetworkInterfaceSet) < 1 ||
response.NetworkInterfaceSets.NetworkInterfaceSet[0].NetworkInterfaceId != id {
err = WrapErrorf(Error(GetNotFoundMessage("NetworkInterface", id)), NotFoundMsg, ProviderERROR, response.RequestId)
return
}
return response.NetworkInterfaceSets.NetworkInterfaceSet[0], nil
}
func (s *EcsService) DescribeEcsNetworkInterfaceAttachment(id string) (object map[string]interface{}, err error) {
parts, err := ParseResourceId(id, 2)
var response map[string]interface{}
conn, err := s.client.NewEcsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeNetworkInterfaces"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"NetworkInterfaceId": []string{parts[0]},
"InstanceId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidEcsId.NotFound", "InvalidEniId.NotFound", "InvalidSecurityGroupId.NotFound", "InvalidVSwitchId.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS:NetworkInterface", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.NetworkInterfaceSets.NetworkInterfaceSet", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.NetworkInterfaceSets.NetworkInterfaceSet", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["NetworkInterfaceId"].(string) != parts[0] {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
// WaitForInstance waits for instance to given status
func (s *EcsService) WaitForEcsInstance(instanceId string, status Status, timeout int) error {
if timeout <= 0 {
timeout = DefaultTimeout
}
for {
instance, err := s.DescribeInstance(instanceId)
if err != nil && !NotFoundError(err) {
return err
}
if instance.Status == string(status) {
//Sleep one more time for timing issues
time.Sleep(DefaultIntervalMedium * time.Second)
break
}
timeout = timeout - DefaultIntervalShort
if timeout <= 0 {
return GetTimeErrorFromString(GetTimeoutMessage("ECS Instance", string(status)))
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
// WaitForInstance waits for instance to given status
func (s *EcsService) InstanceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeInstance(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.Status == failState {
return object, object.Status, WrapError(Error(FailedToReachTargetStatus, object.Status))
}
}
return object, object.Status, nil
}
}
func (s *EcsService) WaitForDisk(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeDisk(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
// Disk need 3-5 seconds to get ExpiredTime after the status is available
if object.Status == string(status) && object.ExpiredTime != "" {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.Status, string(status), ProviderERROR)
}
}
}
func (s *EcsService) WaitForSecurityGroup(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
_, err := s.DescribeSecurityGroup(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, Null, string(status), ProviderERROR)
}
}
}
func (s *EcsService) WaitForKeyPair(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
_, err := s.DescribeKeyPair(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, Null, string(status), ProviderERROR)
}
}
}
func (s *EcsService) WaitForNetworkInterface(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeNetworkInterface(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.Status == string(status) {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.Status, string(status), ProviderERROR)
}
}
}
func (s *EcsService) QueryPrivateIps(eniId string) ([]string, error) {
if eni, err := s.DescribeNetworkInterface(eniId); err != nil {
return nil, fmt.Errorf("Describe NetworkInterface(%s) failed, %s", eniId, err)
} else {
filterIps := make([]string, 0, len(eni.PrivateIpSets.PrivateIpSet))
for i := range eni.PrivateIpSets.PrivateIpSet {
if eni.PrivateIpSets.PrivateIpSet[i].Primary {
continue
}
filterIps = append(filterIps, eni.PrivateIpSets.PrivateIpSet[i].PrivateIpAddress)
}
return filterIps, nil
}
}
func (s *EcsService) WaitForVpcAttributesChanged(instanceId, vswitchId, privateIp string) error {
deadline := time.Now().Add(DefaultTimeout * time.Second)
for {
if time.Now().After(deadline) {
return WrapError(Error("Wait for VPC attributes changed timeout"))
}
time.Sleep(DefaultIntervalShort * time.Second)
instance, err := s.DescribeInstance(instanceId)
if err != nil {
return WrapError(err)
}
if instance.VpcAttributes.PrivateIpAddress.IpAddress[0] != privateIp {
continue
}
if instance.VpcAttributes.VSwitchId != vswitchId {
continue
}
return nil
}
}
func (s *EcsService) WaitForPrivateIpsCountChanged(eniId string, count int) error {
deadline := time.Now().Add(DefaultTimeout * time.Second)
for {
if time.Now().After(deadline) {
return fmt.Errorf("Wait for private IP addrsses count changed timeout")
}
time.Sleep(DefaultIntervalShort * time.Second)
ips, err := s.QueryPrivateIps(eniId)
if err != nil {
return fmt.Errorf("Query private IP failed, %s", err)
}
if len(ips) == count {
return nil
}
}
}
func (s *EcsService) WaitForPrivateIpsListChanged(eniId string, ipList []string) error {
deadline := time.Now().Add(DefaultTimeout * time.Second)
for {
if time.Now().After(deadline) {
return fmt.Errorf("Wait for private IP addrsses list changed timeout")
}
time.Sleep(DefaultIntervalShort * time.Second)
ips, err := s.QueryPrivateIps(eniId)
if err != nil {
return fmt.Errorf("Query private IP failed, %s", err)
}
if len(ips) != len(ipList) {
continue
}
diff := false
for i := range ips {
exist := false
for j := range ipList {
if ips[i] == ipList[j] {
exist = true
break
}
}
if !exist {
diff = true
break
}
}
if !diff {
return nil
}
}
}
func (s *EcsService) WaitForModifySecurityGroupPolicy(id, target string, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeSecurityGroup(id)
if err != nil {
return WrapError(err)
}
if object.InnerAccessPolicy == target {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.InnerAccessPolicy, target, ProviderERROR)
}
}
}
func (s *EcsService) AttachKeyPair(keyName string, instanceIds []interface{}) error {
request := ecs.CreateAttachKeyPairRequest()
request.RegionId = s.client.RegionId
request.KeyPairName = keyName
request.InstanceIds = convertListToJsonString(instanceIds)
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.AttachKeyPair(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ServiceUnavailable"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, keyName, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return nil
}
func (s *EcsService) SnapshotStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeSnapshot(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.Status == failState {
return object, object.Status, WrapError(Error(FailedToReachTargetStatus, object.Status))
}
}
return object, object.Status, nil
}
}
func (s *EcsService) ImageStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeImageById(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.Status == failState {
return object, object.Status, WrapError(Error(FailedToReachTargetStatus, object.Status))
}
}
return object, object.Status, nil
}
}
func (s *EcsService) TaskStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeTaskById(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.TaskStatus == failState {
return object, object.TaskStatus, WrapError(Error(FailedToReachTargetStatus, object.TaskStatus))
}
}
return object, object.TaskStatus, nil
}
}
func (s *EcsService) DescribeTaskById(id string) (task *ecs.DescribeTaskAttributeResponse, err error) {
request := ecs.CreateDescribeTaskAttributeRequest()
request.TaskId = id
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeTaskAttribute(request)
})
if err != nil {
return task, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
task, _ = raw.(*ecs.DescribeTaskAttributeResponse)
if task.TaskId == "" {
return task, GetNotFoundErrorFromString(GetNotFoundMessage("task", id))
}
return task, nil
}
func (s *EcsService) DescribeSnapshot(id string) (*ecs.Snapshot, error) {
snapshot := &ecs.Snapshot{}
request := ecs.CreateDescribeSnapshotsRequest()
request.RegionId = s.client.RegionId
request.SnapshotIds = fmt.Sprintf("[\"%s\"]", id)
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeSnapshots(request)
})
if err != nil {
return snapshot, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response := raw.(*ecs.DescribeSnapshotsResponse)
if len(response.Snapshots.Snapshot) != 1 || response.Snapshots.Snapshot[0].SnapshotId != id {
return snapshot, WrapErrorf(Error(GetNotFoundMessage("Snapshot", id)), NotFoundMsg, ProviderERROR, response.RequestId)
}
return &response.Snapshots.Snapshot[0], nil
}
func (s *EcsService) DescribeSnapshotPolicy(id string) (*ecs.AutoSnapshotPolicy, error) {
policy := &ecs.AutoSnapshotPolicy{}
request := ecs.CreateDescribeAutoSnapshotPolicyExRequest()
request.AutoSnapshotPolicyId = id
request.RegionId = s.client.RegionId
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeAutoSnapshotPolicyEx(request)
})
if err != nil {
return policy, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response := raw.(*ecs.DescribeAutoSnapshotPolicyExResponse)
if len(response.AutoSnapshotPolicies.AutoSnapshotPolicy) != 1 ||
response.AutoSnapshotPolicies.AutoSnapshotPolicy[0].AutoSnapshotPolicyId != id {
return policy, WrapErrorf(Error(GetNotFoundMessage("SnapshotPolicy", id)), NotFoundMsg, ProviderERROR, response.RequestId)
}
return &response.AutoSnapshotPolicies.AutoSnapshotPolicy[0], nil
}
func (s *EcsService) DescribeReservedInstance(id string) (reservedInstance ecs.ReservedInstance, err error) {
request := ecs.CreateDescribeReservedInstancesRequest()
var balance = &[]string{id}
request.ReservedInstanceId = balance
request.RegionId = s.client.RegionId
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeReservedInstances(request)
})
if err != nil {
return reservedInstance, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ecs.DescribeReservedInstancesResponse)
if len(response.ReservedInstances.ReservedInstance) != 1 ||
response.ReservedInstances.ReservedInstance[0].ReservedInstanceId != id {
return reservedInstance, GetNotFoundErrorFromString(GetNotFoundMessage("PurchaseReservedInstance", id))
}
return response.ReservedInstances.ReservedInstance[0], nil
}
func (s *EcsService) WaitForReservedInstance(id string, status Status, timeout int) error {
deadLine := time.Now().Add(time.Duration(timeout) * time.Second)
for {
reservedInstance, err := s.DescribeReservedInstance(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if reservedInstance.Status == string(status) {
return nil
}
if time.Now().After(deadLine) {
return WrapErrorf(GetTimeErrorFromString("ECS WaitForSnapshotPolicy"), WaitTimeoutMsg, id, GetFunc(1), timeout, reservedInstance.Status, string(status), ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *EcsService) DescribeLaunchTemplate(id string) (set ecs.LaunchTemplateSet, err error) {
request := ecs.CreateDescribeLaunchTemplatesRequest()
request.RegionId = s.client.RegionId
request.LaunchTemplateId = &[]string{id}
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeLaunchTemplates(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response := raw.(*ecs.DescribeLaunchTemplatesResponse)
if len(response.LaunchTemplateSets.LaunchTemplateSet) != 1 ||
response.LaunchTemplateSets.LaunchTemplateSet[0].LaunchTemplateId != id {
err = WrapErrorf(Error(GetNotFoundMessage("LaunchTemplate", id)), NotFoundMsg, ProviderERROR, response.RequestId)
return
}
return response.LaunchTemplateSets.LaunchTemplateSet[0], nil
}
func (s *EcsService) DescribeLaunchTemplateVersion(id string, version int) (set ecs.LaunchTemplateVersionSet, err error) {
request := ecs.CreateDescribeLaunchTemplateVersionsRequest()
request.RegionId = s.client.RegionId
request.LaunchTemplateId = id
request.LaunchTemplateVersion = &[]string{strconv.FormatInt(int64(version), 10)}
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeLaunchTemplateVersions(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidLaunchTemplate.NotFound"}) {
err = WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
return
}
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response := raw.(*ecs.DescribeLaunchTemplateVersionsResponse)
if len(response.LaunchTemplateVersionSets.LaunchTemplateVersionSet) != 1 ||
response.LaunchTemplateVersionSets.LaunchTemplateVersionSet[0].LaunchTemplateId != id {
err = WrapErrorf(Error(GetNotFoundMessage("LaunchTemplateVersion", id)), NotFoundMsg, ProviderERROR, response.RequestId)
return
}
return response.LaunchTemplateVersionSets.LaunchTemplateVersionSet[0], nil
}
func (s *EcsService) WaitForLaunchTemplate(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeLaunchTemplate(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.LaunchTemplateId == id && string(status) != string(Deleted) {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, Null, string(status), ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *EcsService) DescribeImageShareByImageId(id string) (imageShare *ecs.DescribeImageSharePermissionResponse, err error) {
request := ecs.CreateDescribeImageSharePermissionRequest()
request.RegionId = s.client.RegionId
parts, err := ParseResourceId(id, 2)
if err != nil {
return imageShare, WrapError(err)
}
request.ImageId = parts[0]
raw, err := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeImageSharePermission(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidImageId.NotFound"}) {
return imageShare, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return imageShare, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
resp, _ := raw.(*ecs.DescribeImageSharePermissionResponse)
if len(resp.Accounts.Account) == 0 {
return imageShare, WrapErrorf(Error(GetNotFoundMessage("ModifyImageSharePermission", id)), NotFoundMsg, ProviderERROR, resp.RequestId)
}
return resp, nil
}
func (s *EcsService) DescribeAutoProvisioningGroup(id string) (group ecs.AutoProvisioningGroup, err error) {
request := ecs.CreateDescribeAutoProvisioningGroupsRequest()
ids := []string{id}
request.AutoProvisioningGroupId = &ids
request.RegionId = s.client.RegionId
raw, e := s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeAutoProvisioningGroups(request)
})
if e != nil {
err = WrapErrorf(e, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ecs.DescribeAutoProvisioningGroupsResponse)
for _, v := range response.AutoProvisioningGroups.AutoProvisioningGroup {
if v.AutoProvisioningGroupId == id {
return v, nil
}
}
err = WrapErrorf(Error(GetNotFoundMessage("AutoProvisioningGroup", id)), NotFoundMsg, ProviderERROR, response.RequestId)
return
}
func (s *EcsService) ListTagResources(id string, resourceType string) (object interface{}, err error) {
conn, err := s.client.NewEcsClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListTagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": id,
}
tags := make([]interface{}, 0)
var response map[string]interface{}
for {
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{Throttling}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.TagResources.TagResource", response)
if err != nil {
return resource.NonRetryableError(WrapErrorf(err, FailedGetAttributeMsg, id, "$.TagResources.TagResource", response))
}
if v != nil {
tags = append(tags, v.([]interface{})...)
}
return nil
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
if response["NextToken"] == nil {
break
}
request["NextToken"] = response["NextToken"]
}
return tags, nil
}
func (s *EcsService) tagsToMap(tags []ecs.Tag) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !s.ecsTagIgnored(t) {
result[t.TagKey] = t.TagValue
}
}
return result
}
func (s *EcsService) ecsTagIgnored(t ecs.Tag) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, t.TagKey)
ok, _ := regexp.MatchString(v, t.TagKey)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific tag %s (val: %s), ignoring.\n", t.TagKey, t.TagValue)
return true
}
}
return false
}
func (s *EcsService) SetResourceTags(d *schema.ResourceData, resourceType string) error {
if d.HasChange("tags") {
added, removed := parsingTags(d)
conn, err := s.client.NewEcsClient()
if err != nil {
return WrapError(err)
}
removedTagKeys := make([]string, 0)
for _, v := range removed {
if !ignoredTags(v, "") {
removedTagKeys = append(removedTagKeys, v)
}
}
if len(removedTagKeys) > 0 {
action := "UntagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": d.Id(),
}
for i, key := range removedTagKeys {
request[fmt.Sprintf("TagKey.%d", i+1)] = key
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
action := "TagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": d.Id(),
}
count := 1
for key, value := range added {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("tags")
}
return nil
}
func (s *EcsService) DescribeEcsDedicatedHost(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEcsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDedicatedHosts"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DedicatedHostIds": convertListToJsonString([]interface{}{id}),
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDedicatedHostId.NotFound", "InvalidLockReason.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS:DedicatedHost", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.DedicatedHosts.DedicatedHost", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.DedicatedHosts.DedicatedHost", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["DedicatedHostId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *EcsService) EcsDedicatedHostStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeEcsDedicatedHost(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *EcsService) WaitForAutoProvisioningGroup(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeAutoProvisioningGroup(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.AutoProvisioningGroupId, id, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *EcsService) DescribeEcsCommand(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEcsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeCommands"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"CommandId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidRegionId.NotFound", "Operation.Forbidden"}) {
err = WrapErrorf(Error(GetNotFoundMessage("EcsCommand", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Commands.Command", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Commands.Command", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["CommandId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *EcsService) DescribeEcsHpcCluster(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEcsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeHpcClusters"
ids, err := json.Marshal([]string{id})
if err != nil {
return object, err
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"HpcClusterIds": string(ids),
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("DescribeHpcClusters")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"NotExists.HpcCluster"}) {
err = WrapErrorf(Error(GetNotFoundMessage("EcsHpcCluster", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.HpcClusters.HpcCluster", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.HpcClusters.HpcCluster", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["HpcClusterId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *EcsService) DescribeEcsAutoSnapshotPolicy(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEcsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeAutoSnapshotPolicyEx"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"AutoSnapshotPolicyId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.AutoSnapshotPolicies.AutoSnapshotPolicy", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.AutoSnapshotPolicies.AutoSnapshotPolicy", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["AutoSnapshotPolicyId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *EcsService) EcsAutoSnapshotPolicyStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeEcsAutoSnapshotPolicy(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["Status"].(string) == failState {
return object, object["Status"].(string), WrapError(Error(FailedToReachTargetStatus, object["Status"].(string)))
}
}
return object, object["Status"].(string), nil
}
}
func (s *EcsService) DescribeLaunchTemplateVersions(id string) (object []interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEcsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeLaunchTemplateVersions"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"LaunchTemplateId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidLaunchTemplate.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("EcsLaunchTemplate", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.LaunchTemplateVersionSets.LaunchTemplateVersionSet", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.LaunchTemplateVersionSets.LaunchTemplateVersionSet", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["LaunchTemplateId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})
return object, nil
}
func (s *EcsService) SetResourceTemplateTags(d *schema.ResourceData, resourceType string) error {
if d.HasChange("template_tags") {
added, removed := parsingTags(d)
conn, err := s.client.NewEcsClient()
if err != nil {
return WrapError(err)
}
removedTagKeys := make([]string, 0)
for _, v := range removed {
if !ignoredTags(v, "") {
removedTagKeys = append(removedTagKeys, v)
}
}
if len(removedTagKeys) > 0 {
action := "UntagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": d.Id(),
}
for i, key := range removedTagKeys {
request[fmt.Sprintf("TagKey.%d", i+1)] = key
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
action := "TagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": d.Id(),
}
count := 1
for key, value := range added {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("template_tags")
}
return nil
}
func (s *EcsService) DescribeEcsLaunchTemplate(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEcsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeLaunchTemplates"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"LaunchTemplateId": []string{id},
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.LaunchTemplateSets.LaunchTemplateSet", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.LaunchTemplateSets.LaunchTemplateSet", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["LaunchTemplateId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *EcsService) DescribeEcsSnapshot(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEcsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeSnapshots"
ids, err := json.Marshal([]string{id})
if err != nil {
return object, err
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"SnapshotIds": string(ids),
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidFilterKey.NotFound", "InvalidFilterValue", "InvalidSnapshotIds.Malformed,InvalidStatus.NotFound,InvalidSnapshotType.NotFound", "InvalidSnapshotLinkId.NotFound", "InvalidSnapshotType.NotFound", "InvalidSourceDiskType", "InvalidStatus.NotFound", "InvalidUsage"}) {
err = WrapErrorf(Error(GetNotFoundMessage("EcsSnapshot", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Snapshots.Snapshot", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Snapshots.Snapshot", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["SnapshotId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *EcsService) EcsSnapshotStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeEcsSnapshot(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["Status"].(string) == failState {
return object, object["Status"].(string), WrapError(Error(FailedToReachTargetStatus, object["Status"].(string)))
}
}
return object, object["Status"].(string), nil
}
}
func (s *EcsService) DescribeEcsKeyPair(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEcsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeKeyPairs"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"KeyPairName": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidKeyPair.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("EcsKeyPair", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.KeyPairs.KeyPair", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.KeyPairs.KeyPair", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["KeyPairName"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *EcsService) DescribeEcsAutoSnapshotPolicyAttachment(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEcsClient()
if err != nil {
return nil, WrapError(err)
}
parts, err := ParseResourceId(id, 2)
if err != nil {
return object, WrapError(err)
}
action := "DescribeDisks"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DiskIds": convertListToJsonString([]interface{}{parts[1]}),
"autoSnapshotPolicyId": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
v, err := jsonpath.Get("$.Disks.Disk", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Disks.Disk", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *EcsService) DescribeEcsDisk(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEcsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDisks"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DiskIds": convertListToJsonString([]interface{}{id}),
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDiskChargeType.NotFound", "InvalidDiskIds.ValueNotSupported", "InvalidFilterKey.NotFound", "InvalidFilterValue", "InvalidLockReason.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS:Disk", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Disks.Disk", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Disks.Disk", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["DiskId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *EcsService) EcsDiskStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeEcsDisk(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *EcsService) DescribeEcsNetworkInterface(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEcsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeNetworkInterfaces"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"NetworkInterfaceId": []string{id},
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidEcsId.NotFound", "InvalidEniId.NotFound", "InvalidSecurityGroupId.NotFound", "InvalidVSwitchId.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS:NetworkInterface", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.NetworkInterfaceSets.NetworkInterfaceSet", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.NetworkInterfaceSets.NetworkInterfaceSet", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["NetworkInterfaceId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *EcsService) EcsNetworkInterfaceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeEcsNetworkInterface(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *EcsService) DescribeEcsDeploymentSet(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEcsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDeploymentSets"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DeploymentSetIds": convertListToJsonString([]interface{}{id}),
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.DeploymentSets.DeploymentSet", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.DeploymentSets.DeploymentSet", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["DeploymentSetId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *EcsService) DescribeEcsDedicatedHostCluster(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEcsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDedicatedHostClusters"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"PageNumber": 1,
"PageSize": PageSizeLarge,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.DedicatedHostClusters.DedicatedHostCluster", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.DedicatedHostClusters.DedicatedHostCluster", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["DedicatedHostClusterId"]) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS", id)), NotFoundWithResponse, response)
}
return
}
func (s *EcsService) DescribeEcsSessionManagerStatus(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEcsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeUserBusinessBehavior"
request := map[string]interface{}{
"statusKey": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *EcsService) DescribeEcsPrefixList(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEcsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribePrefixListAttributes"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"PrefixListId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidPrefixListId.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("ECS:PrefixList", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"encoding/json"
"reflect"
"strconv"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/aliyun/alibaba-cloud-sdk-go/services/edas"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type EdasService struct {
client *connectivity.AliyunClient
}
type Hook struct {
Exec *Exec `json:"exec,omitempty"`
HttpGet *HttpGet `json:"httpGet,omitempty"`
TcpSocket *TcpSocket `json:"tcpSocket,omitempty"`
}
type Exec struct {
Command []string `json:"command"`
}
type HttpGet struct {
Path string `json:"path"`
Port int `json:"port"`
Scheme string `json:"scheme"`
HttpHeaders []HttpHeader `json:"httpHeaders"`
}
type HttpHeader struct {
Name string `json:"name"`
Value string `json:"value"`
}
type TcpSocket struct {
Host string `json:"host"`
Port int `json:"port"`
}
type Prober struct {
FailureThreshold int `json:"failureThreshold"`
InitialDelaySeconds int `json:"initialDelaySeconds"`
SuccessThreshold int `json:"successThreshold"`
TimeoutSeconds int `json:"timeoutSeconds"`
Hook `json:",inline"`
}
func (e *EdasService) GetChangeOrderStatus(id string) (info *edas.ChangeOrderInfo, err error) {
request := edas.CreateGetChangeOrderInfoRequest()
request.RegionId = e.client.RegionId
request.ChangeOrderId = id
raw, err := e.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.GetChangeOrderInfo(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"OperationDenied.InvalidDBClusterIdNotFound", "OperationDenied.InvalidDBClusterNameNotFound"}) {
return info, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return info, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
rsp := raw.(*edas.GetChangeOrderInfoResponse)
return &rsp.ChangeOrderInfo, nil
}
func (e *EdasService) GetDeployGroup(appId, groupId string) (groupInfo *edas.DeployGroup, err error) {
request := edas.CreateListDeployGroupRequest()
request.RegionId = e.client.RegionId
request.AppId = appId
raw, err := e.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.ListDeployGroup(request)
})
if err != nil {
return groupInfo, WrapErrorf(err, DefaultErrorMsg, appId, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
rsp := raw.(*edas.ListDeployGroupResponse)
if rsp.Code != 200 {
return groupInfo, Error("get deploy group failed for " + rsp.Message)
}
for _, group := range rsp.DeployGroupList.DeployGroup {
if group.GroupId == groupId {
return &group, nil
}
}
return groupInfo, nil
}
func (e *EdasService) EdasChangeOrderStatusRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := e.GetChangeOrderStatus(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if strconv.Itoa(object.Status) == failState {
return object, strconv.Itoa(object.Status), WrapError(Error(FailedToReachTargetStatus, strconv.Itoa(object.Status)))
}
}
return object, strconv.Itoa(object.Status), nil
}
}
func (e *EdasService) SyncResource(resourceType string) error {
request := edas.CreateSynchronizeResourceRequest()
request.RegionId = e.client.RegionId
request.Type = resourceType
raw, err := e.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.SynchronizeResource(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "sync resource", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
rsp := raw.(*edas.SynchronizeResourceResponse)
if rsp.Code != 200 || !rsp.Success {
return WrapError(Error("sync resource failed for " + rsp.Message))
}
return nil
}
func (e *EdasService) CheckEcsStatus(instanceIds string, count int) error {
request := ecs.CreateDescribeInstancesRequest()
request.RegionId = e.client.RegionId
request.Status = "Running"
request.PageSize = requests.NewInteger(100)
request.InstanceIds = instanceIds
raw, err := e.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeInstances(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"OperationDenied.InvalidDBClusterIdNotFound", "OperationDenied.InvalidDBClusterNameNotFound"}) {
return WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return WrapErrorf(err, DefaultErrorMsg, instanceIds, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
rsp := raw.(*ecs.DescribeInstancesResponse)
if len(rsp.Instances.Instance) != count {
return WrapErrorf(Error("not enough instances"), DefaultErrorMsg, instanceIds, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return nil
}
func (e *EdasService) GetLastPackgeVersion(appId, groupId string) (string, error) {
var versionId string
request := edas.CreateQueryApplicationStatusRequest()
request.AppId = appId
raw, err := e.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.QueryApplicationStatus(request)
})
if err != nil {
return "", WrapErrorf(err, DefaultErrorMsg, "alicloud_edas_application_package_version", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*edas.QueryApplicationStatusResponse)
if response.Code != 200 {
return "", WrapError(Error("QueryApplicationStatus failed for " + response.Message))
}
for _, group := range response.AppInfo.GroupList.Group {
if group.GroupId == groupId {
versionId = group.PackageVersionId
}
}
rq := edas.CreateListHistoryDeployVersionRequest()
rq.AppId = appId
raw, err = e.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.ListHistoryDeployVersion(rq)
})
if err != nil {
return "", WrapErrorf(err, DefaultErrorMsg, "alicloud_edas_application_package_version_list", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
rsp, _ := raw.(*edas.ListHistoryDeployVersionResponse)
if rsp.Code != 200 {
return "", WrapError(Error("QueryApplicationStatus failed for " + response.Message))
}
for _, version := range rsp.PackageVersionList.PackageVersion {
if version.Id == versionId {
return version.PackageVersion, nil
}
}
return "", nil
}
func (e *EdasService) DescribeEdasApplication(appId string) (*edas.Applcation, error) {
application := &edas.Applcation{}
regionId := e.client.RegionId
request := edas.CreateGetApplicationRequest()
request.RegionId = regionId
request.AppId = appId
raw, err := e.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.GetApplication(request)
})
if err != nil {
return application, WrapError(err)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*edas.GetApplicationResponse)
if response.Code != 200 {
return application, WrapError(Error("get application error :" + response.Message))
}
v := response.Applcation
return &v, nil
}
func (e *EdasService) DescribeEdasCluster(clusterId string) (*edas.Cluster, error) {
cluster := &edas.Cluster{}
regionId := e.client.RegionId
request := edas.CreateGetClusterRequest()
request.RegionId = regionId
request.ClusterId = clusterId
raw, err := e.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.GetCluster(request)
})
if err != nil {
return cluster, WrapErrorf(err, DefaultErrorMsg, "alicloud_edas_cluster", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*edas.GetClusterResponse)
if response.Code != 200 {
return cluster, WrapError(Error("create cluster failed for " + response.Message))
}
v := response.Cluster
return &v, nil
}
func (e *EdasService) DescribeEdasDeployGroup(id string) (*edas.DeployGroup, error) {
group := &edas.DeployGroup{}
regionId := e.client.RegionId
strs := strings.Split(id, ":")
request := edas.CreateListDeployGroupRequest()
request.RegionId = regionId
request.AppId = strs[0]
raw, err := e.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.ListDeployGroup(request)
})
if err != nil {
return group, WrapErrorf(err, DefaultErrorMsg, "alicloud_edas_deploy_group", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*edas.ListDeployGroupResponse)
if response.Code != 200 {
return group, WrapError(Error("create cluster failed for " + response.Message))
}
for _, v := range response.DeployGroupList.DeployGroup {
if v.ClusterName == strs[1] {
return &v, nil
}
}
return group, nil
}
func (e *EdasService) DescribeEdasInstanceClusterAttachment(id string) (*edas.Cluster, error) {
cluster := &edas.Cluster{}
v := strings.Split(id, ":")
o, err := e.DescribeEdasCluster(v[0])
if err != nil {
return cluster, WrapError(err)
}
return o, nil
}
func (e *EdasService) DescribeEdasApplicationDeployment(id string) (*edas.Applcation, error) {
application := &edas.Applcation{}
v := strings.Split(id, ":")
o, err := e.DescribeEdasApplication(v[0])
if err != nil {
return application, WrapError(err)
}
return o, nil
}
func (e *EdasService) DescribeEdasApplicationScale(id string) (*edas.Applcation, error) {
application := &edas.Applcation{}
v := strings.Split(id, ":")
o, err := e.DescribeEdasApplication(v[0])
if err != nil {
return application, WrapError(err)
}
return o, nil
}
func (e *EdasService) DescribeEdasSlbAttachment(id string) (*edas.Applcation, error) {
application := &edas.Applcation{}
v := strings.Split(id, ":")
o, err := e.DescribeEdasApplication(v[0])
if err != nil {
return application, WrapError(err)
}
return o, nil
}
type CommandArg struct {
Argument string `json:"argument" xml:"argument"`
}
func (e *EdasService) GetK8sCommandArgs(args []interface{}) (string, error) {
aString := make([]CommandArg, 0)
for _, v := range args {
aString = append(aString, CommandArg{Argument: v.(string)})
}
b, err := json.Marshal(aString)
if err != nil {
return "", WrapError(err)
}
return string(b), nil
}
func (e *EdasService) GetK8sCommandArgsForDeploy(args []interface{}) (string, error) {
b, err := json.Marshal(args)
if err != nil {
return "", WrapError(err)
}
return string(b), nil
}
type K8sEnv struct {
Name string `json:"name" xml:"name"`
Value string `json:"value" xml:"value"`
}
func (e *EdasService) GetK8sEnvs(envs map[string]interface{}) (string, error) {
k8sEnvs := make([]K8sEnv, 0)
for n, v := range envs {
k8sEnvs = append(k8sEnvs, K8sEnv{Name: n, Value: v.(string)})
}
b, err := json.Marshal(k8sEnvs)
if err != nil {
return "", WrapError(err)
}
return string(b), nil
}
func (e *EdasService) QueryK8sAppPackageType(appId string) (string, error) {
request := edas.CreateGetApplicationRequest()
request.RegionId = e.client.RegionId
request.AppId = appId
raw, err := e.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.GetApplication(request)
})
if err != nil {
return "", WrapError(err)
}
response, _ := raw.(*edas.GetApplicationResponse)
if response.Code != 200 {
return "", WrapError(Error("get application for appId:" + appId + " failed:" + response.Message))
}
if len(response.Applcation.ApplicationType) > 0 {
return response.Applcation.ApplicationType, nil
}
return "", WrapError(Error("not package type for appId:" + appId))
}
func (e *EdasService) DescribeEdasK8sCluster(clusterId string) (*edas.Cluster, error) {
cluster := &edas.Cluster{}
regionId := e.client.RegionId
request := edas.CreateGetClusterRequest()
request.RegionId = regionId
request.ClusterId = clusterId
raw, err := e.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.GetCluster(request)
})
if err != nil {
return cluster, WrapErrorf(err, DefaultErrorMsg, clusterId, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*edas.GetClusterResponse)
if response.Code != 200 {
if strings.Contains(response.Message, "does not exist") {
return cluster, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return cluster, WrapError(Error("create k8s cluster failed for " + response.Message))
}
v := response.Cluster
return &v, nil
}
func (e *EdasService) DescribeEdasK8sApplication(appId string) (*edas.Applcation, error) {
application := &edas.Applcation{}
regionId := e.client.RegionId
request := edas.CreateGetK8sApplicationRequest()
request.RegionId = regionId
request.AppId = appId
raw, err := e.client.WithEdasClient(func(edasClient *edas.Client) (interface{}, error) {
return edasClient.GetK8sApplication(request)
})
if err != nil {
return application, WrapError(err)
}
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
response, _ := raw.(*edas.GetK8sApplicationResponse)
if response.Code != 200 {
if strings.Contains(response.Message, "does not exist") {
return application, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return application, WrapError(Error("get k8s application error :" + response.Message))
}
v := response.Applcation
return &v, nil
}
func (e *EdasService) PreStopEqual(old, new interface{}) bool {
oldStr := old.(string)
newStr := new.(string)
var oldHook Hook
err := json.Unmarshal([]byte(oldStr), &oldHook)
if err != nil {
return false
}
var newHook Hook
err = json.Unmarshal([]byte(newStr), &newHook)
if err != nil {
return false
}
return reflect.DeepEqual(oldHook, newHook)
}
func (e *EdasService) PostStartEqual(old, new interface{}) bool {
oldStr := old.(string)
newStr := new.(string)
var oldHook Hook
err := json.Unmarshal([]byte(oldStr), &oldHook)
if err != nil {
return false
}
var newHook Hook
err = json.Unmarshal([]byte(newStr), &newHook)
if err != nil {
return false
}
return reflect.DeepEqual(oldHook, newHook)
}
func (e *EdasService) LivenessEqual(old, new interface{}) bool {
oldStr := old.(string)
newStr := new.(string)
var oldProber Prober
err := json.Unmarshal([]byte(oldStr), &oldProber)
if err != nil {
return false
}
var newProber Prober
err = json.Unmarshal([]byte(newStr), &newProber)
if err != nil {
return false
}
return reflect.DeepEqual(oldProber, newProber)
}
func (e *EdasService) ReadinessEqual(old, new interface{}) bool {
oldStr := old.(string)
newStr := new.(string)
var oldProber Prober
err := json.Unmarshal([]byte(oldStr), &oldProber)
if err != nil {
return false
}
var newProber Prober
err = json.Unmarshal([]byte(newStr), &newProber)
if err != nil {
return false
}
return reflect.DeepEqual(oldProber, newProber)
}
package alicloud
import (
"fmt"
"strconv"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type EdsUserService struct {
client *connectivity.AliyunClient
}
func (s *EdsUserService) DescribeEcdUser(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEdsuserClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeUsers"
request := map[string]interface{}{
"MaxResults": PageSizeLarge,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-03-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"Forbidden"}) {
conn.Endpoint = String(connectivity.EcdOpenAPIEndpointUser)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Users", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Users", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ECD", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["EndUserId"]) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("ECD", id)), NotFoundWithResponse, response)
}
return
}
func (s *EdsUserService) EcdUserStateRefreshFunc(id string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeEcdUser(id)
status := convertEcdUserStatusResponse(strconv.Itoa(formatInt(object["Status"])))
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
return object, status, nil
}
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type EhpcService struct {
client *connectivity.AliyunClient
}
func (s *EhpcService) DescribeEhpcJobTemplate(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEhpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListJobTemplates"
request := map[string]interface{}{
"PageSize": PageSizeLarge,
"PageNumber": 1,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2018-04-12"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Templates.JobTemplates", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Templates.JobTemplates", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("Ehpc", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["Id"]) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("Ehpc", id)), NotFoundWithResponse, response)
}
return
}
package alicloud
import (
"fmt"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type EipanycastService struct {
client *connectivity.AliyunClient
}
func (s *EipanycastService) DescribeEipanycastAnycastEipAddress(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEipanycastClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeAnycastEipAddress"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"AnycastId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *EipanycastService) EipanycastAnycastEipAddressStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeEipanycastAnycastEipAddress(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["Status"].(string) == failState {
return object, object["Status"].(string), WrapError(Error(FailedToReachTargetStatus, object["Status"].(string)))
}
}
return object, object["Status"].(string), nil
}
}
func (s *EipanycastService) DescribeEipanycastAnycastEipAddressAttachment(id string) (object map[string]interface{}, err error) {
parts, err := ParseResourceId(id, 4)
if err != nil {
return nil, WrapError(err)
}
var response map[string]interface{}
conn, err := s.client.NewEipanycastClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeAnycastEipAddress"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"AnycastId": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
if len(v.(map[string]interface{})["AnycastEipBindInfoList"].([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("EipanycastAnycastEipAddressAttachment", id)), NotFoundWithResponse, response)
} else {
if vv, ok := v.(map[string]interface{})["AnycastEipBindInfoList"].([]interface{})[0].(map[string]interface{}); ok {
if parts[1]+parts[2]+parts[3] != fmt.Sprint(vv["BindInstanceId"], vv["BindInstanceRegionId"], vv["BindInstanceType"]) {
return object, WrapErrorf(Error(GetNotFoundMessage("EipanycastAnycastEipAddressAttachment", id)), NotFoundWithResponse, response)
}
}
}
object = v.(map[string]interface{})
return object, nil
}
func (s *EipanycastService) EipanycastAnycastEipAddressAttachmentStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeEipanycastAnycastEipAddressAttachment(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["Status"].(string) == failState {
return object, object["Status"].(string), WrapError(Error(FailedToReachTargetStatus, object["Status"].(string)))
}
}
return object, object["Status"].(string), nil
}
}
package alicloud
import (
"encoding/json"
"fmt"
"strings"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/aliyun/alibaba-cloud-sdk-go/services/elasticsearch"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type ElasticsearchService struct {
client *connectivity.AliyunClient
}
func (s *ElasticsearchService) DescribeElasticsearchInstance(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewElasticsearchClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeInstance"
response, err = conn.DoRequestWithAction(StringPointer(action), StringPointer("2017-06-13"), nil, StringPointer("GET"), StringPointer("AK"),
String(fmt.Sprintf("/openapi/instances/%s", id)), nil, nil, nil, &util.RuntimeOptions{})
addDebug(action, response, nil)
if err != nil {
if IsExpectedErrors(err, []string{"InstanceNotFound"}) {
return object, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.body.Result", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.body.Result", response)
}
object = v.(map[string]interface{})
if (object["instanceId"].(string)) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("Elasticsearch Instance", id)), NotFoundWithResponse, response)
}
return object, WrapError(err)
}
func (s *ElasticsearchService) ElasticsearchStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeElasticsearchInstance(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["status"].(string) == failState {
return object, object["status"].(string), WrapError(Error(FailedToReachTargetStatus, object["status"].(string)))
}
}
return object, object["status"].(string), nil
}
}
func (s *ElasticsearchService) ElasticsearchRetryFunc(wait func(), errorCodeList []string, do func(*elasticsearch.Client) (interface{}, error)) (interface{}, error) {
var raw interface{}
var err error
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithElasticsearchClient(do)
if err != nil {
if IsExpectedErrors(err, errorCodeList) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
return raw, WrapError(err)
}
func (s *ElasticsearchService) TriggerNetwork(d *schema.ResourceData, content map[string]interface{}, meta interface{}) error {
var response map[string]interface{}
conn, err := s.client.NewElasticsearchClient()
if err != nil {
return WrapError(err)
}
action := "TriggerNetwork"
requestQuery := map[string]*string{
"clientToken": StringPointer(buildClientToken(action)),
}
// retry
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequestWithAction(StringPointer(action), StringPointer("2017-06-13"), nil, StringPointer("POST"), StringPointer("AK"),
String(fmt.Sprintf("/openapi/instances/%s/actions/network-trigger", d.Id())), requestQuery, nil, content, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ConcurrencyUpdateInstanceConflict", "InstanceStatusNotSupportCurrentAction", "InternalServerError"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, content)
return nil
})
addDebug(action, response, content)
if err != nil {
if IsExpectedErrors(err, []string{"RepetitionOperationError"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"activating"}, []string{"active"}, d.Timeout(schema.TimeoutUpdate), 5*time.Minute, s.ElasticsearchStateRefreshFunc(d.Id(), []string{"inactive"}))
stateConf.PollInterval = 5 * time.Second
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
func (s *ElasticsearchService) ModifyWhiteIps(d *schema.ResourceData, content map[string]interface{}, meta interface{}) error {
var response map[string]interface{}
conn, err := s.client.NewElasticsearchClient()
if err != nil {
return WrapError(err)
}
action := "ModifyWhiteIps"
requestQuery := map[string]*string{
"clientToken": StringPointer(buildClientToken(action)),
}
// retry
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequestWithAction(StringPointer(action), StringPointer("2017-06-13"), nil, StringPointer("POST"), StringPointer("AK"),
String(fmt.Sprintf("/openapi/instances/%s/actions/modify-white-ips", d.Id())), requestQuery, nil, content, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ConcurrencyUpdateInstanceConflict", "InstanceStatusNotSupportCurrentAction", "InternalServerError"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
addDebug(action, response, nil)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"activating"}, []string{"active"}, d.Timeout(schema.TimeoutUpdate), 5*time.Minute, s.ElasticsearchStateRefreshFunc(d.Id(), []string{"inactive"}))
stateConf.PollInterval = 5 * time.Second
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
func (s *ElasticsearchService) DescribeElasticsearchTags(id string) (tags map[string]string, err error) {
resourceIds, err := json.Marshal([]string{id})
if err != nil {
tmp := make(map[string]string)
return tmp, WrapError(err)
}
request := elasticsearch.CreateListTagResourcesRequest()
request.RegionId = s.client.RegionId
request.ResourceIds = string(resourceIds)
request.ResourceType = strings.ToUpper(string(TagResourceInstance))
raw, err := s.client.WithElasticsearchClient(func(elasticsearchClient *elasticsearch.Client) (interface{}, error) {
return elasticsearchClient.ListTagResources(request)
})
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
if err != nil {
tmp := make(map[string]string)
return tmp, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*elasticsearch.ListTagResourcesResponse)
return s.tagsToMap(response.TagResources.TagResource), nil
}
func (s *ElasticsearchService) tagsToMap(tagSet []elasticsearch.TagResourceItem) (tags map[string]string) {
result := make(map[string]string)
for _, t := range tagSet {
if !elasticsearchTagIgnored(t.TagKey, t.TagValue) {
result[t.TagKey] = t.TagValue
}
}
return result
}
func (s *ElasticsearchService) diffElasticsearchTags(oldTags, newTags map[string]interface{}) (remove []string, add []map[string]string) {
for k, _ := range oldTags {
remove = append(remove, k)
}
for k, v := range newTags {
tag := map[string]string{
"key": k,
"value": v.(string),
}
add = append(add, tag)
}
return
}
func (s *ElasticsearchService) getActionType(actionType bool) string {
if actionType == true {
return string(OPEN)
} else {
return string(CLOSE)
}
}
func updateDescription(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
action := "UpdateDescription"
content := make(map[string]interface{})
content["description"] = d.Get("description").(string)
requestQuery := map[string]*string{
"clientToken": StringPointer(buildClientToken(action)),
}
elasticsearchClient, err := client.NewElasticsearchClient()
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := elasticsearchClient.DoRequestWithAction(StringPointer(action), StringPointer("2017-06-13"), nil, StringPointer("POST"), StringPointer("AK"),
String(fmt.Sprintf("/openapi/instances/%s/description", d.Id())), requestQuery, nil, content, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"GetCustomerLabelFail"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return nil
}
func updateInstanceTags(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
elasticsearchService := ElasticsearchService{client}
oraw, nraw := d.GetChange("tags")
o := oraw.(map[string]interface{})
n := nraw.(map[string]interface{})
remove, add := elasticsearchService.diffElasticsearchTags(o, n)
// 对系统 Tag 进行过滤
removeTagKeys := make([]string, 0)
for _, v := range remove {
if !elasticsearchTagIgnored(v, "") {
removeTagKeys = append(removeTagKeys, v)
}
}
if len(removeTagKeys) > 0 {
tagKeys, err := json.Marshal(removeTagKeys)
if err != nil {
return WrapError(err)
}
resourceIds, err := json.Marshal([]string{d.Id()})
if err != nil {
return WrapError(err)
}
request := elasticsearch.CreateUntagResourcesRequest()
request.RegionId = client.RegionId
request.TagKeys = string(tagKeys)
request.ResourceType = strings.ToUpper(string(TagResourceInstance))
request.ResourceIds = string(resourceIds)
request.SetContentType("application/json")
raw, err := client.WithElasticsearchClient(func(elasticsearchClient *elasticsearch.Client) (interface{}, error) {
return elasticsearchClient.UntagResources(request)
})
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
if len(add) > 0 {
content := make(map[string]interface{})
content["ResourceIds"] = []string{d.Id()}
content["ResourceType"] = strings.ToUpper(string(TagResourceInstance))
content["Tags"] = add
data, err := json.Marshal(content)
if err != nil {
return WrapError(err)
}
request := elasticsearch.CreateTagResourcesRequest()
request.RegionId = client.RegionId
request.SetContent(data)
request.SetContentType("application/json")
raw, err := client.WithElasticsearchClient(func(elasticsearchClient *elasticsearch.Client) (interface{}, error) {
return elasticsearchClient.TagResources(request)
})
addDebug(request.GetActionName(), raw, request.RoaRequest, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
return nil
}
func updateInstanceChargeType(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
elasticsearchClient, err := client.NewElasticsearchClient()
action := "UpdateInstanceChargeType"
content := make(map[string]interface{})
content["paymentType"] = strings.ToLower(d.Get("instance_charge_type").(string))
if d.Get("instance_charge_type").(string) == string(PrePaid) {
paymentInfo := make(map[string]interface{})
if d.Get("period").(int) >= 12 {
paymentInfo["duration"] = d.Get("period").(int) / 12
paymentInfo["pricingCycle"] = string(Year)
} else {
paymentInfo["duration"] = d.Get("period").(int)
paymentInfo["pricingCycle"] = string(Month)
}
content["paymentInfo"] = paymentInfo
}
requestQuery := map[string]*string{
"clientToken": StringPointer(buildClientToken(action)),
}
response, err := elasticsearchClient.DoRequestWithAction(StringPointer(action), StringPointer("2017-06-13"), nil, StringPointer("POST"), StringPointer("AK"),
String(fmt.Sprintf("/openapi/instances/%s/actions/convert-pay-type", d.Id())), requestQuery, nil, content, &util.RuntimeOptions{})
time.Sleep(10 * time.Second)
addDebug(action, response, content)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), response, AlibabaCloudSdkGoERROR)
}
return nil
}
func renewInstance(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
elasticsearchClient, err := client.NewElasticsearchClient()
action := "RenewInstance"
content := make(map[string]interface{})
if d.Get("period").(int) >= 12 {
content["duration"] = d.Get("period").(int) / 12
content["pricingCycle"] = string(Year)
} else {
content["duration"] = d.Get("period").(int)
content["pricingCycle"] = string(Month)
}
requestQuery := map[string]*string{
"clientToken": StringPointer(buildClientToken(action)),
}
response, err := elasticsearchClient.DoRequestWithAction(StringPointer(action), StringPointer("2017-06-13"), nil, StringPointer("POST"), StringPointer("AK"),
String(fmt.Sprintf("/openapi/instances/%s/actions/renew", d.Id())), requestQuery, nil, content, &util.RuntimeOptions{})
time.Sleep(10 * time.Second)
addDebug(action, response, content)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), response, AlibabaCloudSdkGoERROR)
}
return nil
}
func updateDataNodeAmount(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
elasticsearchService := ElasticsearchService{client}
conn, err := client.NewElasticsearchClient()
if err != nil {
return WrapError(err)
}
action := "UpdateInstance"
var response map[string]interface{}
requestQuery := map[string]*string{
"clientToken": StringPointer(buildClientToken(action)),
}
content := make(map[string]interface{})
content["nodeAmount"] = d.Get("data_node_amount").(int)
// retry
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequestWithAction(StringPointer(action), StringPointer("2017-06-13"), nil, StringPointer("PUT"), StringPointer("AK"),
String(fmt.Sprintf("/openapi/instances/%s", d.Id())), requestQuery, nil, content, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ConcurrencyUpdateInstanceConflict", "InstanceStatusNotSupportCurrentAction"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, content)
return nil
})
addDebug(action, response, content)
if err != nil && !IsExpectedErrors(err, []string{"MustChangeOneResource", "CssCheckUpdowngradeError"}) {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"activating"}, []string{"active"}, d.Timeout(schema.TimeoutUpdate), 5*time.Minute, elasticsearchService.ElasticsearchStateRefreshFunc(d.Id(), []string{"inactive"}))
stateConf.PollInterval = 5 * time.Second
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
func updateDataNodeSpec(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
elasticsearchService := ElasticsearchService{client}
conn, err := client.NewElasticsearchClient()
if err != nil {
return WrapError(err)
}
action := "UpdateInstance"
var response map[string]interface{}
content := make(map[string]interface{})
spec := make(map[string]interface{})
spec["spec"] = d.Get("data_node_spec")
spec["disk"] = d.Get("data_node_disk_size")
spec["diskType"] = d.Get("data_node_disk_type")
content["nodeSpec"] = spec
requestQuery := map[string]*string{
"clientToken": StringPointer(buildClientToken(action)),
}
// retry
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequestWithAction(StringPointer(action), StringPointer("2017-06-13"), nil, StringPointer("PUT"), StringPointer("AK"),
String(fmt.Sprintf("/openapi/instances/%s", d.Id())), requestQuery, nil, content, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ConcurrencyUpdateInstanceConflict", "InstanceStatusNotSupportCurrentAction"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, content)
return nil
})
addDebug(action, response, content)
if err != nil && !IsExpectedErrors(err, []string{"MustChangeOneResource", "CssCheckUpdowngradeError"}) {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"activating"}, []string{"active"}, d.Timeout(schema.TimeoutUpdate), 5*time.Minute, elasticsearchService.ElasticsearchStateRefreshFunc(d.Id(), []string{"inactive"}))
stateConf.PollInterval = 5 * time.Second
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
func updateMasterNode(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
elasticsearchService := ElasticsearchService{client}
conn, err := client.NewElasticsearchClient()
if err != nil {
return WrapError(err)
}
action := "UpdateInstance"
var response map[string]interface{}
content := make(map[string]interface{})
if d.Get("master_node_spec") != nil {
master := make(map[string]interface{})
master["spec"] = d.Get("master_node_spec").(string)
master["amount"] = "3"
master["diskType"] = "cloud_ssd"
master["disk"] = "20"
content["masterConfiguration"] = master
content["advancedDedicateMaster"] = true
} else {
content["advancedDedicateMaster"] = false
}
requestQuery := map[string]*string{
"clientToken": StringPointer(buildClientToken(action)),
}
// retry
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequestWithAction(StringPointer(action), StringPointer("2017-06-13"), nil, StringPointer("PUT"), StringPointer("AK"),
String(fmt.Sprintf("/openapi/instances/%s", d.Id())), requestQuery, nil, content, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ConcurrencyUpdateInstanceConflict", "InstanceStatusNotSupportCurrentAction"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, content)
return nil
})
if err != nil && !IsExpectedErrors(err, []string{"MustChangeOneResource", "CssCheckUpdowngradeError"}) {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, content)
stateConf := BuildStateConf([]string{"activating"}, []string{"active"}, d.Timeout(schema.TimeoutUpdate), 5*time.Minute, elasticsearchService.ElasticsearchStateRefreshFunc(d.Id(), []string{"inactive"}))
stateConf.PollInterval = 5 * time.Second
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
func updatePassword(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
elasticsearchService := ElasticsearchService{client}
conn, err := client.NewElasticsearchClient()
if err != nil {
return WrapError(err)
}
action := "UpdateAdminPassword"
var response map[string]interface{}
content := make(map[string]interface{})
password := d.Get("password").(string)
kmsPassword := d.Get("kms_encrypted_password").(string)
if password == "" && kmsPassword == "" {
return WrapError(Error("One of the 'password' and 'kms_encrypted_password' should be set."))
}
if password != "" {
d.SetPartial("password")
content["esAdminPassword"] = password
} else {
kmsService := KmsService{meta.(*connectivity.AliyunClient)}
decryptResp, err := kmsService.Decrypt(kmsPassword, d.Get("kms_encryption_context").(map[string]interface{}))
if err != nil {
return WrapError(err)
}
content["esAdminPassword"] = decryptResp
d.SetPartial("kms_encrypted_password")
d.SetPartial("kms_encryption_context")
}
requestQuery := map[string]*string{
"clientToken": StringPointer(buildClientToken(action)),
}
// retry
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequestWithAction(StringPointer(action), StringPointer("2017-06-13"), nil, StringPointer("POST"), StringPointer("AK"),
String(fmt.Sprintf("/openapi/instances/%s/admin-pwd", d.Id())), requestQuery, nil, content, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ConcurrencyUpdateInstanceConflict", "InstanceStatusNotSupportCurrentAction"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, content)
return nil
})
addDebug(action, response, content)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"activating"}, []string{"active"}, d.Timeout(schema.TimeoutUpdate), 5*time.Minute, elasticsearchService.ElasticsearchStateRefreshFunc(d.Id(), []string{"inactive"}))
stateConf.PollInterval = 5 * time.Second
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
func getChargeType(paymentType string) string {
if strings.ToLower(paymentType) == strings.ToLower(string(PostPaid)) {
return string(PostPaid)
} else {
return string(PrePaid)
}
}
func filterWhitelist(destIPs []string, localIPs *schema.Set) []string {
var whitelist []string
if destIPs != nil {
for _, ip := range destIPs {
if (ip == "::1" || ip == "::/0" || ip == "127.0.0.1" || ip == "0.0.0.0/0") && !localIPs.Contains(ip) {
continue
}
whitelist = append(whitelist, ip)
}
}
return whitelist
}
func updateClientNode(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
elasticsearchService := ElasticsearchService{client}
conn, err := client.NewElasticsearchClient()
if err != nil {
return WrapError(err)
}
action := "UpdateInstance"
var response map[string]interface{}
content := make(map[string]interface{})
content["isHaveClientNode"] = true
spec := make(map[string]interface{})
spec["spec"] = d.Get("client_node_spec")
if d.Get("client_node_amount") == nil {
spec["amount"] = "2"
} else {
spec["amount"] = d.Get("client_node_amount")
}
spec["disk"] = "20"
spec["diskType"] = "cloud_efficiency"
content["clientNodeConfiguration"] = spec
requestQuery := map[string]*string{
"clientToken": StringPointer(buildClientToken(action)),
}
// retry
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequestWithAction(StringPointer(action), StringPointer("2017-06-13"), nil, StringPointer("PUT"), StringPointer("AK"),
String(fmt.Sprintf("/openapi/instances/%s", d.Id())), requestQuery, nil, content, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ConcurrencyUpdateInstanceConflict", "InstanceStatusNotSupportCurrentAction"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, content)
return nil
})
addDebug(action, response, content)
if err != nil && !IsExpectedErrors(err, []string{"MustChangeOneResource", "CssCheckUpdowngradeError"}) {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"activating"}, []string{"active"}, d.Timeout(schema.TimeoutUpdate), 5*time.Minute, elasticsearchService.ElasticsearchStateRefreshFunc(d.Id(), []string{"inactive"}))
stateConf.PollInterval = 5 * time.Second
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
func openHttps(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
elasticsearchService := ElasticsearchService{client}
conn, err := client.NewElasticsearchClient()
if err != nil {
return WrapError(err)
}
action := "OpenHttps"
var response map[string]interface{}
requestQuery := map[string]*string{
"clientToken": StringPointer(buildClientToken(action)),
}
// retry
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequestWithAction(StringPointer(action), StringPointer("2017-06-13"), nil, StringPointer("POST"), StringPointer("AK"),
String(fmt.Sprintf("/openapi/instances/%s/actions/open-https", d.Id())), requestQuery, nil, nil, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ConcurrencyUpdateInstanceConflict", "InstanceStatusNotSupportCurrentAction"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
addDebug(action, response, nil)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"activating"}, []string{"active"}, d.Timeout(schema.TimeoutUpdate), 5*time.Minute, elasticsearchService.ElasticsearchStateRefreshFunc(d.Id(), []string{"inactive"}))
stateConf.PollInterval = 5 * time.Second
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
func closeHttps(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
elasticsearchService := ElasticsearchService{client}
conn, err := client.NewElasticsearchClient()
if err != nil {
return WrapError(err)
}
action := "CloseHttps"
var response map[string]interface{}
requestQuery := map[string]*string{
"clientToken": StringPointer(buildClientToken(action)),
}
// retry
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequestWithAction(StringPointer(action), StringPointer("2017-06-13"), nil, StringPointer("POST"), StringPointer("AK"),
String(fmt.Sprintf("/openapi/instances/%s/actions/close-https", d.Id())), requestQuery, nil, nil, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"ConcurrencyUpdateInstanceConflict", "InstanceStatusNotSupportCurrentAction"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, nil)
return nil
})
addDebug(action, response, nil)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{"activating"}, []string{"active"}, d.Timeout(schema.TimeoutUpdate), 5*time.Minute, elasticsearchService.ElasticsearchStateRefreshFunc(d.Id(), []string{"inactive"}))
stateConf.PollInterval = 5 * time.Second
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/aliyun/alibaba-cloud-sdk-go/services/emr"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
)
type EmrService struct {
client *connectivity.AliyunClient
}
func (s *EmrService) DescribeEmrCluster(id string) (*emr.DescribeClusterV2Response, error) {
response := &emr.DescribeClusterV2Response{}
request := emr.CreateDescribeClusterV2Request()
request.Id = id
raw, err := s.client.WithEmrClient(func(emrClient *emr.Client) (interface{}, error) {
return emrClient.DescribeClusterV2(request)
})
if err != nil {
return response, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest)
response, _ = raw.(*emr.DescribeClusterV2Response)
if response.ClusterInfo.Status == "RELEASED" {
return response, WrapErrorf(Error(GetNotFoundMessage("EmrCluster", id)), NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, nil
}
func (s *EmrService) DataSourceDescribeEmrCluster(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEmrClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeClusterV2"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"Id": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.ClusterInfo", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ClusterInfo", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *EmrService) WaitForEmrCluster(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeEmrCluster(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.ClusterInfo.Id == id && status != Deleted {
break
}
time.Sleep(DefaultIntervalShort * time.Second)
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.ClusterInfo.Id, id, ProviderERROR)
}
}
return nil
}
func (s *EmrService) EmrClusterStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeEmrCluster(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.ClusterInfo.Status == failState {
return object, object.ClusterInfo.Status, WrapError(Error(FailedToReachTargetStatus, object.ClusterInfo.Status))
}
}
return object, object.ClusterInfo.Status, nil
}
}
func (s *EmrService) setEmrClusterTags(d *schema.ResourceData) error {
if d.HasChange("tags") {
oraw, nraw := d.GetChange("tags")
o := oraw.(map[string]interface{})
n := nraw.(map[string]interface{})
create, remove := s.diffTags(s.tagsFromMap(o), s.tagsFromMap(n))
if len(remove) > 0 {
var tagKey []string
for _, v := range remove {
tagKey = append(tagKey, v.Key)
}
request := emr.CreateUntagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.ResourceType = string(TagResourceCluster)
request.TagKey = &tagKey
request.RegionId = s.client.RegionId
raw, err := s.client.WithEmrClient(func(client *emr.Client) (interface{}, error) {
return client.UntagResources(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
if len(create) > 0 {
request := emr.CreateTagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.Tag = &create
request.ResourceType = string(TagResourceCluster)
request.RegionId = s.client.RegionId
raw, err := s.client.WithEmrClient(func(client *emr.Client) (interface{}, error) {
return client.TagResources(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
d.SetPartial("tags")
}
return nil
}
func (s *EmrService) DescribeEmrClusterTags(resourceId string, resourceType TagResourceType) (tags []emr.TagResource, err error) {
request := emr.CreateListTagResourcesRequest()
request.RegionId = s.client.RegionId
request.ResourceType = string(resourceType)
request.ResourceId = &[]string{resourceId}
raw, err := s.client.WithEmrClient(func(client *emr.Client) (interface{}, error) {
return client.ListTagResources(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, resourceId, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*emr.ListTagResourcesResponse)
tags = response.TagResources.TagResource
return
}
func (s *EmrService) diffTags(oldTags, newTags []emr.TagResourcesTag) ([]emr.TagResourcesTag, []emr.TagResourcesTag) {
// First, we're creating everything we have
create := make(map[string]interface{})
for _, t := range newTags {
create[t.Key] = t.Value
}
// Build the list of what to remove
var remove []emr.TagResourcesTag
for _, t := range oldTags {
old, ok := create[t.Key]
if !ok || old != t.Value {
// Delete it!
remove = append(remove, t)
}
}
return s.tagsFromMap(create), remove
}
func (s *EmrService) tagsFromMap(m map[string]interface{}) []emr.TagResourcesTag {
result := make([]emr.TagResourcesTag, 0, len(m))
for k, v := range m {
result = append(result, emr.TagResourcesTag{
Key: k,
Value: v.(string),
})
}
return result
}
func (s *EmrService) tagsToMap(tags []emr.TagResource) map[string]string {
result := make(map[string]string)
for _, t := range tags {
result[t.TagKey] = t.TagValue
}
return result
}
func (s *EmrService) ListTagResources(id string, resourceType string) (object interface{}, err error) {
conn, err := s.client.NewEmrClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListTagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": id,
}
tags := make([]interface{}, 0)
var response map[string]interface{}
for {
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{Throttling}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.TagResources.TagResource", response)
if err != nil {
return resource.NonRetryableError(WrapErrorf(err, FailedGetAttributeMsg, id, "$.TagResources.TagResource", response))
}
if v != nil {
tags = append(tags, v.([]interface{})...)
}
return nil
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
if response["NextToken"] == nil {
break
}
request["NextToken"] = response["NextToken"]
}
return tags, nil
}
func (s *EmrService) SetResourceTags(d *schema.ResourceData, resourceType string) error {
if d.HasChange("tags") {
added, removed := parsingTags(d)
conn, err := s.client.NewEmrClient()
if err != nil {
return WrapError(err)
}
removedTagKeys := make([]string, 0)
for _, v := range removed {
if !ignoredTags(v, "") {
removedTagKeys = append(removedTagKeys, v)
}
}
if len(removedTagKeys) > 0 {
action := "UntagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": d.Id(),
}
for i, key := range removedTagKeys {
request[fmt.Sprintf("TagKey.%d", i+1)] = key
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
action := "TagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": d.Id(),
}
count := 1
for key, value := range added {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-08"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("tags")
}
return nil
}
func (s *EmrService) DescribeClusterBasicInfo(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEmrClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeClusterBasicInfo"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ClusterId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.ClusterInfo", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ClusterInfo", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *EmrService) DescribeClusterV2(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEmrClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeClusterV2"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"Id": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.ClusterInfo", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ClusterInfo", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type EnsService struct {
client *connectivity.AliyunClient
}
func (s *EnsService) DescribeEnsKeyPair(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEnsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeKeyPairs"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"KeyPairName": parts[0],
"Version": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-11-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.KeyPairs.KeyPair", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.KeyPairs.KeyPair", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ENS", id)), NotFoundWithResponse, response)
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
package alicloud
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ess"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type EssService struct {
client *connectivity.AliyunClient
}
func (s *EssService) DescribeEssAlarm(id string) (alarm ess.Alarm, err error) {
request := ess.CreateDescribeAlarmsRequest()
request.RegionId = s.client.RegionId
request.AlarmTaskId = id
request.MetricType = "system"
Alarms, err := s.client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DescribeAlarms(request)
})
if err != nil {
return alarm, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), Alarms, request.RpcRequest, request)
AlarmsResponse, _ := Alarms.(*ess.DescribeAlarmsResponse)
systemAlarms := AlarmsResponse.AlarmList.Alarm
if len(systemAlarms) > 0 {
return systemAlarms[0], nil
}
AlarmsRequest := ess.CreateDescribeAlarmsRequest()
AlarmsRequest.RegionId = s.client.RegionId
AlarmsRequest.AlarmTaskId = id
AlarmsRequest.MetricType = "custom"
raw, err := s.client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DescribeAlarms(AlarmsRequest)
})
if err != nil {
return alarm, WrapErrorf(err, DefaultErrorMsg, id, AlarmsRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(AlarmsRequest.GetActionName(), raw, AlarmsRequest.RpcRequest, AlarmsRequest)
response, _ := raw.(*ess.DescribeAlarmsResponse)
customAlarms := response.AlarmList.Alarm
if len(customAlarms) > 0 {
return customAlarms[0], nil
}
return alarm, WrapErrorf(Error(GetNotFoundMessage("EssAlarm", id)), NotFoundMsg, ProviderERROR)
}
func (s *EssService) DescribeEssLifecycleHook(id string) (hook ess.LifecycleHook, err error) {
request := ess.CreateDescribeLifecycleHooksRequest()
request.LifecycleHookId = &[]string{id}
request.RegionId = s.client.RegionId
raw, err := s.client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DescribeLifecycleHooks(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ess.DescribeLifecycleHooksResponse)
for _, v := range response.LifecycleHooks.LifecycleHook {
if v.LifecycleHookId == id {
return v, nil
}
}
err = WrapErrorf(Error(GetNotFoundMessage("EssLifecycleHook", id)), NotFoundMsg, ProviderERROR)
return
}
func (s *EssService) WaitForEssLifecycleHook(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeEssLifecycleHook(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.LifecycleHookId == id && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.LifecycleHookId, id, ProviderERROR)
}
}
}
func (s *EssService) DescribeEssNotification(id string) (notification ess.NotificationConfigurationModel, err error) {
parts := strings.SplitN(id, ":", 2)
scalingGroupId, notificationArn := parts[0], parts[1]
request := ess.CreateDescribeNotificationConfigurationsRequest()
request.RegionId = s.client.RegionId
request.ScalingGroupId = scalingGroupId
raw, err := s.client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DescribeNotificationConfigurations(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"NotificationConfigurationNotExist", "InvalidScalingGroupId.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("EssNotification", id)), NotFoundMsg, ProviderERROR)
}
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ess.DescribeNotificationConfigurationsResponse)
for _, v := range response.NotificationConfigurationModels.NotificationConfigurationModel {
if v.NotificationArn == notificationArn {
return v, nil
}
}
err = WrapErrorf(Error(GetNotFoundMessage("EssNotificationConfiguration", id)), NotFoundMsg, ProviderERROR)
return
}
func (s *EssService) WaitForEssNotification(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeEssNotification(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
resourceId := fmt.Sprintf("%s:%s", object.ScalingGroupId, object.NotificationArn)
if resourceId == id && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, resourceId, id, ProviderERROR)
}
}
}
func (s *EssService) DescribeEssScalingGroup(id string) (group ess.ScalingGroup, err error) {
request := ess.CreateDescribeScalingGroupsRequest()
request.ScalingGroupId = &[]string{id}
request.RegionId = s.client.RegionId
raw, e := s.client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DescribeScalingGroups(request)
})
if e != nil {
err = WrapErrorf(e, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ess.DescribeScalingGroupsResponse)
for _, v := range response.ScalingGroups.ScalingGroup {
if v.ScalingGroupId == id {
return v, nil
}
}
err = WrapErrorf(Error(GetNotFoundMessage("EssScalingGroup", id)), NotFoundMsg, ProviderERROR)
return
}
func (s *EssService) DescribeEssScalingConfiguration(id string) (config ess.ScalingConfiguration, err error) {
request := ess.CreateDescribeScalingConfigurationsRequest()
request.ScalingConfigurationId = &[]string{id}
request.RegionId = s.client.RegionId
raw, err := s.client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DescribeScalingConfigurations(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ess.DescribeScalingConfigurationsResponse)
for _, v := range response.ScalingConfigurations.ScalingConfiguration {
if v.ScalingConfigurationId == id {
return v, nil
}
}
err = GetNotFoundErrorFromString(GetNotFoundMessage("Scaling Configuration", id))
return
}
func (s *EssService) ActiveEssScalingConfiguration(sgId, id string) error {
request := ess.CreateModifyScalingGroupRequest()
request.ScalingGroupId = sgId
request.ActiveScalingConfigurationId = id
request.RegionId = s.client.RegionId
raw, err := s.client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.ModifyScalingGroup(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return err
}
func (s *EssService) WaitForScalingConfiguration(id string, status Status, timeout int) (err error) {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeEssScalingConfiguration(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.ScalingConfigurationId == id && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.ScalingConfigurationId, id, ProviderERROR)
}
}
}
// Flattens an array of datadisk into a []map[string]interface{}
func (s *EssService) flattenDataDiskMappings(list []ess.DataDisk) []map[string]interface{} {
result := make([]map[string]interface{}, 0, len(list))
for _, i := range list {
l := map[string]interface{}{
"size": i.Size,
"category": i.Category,
"snapshot_id": i.SnapshotId,
"device": i.Device,
"delete_with_instance": i.DeleteWithInstance,
"encrypted": i.Encrypted,
"kms_key_id": i.KMSKeyId,
"disk_name": i.DiskName,
"description": i.Description,
"auto_snapshot_policy_id": i.AutoSnapshotPolicyId,
"performance_level": i.PerformanceLevel,
}
result = append(result, l)
}
return result
}
func (s *EssService) flattenSpotPriceLimitMappings(list []ess.SpotPriceModel) []map[string]interface{} {
result := make([]map[string]interface{}, 0, len(list))
for _, i := range list {
p, _ := strconv.ParseFloat(strconv.FormatFloat(i.PriceLimit, 'f', 2, 64), 64)
l := map[string]interface{}{
"instance_type": i.InstanceType,
"price_limit": p,
}
result = append(result, l)
}
return result
}
func (s *EssService) flattenVserverGroupList(vServerGroups []ess.VServerGroup) []map[string]interface{} {
groups := make([]map[string]interface{}, 0, len(vServerGroups))
for _, v := range vServerGroups {
vserverGroupAttributes := v.VServerGroupAttributes.VServerGroupAttribute
attrs := make([]map[string]interface{}, 0, len(vserverGroupAttributes))
for _, a := range vserverGroupAttributes {
attr := map[string]interface{}{
"vserver_group_id": a.VServerGroupId,
"port": a.Port,
"weight": a.Weight,
}
attrs = append(attrs, attr)
}
group := map[string]interface{}{
"loadbalancer_id": v.LoadBalancerId,
"vserver_attributes": attrs,
}
groups = append(groups, group)
}
return groups
}
func (s *EssService) DescribeEssScalingRule(id string) (rule ess.ScalingRule, err error) {
request := ess.CreateDescribeScalingRulesRequest()
request.ScalingRuleId = &[]string{id}
request.RegionId = s.client.RegionId
raw, err := s.client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DescribeScalingRules(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidScalingRuleId.NotFound"}) {
return rule, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return rule, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ess.DescribeScalingRulesResponse)
for _, v := range response.ScalingRules.ScalingRule {
if v.ScalingRuleId == id {
return v, nil
}
}
return rule, WrapErrorf(Error(GetNotFoundMessage("EssScalingRule", id)), NotFoundMsg, ProviderERROR)
}
func (s *EssService) WaitForEssScalingRule(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeEssScalingRule(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
}
return WrapError(err)
}
if object.ScalingRuleId == id && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.ScalingRuleId, id, ProviderERROR)
}
}
}
func (s *EssService) DescribeEssScheduledTask(id string) (task ess.ScheduledTask, err error) {
request := ess.CreateDescribeScheduledTasksRequest()
request.ScheduledTaskId = &[]string{id}
request.RegionId = s.client.RegionId
raw, err := s.client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DescribeScheduledTasks(request)
})
if err != nil {
return task, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ess.DescribeScheduledTasksResponse)
for _, v := range response.ScheduledTasks.ScheduledTask {
if v.ScheduledTaskId == id {
task = v
return
}
}
err = WrapErrorf(Error(GetNotFoundMessage("EssSchedule", id)), NotFoundMsg, ProviderERROR)
return
}
func (s *EssService) WaitForEssScheduledTask(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeEssScheduledTask(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.TaskEnabled {
return nil
}
time.Sleep(DefaultIntervalShort * time.Second)
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.ScheduledTaskId, id, ProviderERROR)
}
}
}
func (srv *EssService) DescribeEssAttachment(id string, instanceIds []string) (instances []ess.ScalingInstance, err error) {
request := ess.CreateDescribeScalingInstancesRequest()
request.RegionId = srv.client.RegionId
request.ScalingGroupId = id
if len(instanceIds) > 0 {
request.InstanceId = &instanceIds
}
raw, err := srv.client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DescribeScalingInstances(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidScalingGroupId.NotFound"}) {
err = WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
} else {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ess.DescribeScalingInstancesResponse)
if len(response.ScalingInstances.ScalingInstance) < 1 {
err = WrapErrorf(Error(GetNotFoundMessage("EssAttachment", id)), NotFoundMsg, ProviderERROR)
return
}
return response.ScalingInstances.ScalingInstance, nil
}
func (s *EssService) DescribeEssScalingConfifurations(id string) (configs []ess.ScalingConfiguration, err error) {
request := ess.CreateDescribeScalingConfigurationsRequest()
request.ScalingGroupId = id
request.PageNumber = requests.NewInteger(1)
request.PageSize = requests.NewInteger(PageSizeLarge)
request.RegionId = s.client.RegionId
for {
raw, err := s.client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.DescribeScalingConfigurations(request)
})
if err != nil {
return configs, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ess.DescribeScalingConfigurationsResponse)
if len(response.ScalingConfigurations.ScalingConfiguration) < 1 {
break
}
configs = append(configs, response.ScalingConfigurations.ScalingConfiguration...)
if len(response.ScalingConfigurations.ScalingConfiguration) < PageSizeLarge {
break
}
if page, err := getNextpageNumber(request.PageNumber); err != nil {
return configs, WrapError(err)
} else {
request.PageNumber = page
}
}
if len(configs) < 1 {
return configs, WrapErrorf(Error(GetNotFoundMessage("EssScalingConfifuration", id)), NotFoundMsg, ProviderERROR)
}
return
}
func (srv *EssService) EssRemoveInstances(id string, instanceIds []string) error {
if len(instanceIds) < 1 {
return nil
}
group, err := srv.DescribeEssScalingGroup(id)
if err != nil {
return WrapError(err)
}
if group.LifecycleState == string(Inactive) {
return WrapError(Error("Scaling group current status is %s, please active it before attaching or removing ECS instances.", group.LifecycleState))
} else {
if err := srv.WaitForEssScalingGroup(group.ScalingGroupId, Active, DefaultTimeout); err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
}
removed := instanceIds
if err := resource.Retry(5*time.Minute, func() *resource.RetryError {
request := ess.CreateRemoveInstancesRequest()
request.ScalingGroupId = id
request.RegionId = srv.client.RegionId
if len(removed) > 0 {
request.InstanceId = &removed
} else {
return nil
}
raw, err := srv.client.WithEssClient(func(essClient *ess.Client) (interface{}, error) {
return essClient.RemoveInstances(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidScalingGroupId.NotFound"}) {
return nil
}
if IsExpectedErrors(err, []string{"IncorrectCapacity.MinSize"}) {
instances, err := srv.DescribeEssAttachment(id, instanceIds)
if len(instances) > 0 {
if group.MinSize == 0 {
return resource.RetryableError(WrapError(err))
}
return resource.NonRetryableError(WrapError(err))
}
}
if IsExpectedErrors(err, []string{"ScalingActivityInProgress", "IncorrectScalingGroupStatus"}) {
time.Sleep(5)
return resource.RetryableError(WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR))
}
return resource.NonRetryableError(WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR))
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
time.Sleep(3 * time.Second)
instances, err := srv.DescribeEssAttachment(id, instanceIds)
if err != nil {
if NotFoundError(err) {
return nil
}
return resource.NonRetryableError(WrapError(err))
}
if len(instances) > 0 {
removed = make([]string, 0)
for _, inst := range instances {
removed = append(removed, inst.InstanceId)
}
return resource.RetryableError(WrapError(Error("There are still ECS instances in the scaling group.")))
}
return nil
}); err != nil {
return WrapError(err)
}
return nil
}
// WaitForScalingGroup waits for group to given status
func (s *EssService) WaitForEssScalingGroup(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeEssScalingGroup(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.LifecycleState == string(status) {
return nil
}
time.Sleep(DefaultIntervalShort * time.Second)
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.LifecycleState, string(status), ProviderERROR)
}
}
}
// ess dimensions to map
func (s *EssService) flattenDimensionsToMap(dimensions []ess.Dimension) map[string]string {
result := make(map[string]string)
for _, dimension := range dimensions {
if dimension.DimensionKey == UserId || dimension.DimensionKey == ScalingGroup {
continue
}
result[dimension.DimensionKey] = dimension.DimensionValue
}
return result
}
func (s *EssService) WaitForEssAttachment(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeEssAttachment(id, make([]string, 0))
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if len(object) > 0 && status != Deleted {
return nil
}
time.Sleep(DefaultIntervalShort * time.Second)
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, Null, string(status), ProviderERROR)
}
}
}
func (s *EssService) WaitForEssAlarm(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeEssAlarm(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.AlarmTaskId == id && status != Deleted {
return nil
}
time.Sleep(DefaultIntervalShort * time.Second)
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.AlarmTaskId, id, ProviderERROR)
}
}
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type EventbridgeService struct {
client *connectivity.AliyunClient
}
func (s *EventbridgeService) DescribeEventBridgeEventBus(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEventbridgeClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetEventBus"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"EventBusName": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if IsExpectedErrorCodes(fmt.Sprint(response["Code"]), []string{"EventBusNotExist"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("EventBridge:EventBus", id)), NotFoundMsg, ProviderERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("GetEventBus failed, response: %v", response))
}
v, err := jsonpath.Get("$.Data", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *EventbridgeService) DescribeEventBridgeRule(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEventbridgeClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetRule"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"EventBusName": parts[0],
"RuleName": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if IsExpectedErrorCodes(fmt.Sprint(response["Code"]), []string{"EventRuleNotExisted"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("EventBridge:Rule", id)), NotFoundMsg, ProviderERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return object, WrapError(fmt.Errorf("GetRule failed, response: %v", response))
}
v, err := jsonpath.Get("$.Data", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *EventbridgeService) EventBridgeRuleStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeEventBridgeRule(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *EventbridgeService) DescribeEventBridgeServiceLinkedRole(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEventbridgeClient()
if err != nil {
return nil, WrapError(err)
}
action := "CheckRoleForProduct"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ProductName": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2020-04-01"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("CheckRoleForProduct failed, response: %v", response))
}
v, err := jsonpath.Get("$.Data", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *EventbridgeService) CheckRoleForProductRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeEventBridgeServiceLinkedRole(id)
if err != nil {
if NotFoundError(err) {
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["CheckPass"]) == failState {
return object, fmt.Sprint(object["CheckPass"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["CheckPass"])))
}
}
return object, fmt.Sprint(object["CheckPass"]), nil
}
}
func (s *EventbridgeService) DescribeEventBridgeEventSource(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewEventbridgeClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListUserDefinedEventSources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"Limit": PageSizeLarge,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.Data.EventSourceList", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data.EventSourceList", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("EventBridge", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if v.(map[string]interface{})["Name"].(string) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("EventBridge", id)), NotFoundWithResponse, response)
}
return
}
package alicloud
import (
"encoding/json"
"strings"
"time"
"github.com/aliyun/fc-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
)
type FcService struct {
client *connectivity.AliyunClient
}
func (s *FcService) DescribeFcService(id string) (*fc.GetServiceOutput, error) {
response := &fc.GetServiceOutput{}
request := &fc.GetServiceInput{ServiceName: &id}
var requestInfo *fc.Client
raw, err := s.client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.GetService(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ServiceNotFound"}) {
err = WrapErrorf(err, NotFoundMsg, FcGoSdk)
} else {
err = WrapErrorf(err, DefaultErrorMsg, id, "GetService", FcGoSdk)
}
return response, err
}
addDebug("GetService", raw, requestInfo, request)
response, _ = raw.(*fc.GetServiceOutput)
if *response.ServiceName != id {
err = WrapErrorf(Error(GetNotFoundMessage("FcService", id)), NotFoundMsg, FcGoSdk)
}
return response, err
}
func (s *FcService) WaitForFcService(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeFcService(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if *object.ServiceName == id && status != Deleted {
return nil
}
time.Sleep(DefaultIntervalShort * time.Second)
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, *object.ServiceName, id, ProviderERROR)
}
}
}
func (s *FcService) DescribeFcFunction(id string) (*fc.GetFunctionOutput, error) {
response := &fc.GetFunctionOutput{}
parts, err := ParseResourceId(id, 2)
if err != nil {
return response, WrapError(err)
}
service, name := parts[0], parts[1]
request := &fc.GetFunctionInput{
ServiceName: &service,
FunctionName: &name,
}
var requestInfo *fc.Client
raw, err := s.client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.GetFunction(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ServiceNotFound", "FunctionNotFound"}) {
err = WrapErrorf(err, NotFoundMsg, FcGoSdk)
} else {
err = WrapErrorf(err, DefaultErrorMsg, id, "GetFunction", FcGoSdk)
}
return response, err
}
addDebug("GetFunction", raw, requestInfo, request)
response, _ = raw.(*fc.GetFunctionOutput)
if *response.FunctionName == "" {
err = WrapErrorf(Error(GetNotFoundMessage("FcFunction", id)), NotFoundMsg, FcGoSdk)
}
return response, err
}
func (s *FcService) WaitForFcFunction(id string, status Status, timeout int) error {
parts, err := ParseResourceId(id, 2)
if err != nil {
return WrapError(err)
}
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeFcFunction(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if *object.FunctionName == parts[1] && status != Deleted {
break
}
time.Sleep(DefaultIntervalShort * time.Second)
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, *object.FunctionName, parts[1], ProviderERROR)
}
}
return nil
}
func (s *FcService) DescribeFcTrigger(id string) (*fc.GetTriggerOutput, error) {
response := &fc.GetTriggerOutput{}
parts, err := ParseResourceId(id, 3)
if err != nil {
return response, WrapError(err)
}
service, function, name := parts[0], parts[1], parts[2]
request := fc.NewGetTriggerInput(service, function, name)
var requestInfo *fc.Client
raw, err := s.client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.GetTrigger(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ServiceNotFound", "FunctionNotFound", "TriggerNotFound"}) {
err = WrapErrorf(err, NotFoundMsg, FcGoSdk)
} else {
err = WrapErrorf(err, DefaultErrorMsg, id, "FcTrigger", FcGoSdk)
}
return response, err
}
addDebug("GetTrigger", raw, requestInfo, request)
response, _ = raw.(*fc.GetTriggerOutput)
if *response.TriggerName != name {
err = WrapErrorf(Error(GetNotFoundMessage("FcTrigger", name)), NotFoundMsg, ProviderERROR)
}
return response, err
}
func (s *FcService) DescribeFcAlias(id string) (*fc.GetAliasOutput, error) {
response := &fc.GetAliasOutput{}
parts, err := ParseResourceId(id, 2)
if err != nil {
return nil, WrapError(err)
}
service, name := parts[0], parts[1]
request := &fc.GetAliasInput{
ServiceName: &service,
AliasName: &name,
}
var requestInfo *fc.Client
raw, err := s.client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.GetAlias(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ServiceNotFound", "AliasNotFound"}) {
err = WrapErrorf(err, NotFoundMsg, FcGoSdk)
} else {
err = WrapErrorf(err, DefaultErrorMsg, id, "GetAlias", FcGoSdk)
}
return response, err
}
addDebug("GetAlias", raw, requestInfo, request)
response, _ = raw.(*fc.GetAliasOutput)
if *response.AliasName == "" {
err = WrapErrorf(Error(GetNotFoundMessage("FcAlias", id)), NotFoundMsg, FcGoSdk)
}
return response, err
}
func removeSpaceAndEnter(s string) string {
if Trim(s) == "" {
return Trim(s)
}
return strings.Replace(strings.Replace(strings.Replace(s, " ", "", -1), "\n", "", -1), "\t", "", -1)
}
func delEmptyPayloadIfExist(s string) (string, error) {
if s == "" {
return s, nil
}
in := []byte(s)
var raw map[string]interface{}
if err := json.Unmarshal(in, &raw); err != nil {
return s, err
}
if _, ok := raw["payload"]; ok {
delete(raw, "payload")
}
out, err := json.Marshal(raw)
return string(out), err
}
func resolveFcTriggerConfig(s string) (string, error) {
if s == "" {
return s, nil
}
in := []byte(s)
var raw map[string]interface{}
if err := json.Unmarshal(in, &raw); err != nil {
return s, err
}
out, err := json.Marshal(raw)
return string(out), err
}
func (s *FcService) WaitForFcTrigger(id string, status Status, timeout int) error {
parts, err := ParseResourceId(id, 3)
if err != nil {
return WrapError(err)
}
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeFcTrigger(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if *object.TriggerName == parts[2] {
break
}
time.Sleep(DefaultIntervalShort * time.Second)
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, *object.TriggerName, parts[2], ProviderERROR)
}
}
return nil
}
func (s *FcService) DescribeFcCustomDomain(id string) (*fc.GetCustomDomainOutput, error) {
request := &fc.GetCustomDomainInput{DomainName: &id}
response := &fc.GetCustomDomainOutput{}
var requestInfo *fc.Client
raw, err := s.client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.GetCustomDomain(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"DomainNameNotFound"}) {
err = WrapErrorf(err, NotFoundMsg, FcGoSdk)
} else {
err = WrapErrorf(err, DefaultErrorMsg, id, "FcCustomDomain", FcGoSdk)
}
return response, err
}
addDebug("GetCustomDomain", raw, requestInfo, request)
response, _ = raw.(*fc.GetCustomDomainOutput)
if *response.DomainName != id {
err = WrapErrorf(Error(GetNotFoundMessage("FcCustomDomain", id)), NotFoundMsg, ProviderERROR)
}
return response, err
}
func (s *FcService) WaitForFcCustomDomain(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeFcCustomDomain(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if *object.DomainName == id && status != Deleted {
return nil
}
time.Sleep(DefaultIntervalShort * time.Second)
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, *object.DomainName, id, ProviderERROR)
}
}
}
func (s *FcService) DescribeFcFunctionAsyncInvokeConfig(id string) (*fc.GetFunctionAsyncInvokeConfigOutput, error) {
serviceName, functionName, qualifier, err := parseFCDestinationConfigId(id)
if err != nil {
return nil, err
}
request := &fc.GetFunctionAsyncInvokeConfigInput{
ServiceName: &serviceName,
FunctionName: &functionName,
}
if qualifier != "" {
request.Qualifier = &qualifier
}
response := &fc.GetFunctionAsyncInvokeConfigOutput{}
var requestInfo *fc.Client
raw, err := s.client.WithFcClient(func(fcClient *fc.Client) (interface{}, error) {
requestInfo = fcClient
return fcClient.GetFunctionAsyncInvokeConfig(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"ServiceNotFound", "FunctionNotFound", "AsyncConfigNotExists"}) {
err = WrapErrorf(err, NotFoundMsg, FcGoSdk)
} else {
err = WrapErrorf(err, DefaultErrorMsg, id, "FcFunctionAsyncInvokeConfig", FcGoSdk)
}
return response, err
}
addDebug("GetFunctionAsyncInvokeConfig", raw, requestInfo, request)
response, _ = raw.(*fc.GetFunctionAsyncInvokeConfigOutput)
return response, err
}
func (s *FcService) WaitForFcFunctionAsyncInvokeConfig(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
_, err := s.DescribeFcFunctionAsyncInvokeConfig(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if status != Deleted {
return nil
}
time.Sleep(DefaultIntervalShort * time.Second)
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, id, ProviderERROR)
}
}
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type FnfService struct {
client *connectivity.AliyunClient
}
func (s *FnfService) DescribeFnfFlow(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewFnfClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeFlow"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"Name": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-03-15"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"FlowNotExists"}) {
err = WrapErrorf(Error(GetNotFoundMessage("FnfFlow", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *FnfService) DescribeFnfSchedule(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewFnfClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeSchedule"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"FlowName": parts[0],
"ScheduleName": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-03-15"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"FlowNotExists", "ScheduleNotExists"}) {
err = WrapErrorf(Error(GetNotFoundMessage("FnfSchedule", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *FnfService) DescribeFnFExecution(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewFnfClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeExecution"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"ExecutionName": parts[1],
"FlowName": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-03-15"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"FlowNotExists"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("FnF:Execution", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *FnfService) FnFExecutionStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeFnFExecution(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *FnfService) DescribeExecution(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewFnfClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeExecution"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"ExecutionName": parts[1],
"FlowName": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-03-15"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"FlowNotExists"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("FnF:Execution", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type GaService struct {
client *connectivity.AliyunClient
}
func (s *GaService) DescribeGaAccelerator(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewGaplusClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeAccelerator"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"AcceleratorId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"UnknownError"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Ga:Accelerator", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *GaService) GaAcceleratorStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeGaAccelerator(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["State"]) == failState {
return object, fmt.Sprint(object["State"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["State"])))
}
}
return object, fmt.Sprint(object["State"]), nil
}
}
func (s *GaService) DescribeGaListener(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewGaplusClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeListener"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ListenerId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"NotExist.Listener", "UnknownError"}) {
err = WrapErrorf(Error(GetNotFoundMessage("GaListener", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *GaService) GaListenerStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeGaListener(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["State"].(string) == failState {
return object, object["State"].(string), WrapError(Error(FailedToReachTargetStatus, object["State"].(string)))
}
}
return object, object["State"].(string), nil
}
}
func (s *GaService) DescribeGaBandwidthPackage(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewGaplusClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeBandwidthPackage"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"BandwidthPackageId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"NotExist.BandwidthPackage"}) {
err = WrapErrorf(Error(GetNotFoundMessage("GaBandwidthPackage", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *GaService) GaBandwidthPackageStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeGaBandwidthPackage(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["State"].(string) == failState {
return object, object["State"].(string), WrapError(Error(FailedToReachTargetStatus, object["State"].(string)))
}
}
return object, object["State"].(string), nil
}
}
func (s *GaService) DescribeGaEndpointGroup(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewGaplusClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeEndpointGroup"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"EndpointGroupId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"NotExist.EndPointGroup"}) {
err = WrapErrorf(Error(GetNotFoundMessage("GaEndpointGroup", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
if object["State"] == nil {
err = WrapErrorf(Error(GetNotFoundMessage("GaEndpointGroup", id)), NotFoundMsg, ProviderERROR)
return object, err
}
return object, nil
}
func (s *GaService) DescribeGaForwardingRule(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewGaplusClient()
if err != nil {
return nil, WrapError(err)
}
parts, err := ParseResourceId(id, 3)
if err != nil {
err = WrapError(err)
return
}
action := "ListForwardingRules"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ListenerId": parts[1],
"AcceleratorId": parts[0],
"ForwardingRuleId": parts[2],
"MaxResults": PageSizeLarge,
}
request["ClientToken"] = buildClientToken(action)
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
err = resource.Retry(5*time.Second, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"StateError.Accelerator"}) {
return resource.RetryableError(WrapErrorf(Error(GetNotFoundMessage("ForwardingRule", id)), NotFoundMsg, ProviderERROR))
}
return resource.NonRetryableError(WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR))
}
addDebug(action, response, request)
return nil
})
if err != nil {
return
}
v, err := jsonpath.Get("$.ForwardingRules", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ForwardingRules", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ForwardingRule", id)), NotFoundWithResponse, response)
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *GaService) DescribeGaIpSet(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewGaplusClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeIpSet"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"IpSetId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"UnknownError"}) {
err = WrapErrorf(Error(GetNotFoundMessage("GaIpSet", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
if object["State"] == nil {
err = WrapErrorf(Error(GetNotFoundMessage("GaIpSet", id)), NotFoundMsg, ProviderERROR)
return object, err
}
return object, nil
}
func (s *GaService) DescribeGaBandwidthPackageAttachment(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
parts, err := ParseResourceId(id, 2)
if err != nil {
return nil, WrapError(err)
}
conn, err := s.client.NewGaplusClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeAccelerator"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"AcceleratorId": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"UnknownError"}) {
err = WrapErrorf(Error(GetNotFoundMessage("GaBandwidthPackageAttachment", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
basic, exist1 := object["BasicBandwidthPackage"]
cross, exist2 := object["CrossDomainBandwidthPackage"]
if (exist1 && basic.(map[string]interface{})["InstanceId"] == parts[1]) || (exist2 && cross.(map[string]interface{})["InstanceId"] == parts[1]) {
return object, nil
}
return object, WrapErrorf(Error(GetNotFoundMessage("GaBandwidthPackageAttachment", id)), NotFoundMsg, ProviderERROR)
}
func (s *GaService) GaEndpointGroupStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeGaEndpointGroup(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["State"].(string) == failState {
return object, object["State"].(string), WrapError(Error(FailedToReachTargetStatus, object["State"].(string)))
}
}
return object, object["State"].(string), nil
}
}
func (s *GaService) GaForwardingRuleStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeGaForwardingRule(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["ForwardingRuleStatus"].(string) == failState {
return object, object["ForwardingRuleStatus"].(string), WrapError(Error(FailedToReachTargetStatus, object["ForwardingRuleStatus"].(string)))
}
}
return object, object["ForwardingRuleStatus"].(string), nil
}
}
func (s *GaService) GaBandwidthPackageAttachmentStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeGaBandwidthPackageAttachment(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["State"].(string) == failState {
return object, object["State"].(string), WrapError(Error(FailedToReachTargetStatus, object["State"].(string)))
}
}
return object, object["State"].(string), nil
}
}
func (s *GaService) GaIpSetStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeGaIpSet(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["State"].(string) == failState {
return object, object["State"].(string), WrapError(Error(FailedToReachTargetStatus, object["State"].(string)))
}
}
return object, object["State"].(string), nil
}
}
func (s *GaService) DescribeAcceleratorAutoRenewAttribute(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewGaplusClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeAcceleratorAutoRenewAttribute"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"AcceleratorId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *GaService) DescribeGaAcl(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewGaplusClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetAcl"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"AclId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"NotExist.Acl"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Ga:Acl", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *GaService) GaAclStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeGaAcl(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["AclStatus"]) == failState {
return object, fmt.Sprint(object["AclStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["AclStatus"])))
}
}
return object, fmt.Sprint(object["AclStatus"]), nil
}
}
func (s *GaService) GetAcl(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewGaplusClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetAcl"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"AclId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"NotExist.Acl"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Ga:Acl", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *GaService) DescribeGaAclAttachment(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewGaplusClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeListener"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ListenerId": parts[0],
}
idExist := false
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"NotExist.Listener"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Ga::AclAttachment", id)), NotFoundWithResponse, response)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
resp, _ := v.(map[string]interface{})
if v, ok := resp["RelatedAcls"].([]interface{}); ok && len(v) > 0 {
for _, aclArgs := range v {
aclArg := aclArgs.(map[string]interface{})
if fmt.Sprint(aclArg["AclId"]) == parts[1] {
idExist = true
resp["status"] = aclArg["Status"]
return resp, nil
}
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("Ga::AclAttachment", id)), NotFoundWithResponse, response)
}
return object, nil
}
func (s *GaService) GaAclAttachmentStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeGaAclAttachment(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["status"]) == failState {
return object, fmt.Sprint(object["status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["RelatedAcls[*].Status"])))
}
}
return object, fmt.Sprint(object["status"]), nil
}
}
func (s *GaService) DescribeGaAdditionalCertificate(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewGaplusClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListListenerCertificates"
parts, err := ParseResourceId(id, 3)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"AcceleratorId": parts[0],
"ListenerId": parts[1],
"Role": "additional",
"MaxResults": PageSizeMedium,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-11-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Certificates", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Certificates", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("Ga", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["Domain"]) == parts[2] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("Ga", id)), NotFoundWithResponse, response)
}
return
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type GdbService struct {
client *connectivity.AliyunClient
}
func (s *GdbService) DescribeGraphDatabaseDbInstance(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewGdsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDBInstanceAttribute"
request := map[string]interface{}{
"DBInstanceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-03"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstance.NotFound", "InvalidDBInstanceId.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("GraphDatabase:DbInstance", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Items.DBInstance", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Items.DBInstance", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("GraphDatabase", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["DBInstanceId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("GraphDatabase", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
GetDBInstanceAccessWhiteListObject, err := s.GetDBInstanceAccessWhiteList(id)
if err != nil {
return nil, err
}
object["DBInstanceIPArray"] = GetDBInstanceAccessWhiteListObject["DBInstanceIPArray"]
return object, nil
}
func (s *GdbService) GetDBInstanceAccessWhiteList(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewGdsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDBInstanceAccessWhiteList"
request := map[string]interface{}{
"DBInstanceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-03"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstance.NotFound", "InvalidDBInstanceId.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("GraphDatabase:DbInstance", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Items", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Items", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *GdbService) GraphDatabaseDbInstanceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeGraphDatabaseDbInstance(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["DBInstanceStatus"]) == failState {
return object, fmt.Sprint(object["DBInstanceStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["DBInstanceStatus"])))
}
}
return object, fmt.Sprint(object["DBInstanceStatus"]), nil
}
}
func (s *GdbService) DescribeDBInstanceAttribute(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewGdsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDBInstanceAttribute"
request := map[string]interface{}{
"DBInstanceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-03"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstance.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("GraphDatabase:DbInstance", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Items.DBInstance", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Items.DBInstance", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("GraphDatabase", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["DBInstanceId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("GraphDatabase", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"strings"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/alibaba-cloud-sdk-go/services/gpdb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type GpdbService struct {
client *connectivity.AliyunClient
}
func (s *GpdbService) DescribeGpdbInstance(id string) (instanceAttribute gpdb.DBInstanceAttribute, err error) {
request := gpdb.CreateDescribeDBInstanceAttributeRequest()
request.RegionId = s.client.RegionId
request.DBInstanceId = id
raw, err := s.client.WithGpdbClient(func(client *gpdb.Client) (interface{}, error) {
return client.DescribeDBInstanceAttribute(request)
})
response, _ := raw.(*gpdb.DescribeDBInstanceAttributeResponse)
if err != nil {
// convert error code
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound"}) {
err = WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
} else {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return
}
addDebug(request.GetActionName(), response, request.RpcRequest, request)
if len(response.Items.DBInstanceAttribute) == 0 {
return instanceAttribute, WrapErrorf(Error(GetNotFoundMessage("Gpdb Instance", id)), NotFoundMsg, ProviderERROR)
}
return response.Items.DBInstanceAttribute[0], nil
}
func (s *GpdbService) DescribeGpdbElasticInstance(id string) (map[string]interface{}, error) {
conn, err := s.client.NewGpdbClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDBInstanceOnECSAttribute"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": id,
"SourceIp": s.client.SourceIp,
}
var response map[string]interface{}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-05-03"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound", ServiceUnavailable}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return nil, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Items.DBInstanceAttribute", response)
if err != nil {
return nil, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Items.DBInstanceAttribute", response)
}
if len(v.([]interface{})) < 1 {
return nil, WrapErrorf(Error(GetNotFoundMessage("Gpdb elastic instance", id)), NotFoundMsg, ProviderERROR)
}
return v.([]interface{})[0].(map[string]interface{}), nil
}
func (s *GpdbService) DescribeGpdbSecurityIps(id string) (ips []string, err error) {
request := gpdb.CreateDescribeDBInstanceIPArrayListRequest()
request.RegionId = s.client.RegionId
request.DBInstanceId = id
raw, err := s.client.WithGpdbClient(func(client *gpdb.Client) (interface{}, error) {
return client.DescribeDBInstanceIPArrayList(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound"}) {
err = WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
} else {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return
}
response, _ := raw.(*gpdb.DescribeDBInstanceIPArrayListResponse)
addDebug(request.GetActionName(), response, request.RpcRequest, request)
var ipstr, separator string
ipsMap := make(map[string]string)
for _, ip := range response.Items.DBInstanceIPArray {
if ip.DBInstanceIPArrayAttribute == "hidden" {
continue
}
ipstr += separator + ip.SecurityIPList
separator = COMMA_SEPARATED
}
for _, ip := range strings.Split(ipstr, COMMA_SEPARATED) {
ipsMap[ip] = ip
}
var finalIps []string
if len(ipsMap) > 0 {
for key := range ipsMap {
finalIps = append(finalIps, key)
}
}
return finalIps, nil
}
func (s *GpdbService) ModifyGpdbSecurityIps(id, ips string) error {
request := gpdb.CreateModifySecurityIpsRequest()
request.RegionId = s.client.RegionId
request.DBInstanceId = id
request.SecurityIPList = ips
raw, err := s.client.WithGpdbClient(func(client *gpdb.Client) (interface{}, error) {
return client.ModifySecurityIps(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response := raw.(*gpdb.ModifySecurityIpsResponse)
addDebug(request.GetActionName(), response, request.RpcRequest, request)
return nil
}
func (s *GpdbService) DescribeGpdbConnection(id string) (*gpdb.DBInstanceNetInfo, error) {
info := &gpdb.DBInstanceNetInfo{}
parts, err := ParseResourceId(id, 2)
if err != nil {
return info, WrapError(err)
}
// Describe DB Instance Net Info
request := gpdb.CreateDescribeDBInstanceNetInfoRequest()
request.RegionId = s.client.RegionId
request.DBInstanceId = parts[0]
raw, err := s.client.WithGpdbClient(func(gpdbClient *gpdb.Client) (interface{}, error) {
return gpdbClient.DescribeDBInstanceNetInfo(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound"}) {
return info, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return info, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*gpdb.DescribeDBInstanceNetInfoResponse)
if response.DBInstanceNetInfos.DBInstanceNetInfo != nil {
for _, o := range response.DBInstanceNetInfos.DBInstanceNetInfo {
if strings.HasPrefix(o.ConnectionString, parts[1]) {
return &o, nil
}
}
}
return info, WrapErrorf(Error(GetNotFoundMessage("GpdbConnection", id)), NotFoundMsg, ProviderERROR)
}
func (s *GpdbService) GpdbInstanceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeGpdbInstance(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.DBInstanceStatus == failState {
return object, object.DBInstanceStatus, WrapError(Error(FailedToReachTargetStatus, object.DBInstanceStatus))
}
}
return object, object.DBInstanceStatus, nil
}
}
func (s *GpdbService) GpdbElasticInstanceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
instance, err := s.DescribeGpdbElasticInstance(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if instance["DBInstanceStatus"] == failState {
return instance, instance["DBInstanceStatus"].(string), WrapError(Error(FailedToReachTargetStatus, instance["DBInstanceStatus"]))
}
}
return instance, instance["DBInstanceStatus"].(string), nil
}
}
func (s *GpdbService) WaitForGpdbConnection(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeGpdbConnection(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.ConnectionString != "" && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.ConnectionString, id, ProviderERROR)
}
}
}
func (s *GpdbService) setInstanceTags(d *schema.ResourceData) error {
oraw, nraw := d.GetChange("tags")
o := oraw.(map[string]interface{})
n := nraw.(map[string]interface{})
create, remove := diffGpdbTags(gpdbTagsFromMap(o), gpdbTagsFromMap(n))
if len(remove) > 0 {
var tagKey []string
for _, v := range remove {
tagKey = append(tagKey, v.Key)
}
request := gpdb.CreateUntagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.ResourceType = string(TagResourceInstance)
request.TagKey = &tagKey
request.RegionId = s.client.RegionId
raw, err := s.client.WithGpdbClient(func(client *gpdb.Client) (interface{}, error) {
return client.UntagResources(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
if len(create) > 0 {
request := gpdb.CreateTagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.Tag = &create
request.ResourceType = string(TagResourceInstance)
request.RegionId = s.client.RegionId
raw, err := s.client.WithGpdbClient(func(client *gpdb.Client) (interface{}, error) {
return client.TagResources(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
d.SetPartial("tags")
return nil
}
func (s *GpdbService) tagsToMap(tags []gpdb.Tag) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !s.ignoreTag(t) {
result[t.Key] = t.Value
}
}
return result
}
func (s *GpdbService) ignoreTag(t gpdb.Tag) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, t.Key)
ok, _ := regexp.MatchString(v, t.Key)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific t %s (val: %s), ignoring.\n", t.Key, t.Value)
return true
}
}
return false
}
func (s *GpdbService) DescribeGpdbAccount(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewGpdbClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeAccounts"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"AccountName": parts[1],
"DBInstanceId": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-05-03"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("GPDB:Account", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Accounts.DBInstanceAccount", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Accounts.DBInstanceAccount", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("GPDB", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["AccountName"]) != parts[1] {
return object, WrapErrorf(Error(GetNotFoundMessage("GPDB", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *GpdbService) GpdbAccountStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeGpdbAccount(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["AccountStatus"]) == failState {
return object, fmt.Sprint(object["AccountStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["AccountStatus"])))
}
}
return object, fmt.Sprint(object["AccountStatus"]), nil
}
}
package alicloud
import (
"fmt"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
)
type HaVipService struct {
client *connectivity.AliyunClient
}
func (s *HaVipService) DescribeHaVip(haVipId string) (v vpc.HaVip, err error) {
request := vpc.CreateDescribeHaVipsRequest()
request.RegionId = s.client.RegionId
values := []string{haVipId}
filter := []vpc.DescribeHaVipsFilter{{
Key: "HaVipId",
Value: &values,
},
}
request.Filter = &filter
invoker := NewInvoker()
err = invoker.Run(func() error {
raw, err := s.client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeHaVips(request)
})
if err != nil {
return err
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
resp, _ := raw.(*vpc.DescribeHaVipsResponse)
if resp == nil || len(resp.HaVips.HaVip) <= 0 ||
resp.HaVips.HaVip[0].HaVipId != haVipId {
return GetNotFoundErrorFromString(GetNotFoundMessage("HaVip", haVipId))
}
v = resp.HaVips.HaVip[0]
return nil
})
return
}
func (s *HaVipService) WaitForHaVip(haVipId string, status Status, timeout int) error {
if timeout <= 0 {
timeout = DefaultTimeout
}
for {
//wait the order effective
havip, err := s.DescribeHaVip(haVipId)
if err != nil {
return err
}
if strings.ToLower(havip.Status) == strings.ToLower(string(status)) {
break
}
timeout = timeout - DefaultIntervalShort
if timeout <= 0 {
return GetTimeErrorFromString(GetTimeoutMessage("HaVip", string(status)))
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *HaVipService) DescribeHaVipAttachment(haVipId string, instanceId string) (err error) {
invoker := NewInvoker()
return invoker.Run(func() error {
haVip, err := s.DescribeHaVip(haVipId)
if err != nil {
return err
}
for _, id := range haVip.AssociatedInstances.AssociatedInstance {
if id == instanceId {
return nil
}
}
return GetNotFoundErrorFromString(GetNotFoundMessage("HaVipAttachment", haVipId+COLON_SEPARATED+instanceId))
})
}
func (s *HaVipService) WaitForHaVipAttachment(haVipId string, instanceId string, timeout int) error {
if timeout <= 0 {
timeout = DefaultTimeout
}
for {
err := s.DescribeHaVipAttachment(haVipId, instanceId)
if err != nil {
if !NotFoundError(err) {
return err
}
} else {
break
}
timeout = timeout - DefaultIntervalShort
if timeout <= 0 {
return GetTimeErrorFromString(GetTimeoutMessage("HaVip Attachment", string("Unavailable")))
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func getHaVipIdAndInstanceId(d *schema.ResourceData, meta interface{}) (string, string, error) {
parts := strings.Split(d.Id(), COLON_SEPARATED)
if len(parts) != 2 {
return "", "", fmt.Errorf("invalid resource id")
}
return parts[0], parts[1], nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/hbase"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
const (
Hb_LAUNCHING = "LAUNCHING"
Hb_CREATING = "CREATING"
Hb_ACTIVATION = "ACTIVATION"
Hb_DELETING = "DELETING"
Hb_CREATE_FAILED = "CREATE_FAILED"
Hb_NODE_RESIZING = "HBASE_SCALE_OUT"
Hb_NODE_RESIZING_FAILED = "NODE_RESIZE_FAILED"
Hb_DISK_RESIZING = "HBASE_EXPANDING"
Hb_DISK_RESIZE_FAILED = "DISK_RESIZING_FAILED"
Hb_LEVEL_MODIFY = "INSTANCE_LEVEL_MODIFY"
Hb_LEVEL_MODIFY_FAILED = "INSTANCE_LEVEL_MODIFY_FAILED"
Hb_HBASE_COLD_EXPANDING = "HBASE_COLD_EXPANDING"
)
type HBaseService struct {
client *connectivity.AliyunClient
}
func (s *HBaseService) setInstanceTags(d *schema.ResourceData) error {
oraw, nraw := d.GetChange("tags")
o := oraw.(map[string]interface{})
n := nraw.(map[string]interface{})
create, remove := s.diffTags(s.tagsFromMap(o), s.tagsFromMap(n))
if len(remove) > 0 {
var tagKey []string
for _, v := range remove {
tagKey = append(tagKey, v.Key)
}
request := hbase.CreateUnTagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.TagKey = &tagKey
request.RegionId = s.client.RegionId
raw, err := s.client.WithHbaseClient(func(hbaseClient *hbase.Client) (interface{}, error) {
return hbaseClient.UnTagResources(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
if len(create) > 0 {
request := hbase.CreateTagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.Tag = &create
request.RegionId = s.client.RegionId
raw, err := s.client.WithHbaseClient(func(hbaseClient *hbase.Client) (interface{}, error) {
return hbaseClient.TagResources(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
d.SetPartial("tags")
return nil
}
func (s *HBaseService) diffTags(oldTags, newTags []hbase.TagResourcesTag) ([]hbase.TagResourcesTag, []hbase.TagResourcesTag) {
// First, we're creating everything we have
create := make(map[string]interface{})
for _, t := range newTags {
create[t.Key] = t.Value
}
// Build the list of what to remove
var remove []hbase.TagResourcesTag
for _, t := range oldTags {
old, ok := create[t.Key]
if !ok || old != t.Value {
// Delete it!
remove = append(remove, t)
}
}
return s.tagsFromMap(create), remove
}
func (s *HBaseService) tagsFromMap(m map[string]interface{}) []hbase.TagResourcesTag {
result := make([]hbase.TagResourcesTag, 0, len(m))
for k, v := range m {
result = append(result, hbase.TagResourcesTag{
Key: k,
Value: v.(string),
})
}
return result
}
func (s *HBaseService) tagsToMap(tags []hbase.Tag) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !s.ignoreTag(t) {
result[t.Key] = t.Value
}
}
return result
}
func (s *HBaseService) ignoreTag(t hbase.Tag) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, t.Key)
ok, _ := regexp.MatchString(v, t.Key)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific t %s (val: %s), ignoring.\n", t.Key, t.Value)
return true
}
}
return false
}
func (s *HBaseService) DescribeHBaseInstance(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHbaseClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeInstance"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ClusterId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-01"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Instance.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Hbase:Instance", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
//pop has limit, support next.
func (s *HBaseService) DescribeIpWhitelist(id string) (instance hbase.DescribeIpWhitelistResponse, err error) {
request := hbase.CreateDescribeIpWhitelistRequest()
request.RegionId = s.client.RegionId
request.ClusterId = id
raw, err := s.client.WithHbaseClient(func(client *hbase.Client) (interface{}, error) {
return client.DescribeIpWhitelist(request)
})
response, _ := raw.(*hbase.DescribeIpWhitelistResponse)
if err != nil {
if IsExpectedErrors(err, []string{"Instance.NotFound"}) {
return instance, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return instance, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return *response, nil
}
func (s *HBaseService) DescribeSecurityGroups(id string) (object hbase.DescribeSecurityGroupsResponse, err error) {
request := hbase.CreateDescribeSecurityGroupsRequest()
request.RegionId = s.client.RegionId
request.ClusterId = id
raw, err := s.client.WithHbaseClient(func(client *hbase.Client) (interface{}, error) {
return client.DescribeSecurityGroups(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*hbase.DescribeSecurityGroupsResponse)
return *response, nil
}
func (s *HBaseService) HBaseClusterStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeHBaseInstance(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *HBaseService) ModifyClusterDeletionProtection(clusterId string, protection bool) error {
request := hbase.CreateModifyClusterDeletionProtectionRequest()
request.ClusterId = clusterId
request.Protection = requests.NewBoolean(protection)
raw, err := s.client.WithHbaseClient(func(client *hbase.Client) (interface{}, error) {
return client.ModifyClusterDeletionProtection(request)
})
if err != nil {
return WrapErrorf(err, clusterId+" modifyClusterDeletionProtection failed")
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}
func (s *HBaseService) DescribeEndpoints(id string) (object hbase.DescribeEndpointsResponse, err error) {
request := hbase.CreateDescribeEndpointsRequest()
request.RegionId = s.client.RegionId
request.ClusterId = id
raw, err := s.client.WithHbaseClient(func(client *hbase.Client) (interface{}, error) {
return client.DescribeEndpoints(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*hbase.DescribeEndpointsResponse)
return *response, nil
}
func (s *HBaseService) DescribeClusterConnection(id string) (object hbase.DescribeClusterConnectionResponse, err error) {
request := hbase.CreateDescribeClusterConnectionRequest()
request.RegionId = s.client.RegionId
request.ClusterId = id
raw, err := s.client.WithHbaseClient(func(client *hbase.Client) (interface{}, error) {
return client.DescribeClusterConnection(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*hbase.DescribeClusterConnectionResponse)
return *response, nil
}
package alicloud
import (
"encoding/json"
"fmt"
"reflect"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type HbrService struct {
client *connectivity.AliyunClient
}
func (s *HbrService) convertDetailToString(details []interface{}) (string, error) {
configRulesMap := make(map[string]interface{})
for _, configRules := range details {
configRulesArg := configRules.(map[string]interface{})
configRulesMap["enableWriters"] = true
configRulesMap["appConsistent"] = configRulesArg["app_consistent"]
configRulesMap["snapshotGroup"] = configRulesArg["snapshot_group"]
configRulesMap["EnableFsFreeze"] = configRulesArg["enable_fs_freeze"]
configRulesMap["preScriptPath"] = configRulesArg["pre_script_path"]
configRulesMap["postScriptPath"] = configRulesArg["post_script_path"]
configRulesMap["timeoutInSeconds"] = configRulesArg["timeout_in_seconds"]
configRulesMap["doCopy"] = configRulesArg["do_copy"]
if configRulesArg["destination_region_id"] != "" {
configRulesMap["destinationRegionId"] = configRulesArg["destination_region_id"]
}
configRulesMap["destinationRetention"] = configRulesArg["destination_retention"]
diskListArg := make([]interface{}, 0)
if configRulesArg["disk_id_list"] != nil {
diskListArg = append(diskListArg, configRulesArg["disk_id_list"].([]interface{})...)
configRulesMap["diskIdList"] = diskListArg
}
}
if v, err := convertArrayObjectToJsonString(configRulesMap); err != nil {
return "", WrapError(err)
} else {
return v, nil
}
}
func (s *HbrService) DescribeHbrVault(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHbrClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeVaults"
request := map[string]interface{}{
"VaultRegionId": s.client.RegionId,
"VaultId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.Vaults.Vault", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Vaults.Vault", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("HBR", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["VaultId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("HBR", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *HbrService) HbrVaultStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeHbrVault(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *HbrService) DescribeHbrEcsBackupPlan(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHbrClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeBackupPlans"
request := map[string]interface{}{
"SourceType": "ECS_FILE",
}
filtersMapList := make([]map[string]interface{}, 0)
filtersMapList = append(filtersMapList, map[string]interface{}{
"Key": "planId",
"Values": []string{id},
})
request["Filters"] = filtersMapList
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.BackupPlans.BackupPlan", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.BackupPlans.BackupPlan", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("HBR", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["PlanId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("HBR", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *HbrService) DescribeHbrNasBackupPlan(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHbrClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeBackupPlans"
request := map[string]interface{}{
"SourceType": "NAS",
}
filtersMapList := make([]map[string]interface{}, 0)
filtersMapList = append(filtersMapList, map[string]interface{}{
"Key": "planId",
"Values": []string{id},
})
request["Filters"] = filtersMapList
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.BackupPlans.BackupPlan", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.BackupPlans.BackupPlan", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("HBR", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["PlanId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("HBR", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *HbrService) DescribeHbrOssBackupPlan(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHbrClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeBackupPlans"
request := map[string]interface{}{
"SourceType": "OSS",
"PageNumber": 1,
"PageSize": 100,
}
filtersMapList := make([]map[string]interface{}, 0)
request["Filters"] = filtersMapList
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.BackupPlans.BackupPlan", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.BackupPlans.BackupPlan", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("HBR", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["PlanId"]) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("HBR", id)), NotFoundWithResponse, response)
}
return
}
type InstallClientTaskStatus struct {
InstanceId string `json:"instanceId"`
ClientId string `json:"clientId"`
ClientStatus string `json:"clientStatus"`
ErrorCode string `json:"errorCode"`
}
func (s *HbrService) DescribeHbrTask(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHbrClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeTask"
request := map[string]interface{}{
"TaskId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
if fmt.Sprint(response["Description"]) == "cancelled" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.Result", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Result", response)
}
var taskStatus []InstallClientTaskStatus
resultJson := v.(string)
if resultJson == "" {
return object, WrapErrorf(Error(GetNotFoundMessage("HBR", id)), NotFoundWithResponse, response)
}
err = json.Unmarshal([]byte(resultJson), &taskStatus)
if len(taskStatus) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("HBR", id)), NotFoundWithResponse, response)
}
object = make(map[string]interface{})
ty := reflect.TypeOf(taskStatus[0])
tv := reflect.ValueOf(taskStatus[0])
for i := 0; i < tv.NumField(); i++ {
object[ty.Field(i).Name] = tv.Field(i).Interface()
}
return object, nil
}
func (s *HbrService) HbrTaskRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeHbrTask(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["ClientStatus"]) == failState {
return object, fmt.Sprint(object["ClientStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["ClientStatus"])))
}
}
return object, fmt.Sprint(object["ClientStatus"]), nil
}
}
func (s *HbrService) DescribeHbrEcsBackupClient(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHbrClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeBackupClients"
request := map[string]interface{}{
"ClientIds": "[\"" + id + "\"]",
"ClientType": "ECS_CLIENT",
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.Clients", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Clients", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("HBR", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["ClientId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("HBR", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *HbrService) HbrEcsBackupClientStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeHbrEcsBackupClient(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *HbrService) DescribeHbrRestoreJob(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHbrClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeRestoreJobs2"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RestoreType": parts[1],
"PageSize": 50,
"PageNumber": 1,
}
filtersMapList := make([]map[string]interface{}, 0)
request["Filters"] = filtersMapList
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.RestoreJobs.RestoreJob", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.RestoreJobs.RestoreJob", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("HBR", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["RestoreId"]) == parts[0] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("HBR", id)), NotFoundWithResponse, response)
}
return
}
func (s *HbrService) HbrRestoreJobStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeHbrRestoreJob(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *HbrService) DescribeHbrServerBackupPlan(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHbrClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeBackupPlans"
request := map[string]interface{}{
"SourceType": "UDM_ECS",
"PageNumber": 1,
"PageSize": PageSizeLarge,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.BackupPlans.BackupPlan", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.BackupPlans.BackupPlan", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("HBR", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["PlanId"]) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("HBR", id)), NotFoundWithResponse, response)
}
return
}
func (s *HbrService) DescribeHbrReplicationVault(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHbrClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeVaults"
request := map[string]interface{}{
"PageSize": 10,
"PageNumber": 1,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-08"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.Vaults.Vault", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Vaults.Vault", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("HBR", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["VaultId"]) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("HBR", id)), NotFoundWithResponse, response)
}
return
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type HitsdbService struct {
client *connectivity.AliyunClient
}
func (s *HitsdbService) DescribeTsdbInstance(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHitsdbClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeHiTSDBInstance"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"InstanceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"Instance.IsNotValidError", "TSDB.Errorcode.InstanceDeleted", "TSDB.Errorcode.InstanceNotFound", "TSDB.Errorcode.ParameterInvaild"}) {
err = WrapErrorf(Error(GetNotFoundMessage("TsdbInstance", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *HitsdbService) TsdbInstanceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeTsdbInstance(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["Status"].(string) == failState {
return object, object["Status"].(string), WrapError(Error(FailedToReachTargetStatus, object["Status"].(string)))
}
}
return object, object["Status"].(string), nil
}
}
func (s *HitsdbService) GetInstanceIpWhiteList(id string) (object []interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHitsdbClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetInstanceIpWhiteList"
request := map[string]interface{}{
"InstanceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.IpList", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.IpList", response)
}
if len(v.([]interface{})) < 1 {
return object, nil
} else {
if fmt.Sprint(response["InstanceId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("Lindorm", id)), NotFoundWithResponse, response)
}
}
return v.([]interface{}), nil
}
func (s *HitsdbService) GetLindormInstanceEngineInfo(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHitsdbClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetLindormInstanceEngineInfo"
request := map[string]interface{}{
"InstanceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *HitsdbService) DescribeLindormInstance(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHitsdbClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetLindormInstance"
request := map[string]interface{}{
"InstanceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Lindorm.Errorcode.InstanceNotFound", "Instance.IsDeleted"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Lindorm:Instance", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *HitsdbService) LindormInstanceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeLindormInstance(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["InstanceStatus"]) == failState {
return object, fmt.Sprint(object["InstanceStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["InstanceStatus"])))
}
}
return object, fmt.Sprint(object["InstanceStatus"]), nil
}
}
func (s *HitsdbService) GetLindormInstance(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHitsdbClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetLindormInstance"
request := map[string]interface{}{
"InstanceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Lindorm.Errorcode.InstanceNotFound", "Instance.IsDeleted"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Lindorm:Instance", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type ImmService struct {
client *connectivity.AliyunClient
}
func (s *ImmService) DescribeImmProject(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewImmClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetProject"
request := map[string]interface{}{
"Project": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-09-06"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidProject.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("IMM:Project", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type ImpService struct {
client *connectivity.AliyunClient
}
func (s *ImpService) DescribeImpAppTemplate(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewImpClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetAppTemplate"
request := map[string]interface{}{
"AppTemplateId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2021-06-30"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidAppTemplateId.App.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("IMP:AppTemplate", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Result", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Result", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
)
type ImsService struct {
client *connectivity.AliyunClient
}
func (s *ImsService) DescribeRamSamlProvider(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewImsClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetSAMLProvider"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"SAMLProviderName": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist.SAMLProviderError"}) {
err = WrapErrorf(Error(GetNotFoundMessage("RamSamlProvider", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.SAMLProvider", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.SAMLProvider", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type IotService struct {
client *connectivity.AliyunClient
}
func (s *IotService) DescribeIotDeviceGroup(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewIotClient()
if err != nil {
return nil, WrapError(err)
}
action := "QueryDeviceGroupInfo"
request := map[string]interface{}{
"GroupId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if IsExpectedErrorCodes(fmt.Sprint(response["Code"]), []string{"iot.group.QueryGroupInfoFailed"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Iot:DeviceGroup", id)), NotFoundMsg, ProviderERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"encoding/json"
"fmt"
"log"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type KmsService struct {
client *connectivity.AliyunClient
}
func (s *KmsService) DescribeKmsKey(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewKmsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeKey"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"KeyId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Forbidden.AliasNotFound", "Forbidden.KeyNotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("KMS:Key", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.KeyMetadata", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.KeyMetadata", response)
}
object = v.(map[string]interface{})
if object["KeyState"] == "PendingDeletion" {
log.Printf("[WARN] Removing KmsKey %s because it's already gone", id)
return object, WrapErrorf(Error(GetNotFoundMessage("KmsKey", id)), NotFoundMsg, ProviderERROR)
}
return object, nil
}
func (s *KmsService) Decrypt(ciphertextBlob string, encryptionContext map[string]interface{}) (plaintext string, err error) {
context, err := json.Marshal(encryptionContext)
if err != nil {
return plaintext, WrapError(err)
}
var response map[string]interface{}
conn, err := s.client.NewKmsClient()
if err != nil {
return plaintext, WrapError(err)
}
action := "Decrypt"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"CiphertextBlob": ciphertextBlob,
"EncryptionContext": string(context[:]),
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return plaintext, WrapErrorf(err, DefaultErrorMsg, context, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Plaintext", response)
if err != nil {
return plaintext, WrapErrorf(err, FailedGetAttributeMsg, context, "$.Plaintext", response)
}
return fmt.Sprint(v), err
}
func (s *KmsService) DescribeKmsSecret(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewKmsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeSecret"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"SecretName": id,
"FetchTags": "true",
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Forbidden.ResourceNotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("KMS:Secret", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *KmsService) GetSecretValue(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewKmsClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetSecretValue"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"SecretName": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *KmsService) DescribeKmsAlias(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewKmsClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListAliases"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"PageNumber": 1,
"PageSize": 20,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Aliases.Alias", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Aliases.Alias", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("KMS", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if v.(map[string]interface{})["AliasName"].(string) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("KMS", id)), NotFoundWithResponse, response)
}
return
}
func (s *KmsService) DescribeKmsKeyVersion(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewKmsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeKeyVersion"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"KeyId": parts[0],
"KeyVersionId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.KeyVersion", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.KeyVersion", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *KmsService) SetResourceTags(d *schema.ResourceData, resourceType string) error {
oldItems, newItems := d.GetChange("tags")
added := make([]JsonTag, 0)
for key, value := range newItems.(map[string]interface{}) {
added = append(added, JsonTag{
TagKey: key,
TagValue: value.(string),
})
}
removed := make([]string, 0)
for key, _ := range oldItems.(map[string]interface{}) {
removed = append(removed, key)
}
// 对系统 Tag 进行过滤
removedTagKeys := make([]string, 0)
for _, v := range removed {
if !ignoredTags(v, "") {
removedTagKeys = append(removedTagKeys, v)
}
}
if len(removedTagKeys) > 0 {
var response map[string]interface{}
conn, err := s.client.NewKmsClient()
if err != nil {
return WrapError(err)
}
action := "UntagResource"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
}
if resourceType == "key" {
request["KeyId"] = d.Id()
}
if resourceType == "secret" {
request["SecretName"] = d.Id()
}
remove, err := json.Marshal(removed)
if err != nil {
return WrapError(err)
}
request["TagKeys"] = string(remove)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
var response map[string]interface{}
conn, err := s.client.NewKmsClient()
if err != nil {
return WrapError(err)
}
action := "TagResource"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
}
if resourceType == "key" {
request["KeyId"] = d.Id()
}
if resourceType == "secret" {
request["SecretName"] = d.Id()
}
add, err := json.Marshal(added)
if err != nil {
return WrapError(err)
}
request["Tags"] = string(add)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-01-20"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
return nil
}
package alicloud
import (
"log"
"regexp"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
r_kvstore "github.com/aliyun/alibaba-cloud-sdk-go/services/r-kvstore"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
)
type KvstoreService struct {
client *connectivity.AliyunClient
}
var KVstoreInstanceStatusCatcher = Catcher{"OperationDenied.KVstoreInstanceStatus", 60, 5}
func (s *KvstoreService) DescribeKVstoreInstance(id string) (*r_kvstore.DBInstanceAttribute, error) {
instance := &r_kvstore.DBInstanceAttribute{}
request := r_kvstore.CreateDescribeInstanceAttributeRequest()
request.RegionId = s.client.RegionId
request.InstanceId = id
raw, err := s.client.WithRkvClient(func(rkvClient *r_kvstore.Client) (interface{}, error) {
return rkvClient.DescribeInstanceAttribute(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidInstanceId.NotFound"}) {
return instance, WrapErrorf(Error(GetNotFoundMessage("KVstoreInstance", id)), NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return instance, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*r_kvstore.DescribeInstanceAttributeResponse)
if len(response.Instances.DBInstanceAttribute) <= 0 {
return instance, WrapErrorf(Error(GetNotFoundMessage("KVstoreInstance", id)), NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return &response.Instances.DBInstanceAttribute[0], nil
}
func (s *KvstoreService) DescribeKVstoreBackupPolicy(id string) (*r_kvstore.DescribeBackupPolicyResponse, error) {
response := &r_kvstore.DescribeBackupPolicyResponse{}
request := r_kvstore.CreateDescribeBackupPolicyRequest()
request.RegionId = s.client.RegionId
request.InstanceId = id
raw, err := s.client.WithRkvClient(func(rkvClient *r_kvstore.Client) (interface{}, error) {
return rkvClient.DescribeBackupPolicy(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidInstanceId.NotFound"}) {
return response, WrapErrorf(Error(GetNotFoundMessage("KVstoreBackupPolicy", id)), NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*r_kvstore.DescribeBackupPolicyResponse)
return response, nil
}
func (s *KvstoreService) WaitForKVstoreInstance(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeKVstoreInstance(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.InstanceStatus == string(status) {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.InstanceStatus, status, ProviderERROR)
}
}
return nil
}
func (s *KvstoreService) RdsKvstoreInstanceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeKVstoreInstance(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.InstanceStatus == failState {
return object, object.InstanceStatus, WrapError(Error(FailedToReachTargetStatus, object.InstanceStatus))
}
}
return object, object.InstanceStatus, nil
}
}
func (s *KvstoreService) WaitForKVstoreInstanceVpcAuthMode(id string, status string, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeKVstoreInstance(id)
if err != nil && !NotFoundError(err) {
return err
}
if object.VpcAuthMode == string(status) {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.VpcAuthMode, status, ProviderERROR)
}
}
return nil
}
func (s *KvstoreService) DescribeParameters(id string) (*r_kvstore.DescribeParametersResponse, error) {
response := &r_kvstore.DescribeParametersResponse{}
request := r_kvstore.CreateDescribeParametersRequest()
request.RegionId = s.client.RegionId
request.DBInstanceId = id
raw, err := s.client.WithRkvClient(func(rkvClient *r_kvstore.Client) (interface{}, error) {
return rkvClient.DescribeParameters(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound"}) {
return response, WrapErrorf(Error(GetNotFoundMessage("Parameters", id)), NotFoundMsg, ProviderERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*r_kvstore.DescribeParametersResponse)
return response, nil
}
func (s *KvstoreService) ModifyInstanceConfig(id string, config string) error {
request := r_kvstore.CreateModifyInstanceConfigRequest()
request.RegionId = s.client.RegionId
request.InstanceId = id
request.Config = config
if err := s.WaitForKVstoreInstance(id, Normal, DefaultLongTimeout); err != nil {
return WrapError(err)
}
raw, err := s.client.WithRkvClient(func(rkvClient *r_kvstore.Client) (interface{}, error) {
return rkvClient.ModifyInstanceConfig(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}
func (s *KvstoreService) setInstanceTags(d *schema.ResourceData) error {
if d.HasChange("tags") {
oraw, nraw := d.GetChange("tags")
o := oraw.(map[string]interface{})
n := nraw.(map[string]interface{})
create, remove := s.diffTags(s.tagsFromMap(o), s.tagsFromMap(n))
if len(remove) > 0 {
var tagKey []string
for _, v := range remove {
tagKey = append(tagKey, v.Key)
}
request := r_kvstore.CreateUntagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.ResourceType = strings.ToUpper(string(TagResourceInstance))
request.TagKey = &tagKey
request.RegionId = s.client.RegionId
raw, err := s.client.WithRkvClient(func(client *r_kvstore.Client) (interface{}, error) {
return client.UntagResources(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
if len(create) > 0 {
request := r_kvstore.CreateTagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.Tag = &create
request.ResourceType = strings.ToUpper(string(TagResourceInstance))
request.RegionId = s.client.RegionId
raw, err := s.client.WithRkvClient(func(client *r_kvstore.Client) (interface{}, error) {
return client.TagResources(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
d.SetPartial("tags")
}
return nil
}
func (s *KvstoreService) tagsToMap(tags []r_kvstore.TagResource) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !s.ignoreTag(t) {
result[t.TagKey] = t.TagValue
}
}
return result
}
func (s *KvstoreService) tagsFromMap(m map[string]interface{}) []r_kvstore.TagResourcesTag {
result := make([]r_kvstore.TagResourcesTag, 0, len(m))
for k, v := range m {
result = append(result, r_kvstore.TagResourcesTag{
Key: k,
Value: v.(string),
})
}
return result
}
func (s *KvstoreService) ignoreTag(t r_kvstore.TagResource) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, t.TagKey)
ok, _ := regexp.MatchString(v, t.TagValue)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific t %s (val: %s), ignoring.\n", t.TagKey, t.TagValue)
return true
}
}
return false
}
func (s *KvstoreService) diffTags(oldTags, newTags []r_kvstore.TagResourcesTag) ([]r_kvstore.TagResourcesTag, []r_kvstore.TagResourcesTag) {
// First, we're creating everything we have
create := make(map[string]interface{})
for _, t := range newTags {
create[t.Key] = t.Value
}
// Build the list of what to remove
var remove []r_kvstore.TagResourcesTag
for _, t := range oldTags {
old, ok := create[t.Key]
if !ok || old != t.Value {
// Delete it!
remove = append(remove, t)
}
}
return s.tagsFromMap(create), remove
}
func (s *KvstoreService) DescribeTags(resourceId string, resourceType TagResourceType) (tags []r_kvstore.TagResource, err error) {
request := r_kvstore.CreateListTagResourcesRequest()
request.RegionId = s.client.RegionId
request.ResourceType = strings.ToUpper(string(resourceType))
request.ResourceId = &[]string{resourceId}
raw, err := s.client.WithRkvClient(func(rkvClient *r_kvstore.Client) (interface{}, error) {
return rkvClient.ListTagResources(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, resourceId, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*r_kvstore.ListTagResourcesResponse)
return response.TagResources.TagResource, nil
}
func (s *KvstoreService) WaitForKVstoreAccount(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeKVstoreAccount(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object != nil && object.AccountStatus == string(status) {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.AccountStatus, status, ProviderERROR)
}
}
return nil
}
func (s *KvstoreService) DescribeKVstoreAccount(id string) (*r_kvstore.Account, error) {
ds := &r_kvstore.Account{}
parts, err := ParseResourceId(id, 2)
if err != nil {
return ds, WrapError(err)
}
request := r_kvstore.CreateDescribeAccountsRequest()
request.RegionId = s.client.RegionId
request.InstanceId = parts[0]
request.AccountName = parts[1]
invoker := NewInvoker()
invoker.AddCatcher(KVstoreInstanceStatusCatcher)
var response *r_kvstore.DescribeAccountsResponse
if err := invoker.Run(func() error {
raw, err := s.client.WithRkvClient(func(rkvClient *r_kvstore.Client) (interface{}, error) {
return rkvClient.DescribeAccounts(request)
})
if err != nil {
return err
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*r_kvstore.DescribeAccountsResponse)
return nil
}); err != nil {
if IsExpectedErrors(err, []string{"InvalidInstanceId.NotFound"}) {
return ds, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return ds, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
if len(response.Accounts.Account) < 1 {
return ds, WrapErrorf(Error(GetNotFoundMessage("KVstoreAccount", id)), NotFoundMsg, ProviderERROR)
}
return &response.Accounts.Account[0], nil
}
func (s *KvstoreService) DescribeKVstoreSecurityGroupId(id string) (*r_kvstore.DescribeSecurityGroupConfigurationResponse, error) {
response := &r_kvstore.DescribeSecurityGroupConfigurationResponse{}
request := r_kvstore.CreateDescribeSecurityGroupConfigurationRequest()
request.RegionId = s.client.RegionId
request.InstanceId = id
if err := s.WaitForKVstoreInstance(id, Normal, DefaultLongTimeout); err != nil {
return response, WrapError(err)
}
raw, err := s.client.WithRkvClient(func(rkvClient *r_kvstore.Client) (interface{}, error) {
return rkvClient.DescribeSecurityGroupConfiguration(request)
})
if err != nil {
return response, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*r_kvstore.DescribeSecurityGroupConfigurationResponse)
return response, nil
}
func (s *KvstoreService) DescribeDBInstanceNetInfo(id string) (*r_kvstore.NetInfoItemsInDescribeDBInstanceNetInfo, error) {
response := &r_kvstore.DescribeDBInstanceNetInfoResponse{}
request := r_kvstore.CreateDescribeDBInstanceNetInfoRequest()
request.RegionId = s.client.RegionId
request.InstanceId = id
if err := s.WaitForKVstoreInstance(id, Normal, DefaultLongTimeout); err != nil {
return &response.NetInfoItems, WrapError(err)
}
raw, err := s.client.WithRkvClient(func(rkvClient *r_kvstore.Client) (interface{}, error) {
return rkvClient.DescribeDBInstanceNetInfo(request)
})
if err != nil {
return &response.NetInfoItems, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*r_kvstore.DescribeDBInstanceNetInfoResponse)
return &response.NetInfoItems, nil
}
package alicloud
import (
"fmt"
"time"
slsPop "github.com/aliyun/alibaba-cloud-sdk-go/services/sls"
sls "github.com/aliyun/aliyun-log-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
var SlsClientTimeoutCatcher = Catcher{LogClientTimeout, 15, 5}
type LogService struct {
client *connectivity.AliyunClient
}
func (s *LogService) DescribeLogProject(id string) (*sls.LogProject, error) {
project := &sls.LogProject{}
var requestInfo *sls.Client
err := resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return slsClient.GetProject(id)
})
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout, "ProjectForbidden"}) {
time.Sleep(5 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if debugOn() {
addDebug("GetProject", raw, requestInfo, map[string]string{"name": id})
}
project, _ = raw.(*sls.LogProject)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ProjectNotExist"}) {
return project, WrapErrorf(err, NotFoundMsg, AliyunLogGoSdkERROR)
}
return project, WrapErrorf(err, DefaultErrorMsg, id, "GetProject", AliyunLogGoSdkERROR)
}
if project == nil || project.Name == "" {
return project, WrapErrorf(Error(GetNotFoundMessage("LogProject", id)), NotFoundMsg, ProviderERROR)
}
return project, nil
}
func (s *LogService) WaitForLogProject(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeLogProject(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.Name == id && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.Name, id, ProviderERROR)
}
}
}
func (s *LogService) DescribeLogStore(id string) (*sls.LogStore, error) {
store := &sls.LogStore{}
parts, err := ParseResourceId(id, 2)
if err != nil {
return store, WrapError(err)
}
projectName, name := parts[0], parts[1]
var requestInfo *sls.Client
err = resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return slsClient.GetLogStore(projectName, name)
})
if err != nil {
if IsExpectedErrors(err, []string{"InternalServerError", LogClientTimeout}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if debugOn() {
addDebug("GetLogStore", raw, requestInfo, map[string]string{
"project": projectName,
"logstore": name,
})
}
store, _ = raw.(*sls.LogStore)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ProjectNotExist", "LogStoreNotExist"}) {
return store, WrapErrorf(err, NotFoundMsg, AliyunLogGoSdkERROR)
}
return store, WrapErrorf(err, DefaultErrorMsg, id, "GetLogStore", AliyunLogGoSdkERROR)
}
if store == nil || store.Name == "" {
return store, WrapErrorf(Error(GetNotFoundMessage("LogStore", id)), NotFoundMsg, ProviderERROR)
}
return store, nil
}
func (s *LogService) WaitForLogStore(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
parts, err := ParseResourceId(id, 2)
if err != nil {
return WrapError(err)
}
name := parts[1]
for {
object, err := s.DescribeLogStore(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.Name == name && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.Name, name, ProviderERROR)
}
}
}
func (s *LogService) DescribeLogStoreIndex(id string) (*sls.Index, error) {
index := &sls.Index{}
parts, err := ParseResourceId(id, 2)
if err != nil {
return index, WrapError(err)
}
projectName, name := parts[0], parts[1]
var requestInfo *sls.Client
err = resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return slsClient.GetIndex(projectName, name)
})
if err != nil {
if IsExpectedErrors(err, []string{"InternalServerError", LogClientTimeout}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if debugOn() {
addDebug("GetIndex", raw, requestInfo, map[string]string{
"project": projectName,
"logstore": name,
})
}
index, _ = raw.(*sls.Index)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ProjectNotExist", "LogStoreNotExist", "IndexConfigNotExist"}) {
return index, WrapErrorf(err, NotFoundMsg, AliyunLogGoSdkERROR)
}
return index, WrapErrorf(err, DefaultErrorMsg, id, "GetIndex", AliyunLogGoSdkERROR)
}
if index == nil || (index.Line == nil && index.Keys == nil) {
return index, WrapErrorf(Error(GetNotFoundMessage("LogStoreIndex", id)), NotFoundMsg, ProviderERROR)
}
return index, nil
}
func (s *LogService) DescribeLogMachineGroup(id string) (*sls.MachineGroup, error) {
group := &sls.MachineGroup{}
parts, err := ParseResourceId(id, 2)
if err != nil {
return group, WrapError(err)
}
projectName, groupName := parts[0], parts[1]
var requestInfo *sls.Client
err = resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return slsClient.GetMachineGroup(projectName, groupName)
})
if err != nil {
if IsExpectedErrors(err, []string{"InternalServerError", LogClientTimeout}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if debugOn() {
addDebug("GetMachineGroup", raw, requestInfo, map[string]string{
"project": projectName,
"machineGroup": groupName,
})
}
group, _ = raw.(*sls.MachineGroup)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ProjectNotExist", "GroupNotExist", "MachineGroupNotExist"}) {
return group, WrapErrorf(err, NotFoundMsg, AliyunLogGoSdkERROR)
}
return group, WrapErrorf(err, DefaultErrorMsg, id, "GetMachineGroup", AliyunLogGoSdkERROR)
}
if group == nil || group.Name == "" {
return group, WrapErrorf(Error(GetNotFoundMessage("LogMachineGroup", id)), NotFoundMsg, ProviderERROR)
}
return group, nil
}
func (s *LogService) WaitForLogMachineGroup(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
parts, err := ParseResourceId(id, 2)
if err != nil {
return WrapError(err)
}
name := parts[1]
for {
object, err := s.DescribeLogMachineGroup(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.Name == name && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.Name, name, ProviderERROR)
}
}
}
func (s *LogService) DescribeLogtailConfig(id string) (*sls.LogConfig, error) {
response := &sls.LogConfig{}
parts, err := ParseResourceId(id, 3)
if err != nil {
return response, WrapError(err)
}
projectName, configName := parts[0], parts[2]
var requestInfo *sls.Client
err = resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return slsClient.GetConfig(projectName, configName)
})
if err != nil {
if IsExpectedErrors(err, []string{"InternalServerError"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if debugOn() {
addDebug("GetConfig", raw, requestInfo, map[string]string{
"project": projectName,
"config": configName,
})
}
response, _ = raw.(*sls.LogConfig)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ProjectNotExist", "LogStoreNotExist", "ConfigNotExist"}) {
return response, WrapErrorf(err, NotFoundMsg, AliyunLogGoSdkERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, "GetConfig", AliyunLogGoSdkERROR)
}
if response == nil || response.Name == "" {
return response, WrapErrorf(Error(GetNotFoundMessage("LogTailConfig", id)), NotFoundMsg, ProviderERROR)
}
return response, nil
}
func (s *LogService) WaitForLogtailConfig(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
parts, err := ParseResourceId(id, 3)
if err != nil {
return WrapError(err)
}
name := parts[2]
for {
object, err := s.DescribeLogtailConfig(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.Name == name && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.Name, name, ProviderERROR)
}
}
}
func (s *LogService) DescribeLogtailAttachment(id string) (groupName string, err error) {
parts, err := ParseResourceId(id, 3)
if err != nil {
return groupName, WrapError(err)
}
projectName, configName, name := parts[0], parts[1], parts[2]
var groupNames []string
var requestInfo *sls.Client
err = resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return slsClient.GetAppliedMachineGroups(projectName, configName)
})
if err != nil {
if IsExpectedErrors(err, []string{"InternalServerError"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if debugOn() {
addDebug("GetAppliedMachineGroups", raw, requestInfo, map[string]string{
"project": projectName,
"confName": configName,
})
}
groupNames, _ = raw.([]string)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ProjectNotExist", "ConfigNotExist", "MachineGroupNotExist"}) {
return groupName, WrapErrorf(err, NotFoundMsg, AliyunLogGoSdkERROR)
}
return groupName, WrapErrorf(err, DefaultErrorMsg, id, "GetAppliedMachineGroups", AliyunLogGoSdkERROR)
}
for _, group_name := range groupNames {
if group_name == name {
groupName = group_name
}
}
if groupName == "" {
return groupName, WrapErrorf(Error(GetNotFoundMessage("LogtailAttachment", id)), NotFoundMsg, ProviderERROR)
}
return groupName, nil
}
func (s *LogService) WaitForLogtailAttachment(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
parts, err := ParseResourceId(id, 3)
if err != nil {
return WrapError(err)
}
name := parts[2]
for {
object, err := s.DescribeLogtailAttachment(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object == name && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object, name, ProviderERROR)
}
}
}
func (s *LogService) DescribeLogAlert(id string) (*sls.Alert, error) {
alert := &sls.Alert{}
parts, err := ParseResourceId(id, 2)
if err != nil {
return alert, WrapError(err)
}
projectName, alertName := parts[0], parts[1]
var requestInfo *sls.Client
err = resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return slsClient.GetAlert(projectName, alertName)
})
if err != nil {
if IsExpectedErrors(err, []string{"InternalServerError", LogClientTimeout}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if debugOn() {
addDebug("GetLogstoreAlert", raw, requestInfo, map[string]string{
"project": projectName,
"alert_name": alertName,
})
}
alert, _ = raw.(*sls.Alert)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ProjectNotExist", "JobNotExist"}) {
return alert, WrapErrorf(err, NotFoundMsg, AliyunLogGoSdkERROR)
}
return alert, WrapErrorf(err, DefaultErrorMsg, id, "GetLogstoreAlert", AliyunLogGoSdkERROR)
}
if alert == nil || alert.Name == "" {
return alert, WrapErrorf(Error(GetNotFoundMessage("LogstoreAlert", id)), NotFoundMsg, ProviderERROR)
}
return alert, nil
}
func (s *LogService) WaitForLogstoreAlert(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
parts, err := ParseResourceId(id, 2)
if err != nil {
return WrapError(err)
}
name := parts[1]
for {
object, err := s.DescribeLogAlert(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.Name == name && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.Name, name, ProviderERROR)
}
}
}
func (s *LogService) CreateLogDashboard(project, name string) error {
dashboard := sls.Dashboard{
DashboardName: name,
ChartList: []sls.Chart{},
}
err := resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
return nil, slsClient.CreateDashboard(project, dashboard)
})
if err != nil {
if IsExpectedErrors(err, []string{"InternalServerError", LogClientTimeout}) {
return resource.RetryableError(err)
}
if err.(*sls.Error).Message == "specified dashboard already exists" {
return nil
}
return resource.NonRetryableError(err)
}
if debugOn() {
addDebug("CreateLogDashboard", raw, map[string]string{
"project": project,
"dashboard_name": name,
})
}
return nil
})
if err != nil {
return err
}
return nil
}
func CreateDashboard(project, name string, client *sls.Client) error {
dashboard := sls.Dashboard{
DashboardName: name,
ChartList: []sls.Chart{},
}
err := resource.Retry(2*time.Minute, func() *resource.RetryError {
err := client.CreateDashboard(project, dashboard)
if err != nil {
if err.(*sls.Error).Message == "specified dashboard already exists" {
return nil
}
if IsExpectedErrors(err, []string{"InternalServerError", LogClientTimeout}) {
return resource.RetryableError(err)
}
}
if debugOn() {
addDebug("CreateLogDashboard", dashboard, map[string]string{
"project": project,
"dashboard_name": name,
})
}
return nil
})
return err
}
func (s *LogService) DescribeLogAudit(id string) (*slsPop.DescribeAppResponse, error) {
request := slsPop.CreateDescribeAppRequest()
response := &slsPop.DescribeAppResponse{}
request.AppName = "audit"
raw, err := s.client.WithLogPopClient(func(client *slsPop.Client) (interface{}, error) {
return client.DescribeApp(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"AppNotExist"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*slsPop.DescribeAppResponse)
return response, nil
}
func GetCharTitile(project, dashboard, char string, client *sls.Client) string {
board, err := client.GetDashboard(project, dashboard)
// If the query fails to ignore the error, return the original value.
if err != nil {
return char
}
for _, v := range board.ChartList {
if v.Display.DisplayName == char {
return v.Title
} else {
return char
}
}
return char
}
func (s *LogService) DescribeLogDashboard(id string) (*sls.Dashboard, error) {
dashboard := &sls.Dashboard{}
parts, err := ParseResourceId(id, 2)
if err != nil {
return dashboard, WrapError(err)
}
projectName, dashboardName := parts[0], parts[1]
var requestInfo *sls.Client
err = resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return slsClient.GetDashboard(projectName, dashboardName)
})
if err != nil {
if IsExpectedErrors(err, []string{"InternalServerError", LogClientTimeout}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if debugOn() {
addDebug("GetLogstoreDashboard", raw, requestInfo, map[string]string{
"project": projectName,
"dashboard_name": dashboardName,
})
}
dashboard, _ = raw.(*sls.Dashboard)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ProjectNotExist", "DashboardNotExist"}) {
return dashboard, WrapErrorf(err, NotFoundMsg, AliyunLogGoSdkERROR)
}
return dashboard, WrapErrorf(err, DefaultErrorMsg, id, "GetLogstoreDashboard", AliyunLogGoSdkERROR)
}
if dashboard == nil || dashboard.DashboardName == "" {
return dashboard, WrapErrorf(Error(GetNotFoundMessage("LogstoreDashboard", id)), NotFoundMsg, ProviderERROR)
}
return dashboard, nil
}
func (s *LogService) WaitForLogDashboard(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
parts, err := ParseResourceId(id, 2)
if err != nil {
return WrapError(err)
}
name := parts[1]
for {
object, err := s.DescribeLogDashboard(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.DashboardName == name && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.DashboardName, name, ProviderERROR)
}
}
}
func (s *LogService) DescribeLogProjectTags(project_name string) ([]*sls.ResourceTagResponse, error) {
var requestInfo *sls.Client
var respTags []*sls.ResourceTagResponse
err := resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
raw, _, err := slsClient.ListTagResources(project_name, "project", []string{project_name}, []sls.ResourceFilterTag{}, "")
return raw, err
})
if err != nil {
if IsExpectedErrors(err, []string{LogClientTimeout}) {
time.Sleep(5 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if debugOn() {
addDebug("GetProjectTags", raw, requestInfo, map[string]string{"project_name": project_name})
}
respTags = raw.([]*sls.ResourceTagResponse)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ProjectNotExist"}) {
return respTags, WrapErrorf(err, NotFoundMsg, AliyunLogGoSdkERROR)
}
return respTags, WrapErrorf(err, DefaultErrorMsg, project_name, "GetProejctTags", AliyunLogGoSdkERROR)
}
return respTags, nil
}
func (s *LogService) DescribeLogEtl(id string) (*sls.ETL, error) {
etl := &sls.ETL{}
parts, err := ParseResourceId(id, 2)
if err != nil {
return etl, WrapError(err)
}
projectName, etlName := parts[0], parts[1]
var requestInfo *sls.Client
err = resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
return slsClient.GetETL(projectName, etlName)
})
if err != nil {
if IsExpectedErrors(err, []string{"InternalServerError", LogClientTimeout}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if debugOn() {
addDebug("GetLogETL", raw, requestInfo, map[string]string{
"project": projectName,
"etl_name": etlName,
})
}
etl, _ = raw.(*sls.ETL)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ProjectNotExist", "JobNotExist"}) {
return etl, WrapErrorf(err, NotFoundMsg, AliyunLogGoSdkERROR)
}
return etl, WrapErrorf(err, DefaultErrorMsg, id, "GetETL", AliyunLogGoSdkERROR)
}
return etl, nil
}
func (s *LogService) WaitForLogETL(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
parts, err := ParseResourceId(id, 2)
if err != nil {
return WrapError(err)
}
for {
object, err := s.DescribeLogEtl(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.Name == parts[1] && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.Name, id, ProviderERROR)
}
}
}
func (s *LogService) LogOssShipperStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeLogEtl(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.Status == failState {
return object, object.Status, WrapError(Error(FailedToReachTargetStatus, object.Status))
}
}
return object, object.Status, nil
}
}
func (s *LogService) DescribeLogOssShipper(id string) (*sls.Shipper, error) {
var shipper *sls.Shipper
parts, err := ParseResourceId(id, 3)
if err != nil {
return shipper, WrapError(err)
}
projectName, logstoreName, shipperName := parts[0], parts[1], parts[2]
var requestInfo *sls.Client
err = resource.Retry(2*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithLogClient(func(slsClient *sls.Client) (interface{}, error) {
requestInfo = slsClient
project, _ := sls.NewLogProject(projectName, slsClient.Endpoint, slsClient.AccessKeyID, slsClient.AccessKeySecret)
project, _ = project.WithToken(slsClient.SecurityToken)
logstore, _ := sls.NewLogStore(logstoreName, project)
return logstore.GetShipper(shipperName)
})
if err != nil {
if IsExpectedErrors(err, []string{"InternalServerError", LogClientTimeout}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
if debugOn() {
addDebug("GetLogOssShipper", raw, requestInfo, map[string]string{
"project_name": projectName,
"logstore_name": logstoreName,
"shipper_name": shipperName,
})
}
shipper, _ = raw.(*sls.Shipper)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ProjectNotExist"}) {
return shipper, WrapErrorf(err, NotFoundMsg, AliyunLogGoSdkERROR)
}
// SLS server problem, temporarily by returning nil value to solve.
if d, ok := err.(*sls.Error); ok {
if d.Message == fmt.Sprintf("shipperName %s does not exist", parts[2]) {
return shipper, WrapErrorf(err, NotFoundMsg, AliyunLogGoSdkERROR)
}
}
return shipper, WrapErrorf(err, DefaultErrorMsg, id, "GetLogOssShipper", AliyunLogGoSdkERROR)
}
return shipper, nil
}
func (s *LogService) WaitForLogOssShipper(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
parts, err := ParseResourceId(id, 3)
if err != nil {
return WrapError(err)
}
for {
object, err := s.DescribeLogOssShipper(id)
if err != nil {
if object == nil {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.ShipperName == parts[2] && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.ShipperName, id, ProviderERROR)
}
}
}
func (s *LogService) LogProjectStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeLogProject(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.Status == failState {
return object, object.Status, WrapError(Error(FailedToReachTargetStatus, object.Status))
}
}
return object, object.Status, nil
}
}
package alicloud
import (
"github.com/aliyun/alibaba-cloud-sdk-go/services/market"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
)
type MarketService struct {
client *connectivity.AliyunClient
}
func (s *MarketService) DescribeMarketOrder(id string) (order *market.DescribeOrderResponse, err error) {
request := market.CreateDescribeOrderRequest()
request.OrderId = id
raw, err := s.client.WithMarketClient(func(client *market.Client) (interface{}, error) {
return client.DescribeOrder(request)
})
response, _ := raw.(*market.DescribeOrderResponse)
if err != nil {
if IsExpectedErrors(err, []string{"null"}) {
return order, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return order, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
if response.OrderId == 0 {
return order, WrapErrorf(Error(GetNotFoundMessage("Market Order", id)), NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, nil
}
func getRegionByImageIdPrefix(imageId string) string {
switch imageId[:5] {
case "m-m5e":
return "cn-qingdao"
case "m-2ze":
return "cn-beijing"
case "m-8vb":
return "cn-zhangjiakou"
case "m-hp3":
return "cn-huhehaote"
case "m-bp1":
return "cn-hangzhou"
case "m-uf6":
return "cn-shanghai"
case "m-wz9":
return "cn-shenzhen"
case "m-f8z":
return "cn-heyuan"
case "m-2vc":
return "cn-chengdu"
case "m-j6c":
return "cn-hongkong"
case "m-6we":
return "ap-northeast-1"
case "m-t4n":
return "ap-southeast-1"
case "m-p0w":
return "ap-southeast-2"
case "m-8ps":
return "ap-southeast-3"
case "m-k1a":
return "ap-southeast-5"
case "m-a2d":
return "ap-south-1"
case "m-0xi":
return "us-east-1"
case "m-rj9":
return "us-west-1"
case "m-d7o":
return "eu-west-1"
case "m-eb3":
return "me-east-1"
case "m-gw8":
return "eu-central-1"
default:
return ""
}
}
package alicloud
import (
"fmt"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
)
type MaxcomputeService struct {
client *connectivity.AliyunClient
}
func (s *MaxcomputeService) DescribeMaxcomputeProject(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewOdpsClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetProject"
request := map[string]interface{}{
"RegionName": s.client.RegionId,
"ProjectName": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
addDebug(action, response, request)
if IsExpectedErrorCodes(fmt.Sprintf("%v", response["Code"]), []string{"102", "403"}) {
err = WrapErrorf(Error(GetNotFoundMessage("MaxcomputeProject", id)), NotFoundMsg, ProviderERROR)
return object, err
}
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
err = Error("GetProject failed for " + response["Message"].(string))
return object, err
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type MhubService struct {
client *connectivity.AliyunClient
}
func (s *MhubService) DescribeMhubProduct(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewMhubClient()
if err != nil {
return nil, WrapError(err)
}
action := "QueryProductInfo"
request := map[string]interface{}{
"ProductId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-08-25"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ProductNotExist"}) {
err = WrapErrorf(Error(GetNotFoundMessage("MHUBProduct", id)), NotFoundMsg, ProviderERROR)
return object, err
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.ProductInfo", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ProductInfo", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *MhubService) DescribeMhubApp(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewMhubClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListApps"
idExist := false
parts, err := ParseResourceId(id, 2)
request := map[string]interface{}{
"ProductId": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-08-25"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ProductNotExist"}) {
err = WrapErrorf(Error(GetNotFoundMessage("MHUBProduct", id)), NotFoundMsg, ProviderERROR)
return object, err
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.AppInfos.AppInfo", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.AppInfos.AppInfo", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("MHUB", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["AppKey"]) == parts[1] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("MHUB", id)), NotFoundWithResponse, response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"strings"
"time"
ali_mns "github.com/aliyun/aliyun-mns-go-sdk"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
)
type MnsService struct {
client *connectivity.AliyunClient
}
func (s *MnsService) SubscriptionNotExistFunc(err error) bool {
return strings.Contains(err.Error(), "SubscriptionNotExist")
}
func (s *MnsService) TopicNotExistFunc(err error) bool {
return strings.Contains(err.Error(), "TopicNotExist")
}
func (s *MnsService) QueueNotExistFunc(err error) bool {
return strings.Contains(err.Error(), "QueueNotExist")
}
func (s *MnsService) DescribeMnsQueue(id string) (response ali_mns.QueueAttribute, err error) {
raw, err := s.client.WithMnsQueueManager(func(queueManager ali_mns.AliQueueManager) (interface{}, error) {
return queueManager.GetQueueAttributes(id)
})
if err != nil {
if s.QueueNotExistFunc(err) {
return response, WrapErrorf(err, NotFoundMsg, AliMnsERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, "GetQueueAttributes", AliMnsERROR)
}
addDebug("GetQueueAttributes", raw)
response, _ = raw.(ali_mns.QueueAttribute)
if response.QueueName == "" {
return response, WrapErrorf(Error(GetNotFoundMessage("MnsQueue", id)), NotFoundMsg, ProviderERROR)
}
return
}
func (s *MnsService) WaitForMnsQueue(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeMnsQueue(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.QueueName == id && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.QueueName, id, ProviderERROR)
}
}
}
func (s *MnsService) DescribeMnsTopic(id string) (*ali_mns.TopicAttribute, error) {
response := &ali_mns.TopicAttribute{}
raw, err := s.client.WithMnsTopicManager(func(topicManager ali_mns.AliTopicManager) (interface{}, error) {
return topicManager.GetTopicAttributes(id)
})
if err != nil {
if s.TopicNotExistFunc(err) {
return response, WrapErrorf(err, NotFoundMsg, AliMnsERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, "GetTopicAttributes", AliMnsERROR)
}
addDebug("GetTopicAttributes", raw)
resp, _ := raw.(ali_mns.TopicAttribute)
if resp.TopicName == "" {
return response, WrapErrorf(Error(GetNotFoundMessage("MnsTopic", id)), NotFoundMsg, ProviderERROR)
}
return &resp, nil
}
func (s *MnsService) WaitForMnsTopic(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeMnsTopic(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.TopicName == id && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.TopicName, id, ProviderERROR)
}
}
}
func (s *MnsService) DescribeMnsTopicSubscription(id string) (*ali_mns.SubscriptionAttribute, error) {
response := &ali_mns.SubscriptionAttribute{}
parts, err := ParseResourceId(id, 2)
if err != nil {
return response, WrapError(err)
}
topicName, name := parts[0], parts[1]
raw, err := s.client.WithMnsSubscriptionManagerByTopicName(topicName, func(subscriptionManager ali_mns.AliMNSTopic) (interface{}, error) {
return subscriptionManager.GetSubscriptionAttributes(name)
})
if err != nil {
if s.TopicNotExistFunc(err) || s.SubscriptionNotExistFunc(err) {
return response, WrapErrorf(err, NotFoundMsg, AliMnsERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, "GetSubscriptionAttributes", AliMnsERROR)
}
addDebug("GetSubscriptionAttributes", raw)
resp, _ := raw.(ali_mns.SubscriptionAttribute)
response = &resp
if response.SubscriptionName == "" {
return response, WrapErrorf(Error(GetNotFoundMessage("MnsTopicSubscription", id)), NotFoundMsg, ProviderERROR)
}
return response, nil
}
func (s *MnsService) WaitForMnsTopicSubscription(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeMnsTopicSubscription(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.TopicName+":"+object.SubscriptionName == id && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.SubscriptionName, id, ProviderERROR)
}
}
}
package alicloud
import (
"fmt"
"log"
"regexp"
"strings"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/dds"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
)
type MongoDBService struct {
client *connectivity.AliyunClient
}
func (s *MongoDBService) DescribeMongoDBInstance(id string) (instance dds.DBInstance, err error) {
request := dds.CreateDescribeDBInstanceAttributeRequest()
request.RegionId = s.client.RegionId
request.DBInstanceId = id
raw, err := s.client.WithDdsClient(func(client *dds.Client) (interface{}, error) {
return client.DescribeDBInstanceAttribute(request)
})
response, _ := raw.(*dds.DescribeDBInstanceAttributeResponse)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound"}) {
return instance, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return instance, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
if response == nil || len(response.DBInstances.DBInstance) == 0 {
return instance, WrapErrorf(Error(GetNotFoundMessage("MongoDB Instance", id)), NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response.DBInstances.DBInstance[0], nil
}
func (s *MongoDBService) RdsMongodbDBInstanceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeMongoDBInstance(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.DBInstanceStatus == failState {
return object, object.DBInstanceStatus, WrapError(Error(FailedToReachTargetStatus, object.DBInstanceStatus))
}
}
return object, object.DBInstanceStatus, nil
}
}
func (s *MongoDBService) DescribeMongoDBSecurityIps(instanceId string) (ips []string, err error) {
request := dds.CreateDescribeSecurityIpsRequest()
request.RegionId = s.client.RegionId
request.DBInstanceId = instanceId
raw, err := s.client.WithDdsClient(func(client *dds.Client) (interface{}, error) {
return client.DescribeSecurityIps(request)
})
if err != nil {
return ips, WrapErrorf(err, DefaultErrorMsg, instanceId, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*dds.DescribeSecurityIpsResponse)
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
var ipstr, separator string
ipsMap := make(map[string]string)
for _, ip := range response.SecurityIpGroups.SecurityIpGroup {
if ip.SecurityIpGroupAttribute == "hidden" {
continue
}
ipstr += separator + ip.SecurityIpList
separator = COMMA_SEPARATED
}
for _, ip := range strings.Split(ipstr, COMMA_SEPARATED) {
ipsMap[ip] = ip
}
var finalIps []string
if len(ipsMap) > 0 {
for key := range ipsMap {
finalIps = append(finalIps, key)
}
}
return finalIps, nil
}
func (s *MongoDBService) ModifyMongoDBSecurityIps(d *schema.ResourceData, ips string) error {
request := dds.CreateModifySecurityIpsRequest()
request.RegionId = s.client.RegionId
request.DBInstanceId = d.Id()
request.SecurityIps = ips
raw, err := s.client.WithDdsClient(func(client *dds.Client) (interface{}, error) {
return client.ModifySecurityIps(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 0, s.RdsMongodbDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapError(err)
}
return nil
}
func (s *MongoDBService) DescribeMongoDBSecurityGroupId(id string) (*dds.DescribeSecurityGroupConfigurationResponse, error) {
response := &dds.DescribeSecurityGroupConfigurationResponse{}
request := dds.CreateDescribeSecurityGroupConfigurationRequest()
request.RegionId = s.client.RegionId
request.DBInstanceId = id
raw, err := s.client.WithDdsClient(func(ddsClient *dds.Client) (interface{}, error) {
return ddsClient.DescribeSecurityGroupConfiguration(request)
})
if err != nil {
return response, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*dds.DescribeSecurityGroupConfigurationResponse)
return response, nil
}
func (server *MongoDBService) ModifyMongodbShardingInstanceNode(
d *schema.ResourceData, nodeType MongoDBShardingNodeType, stateList, diffList []interface{}) error {
client := server.client
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 0, server.RdsMongodbDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapError(err)
}
//create node
if len(stateList) < len(diffList) {
createList := diffList[len(stateList):]
diffList = diffList[:len(stateList)]
for _, item := range createList {
node := item.(map[string]interface{})
request := dds.CreateCreateNodeRequest()
request.RegionId = server.client.RegionId
request.DBInstanceId = d.Id()
request.NodeClass = node["node_class"].(string)
request.NodeType = string(nodeType)
if node["readonly_replicas"] != nil {
request.ReadonlyReplicas = requests.NewInteger(node["readonly_replicas"].(int))
}
request.ClientToken = buildClientToken(request.GetActionName())
if nodeType == MongoDBShardingNodeShard {
request.NodeStorage = requests.NewInteger(node["node_storage"].(int))
}
raw, err := client.WithDdsClient(func(ddsClient *dds.Client) (interface{}, error) {
return ddsClient.CreateNode(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 3*time.Minute, server.RdsMongodbDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapError(err)
}
}
} else if len(stateList) > len(diffList) {
deleteList := stateList[len(diffList):]
stateList = stateList[:len(diffList)]
for _, item := range deleteList {
node := item.(map[string]interface{})
request := dds.CreateDeleteNodeRequest()
request.RegionId = server.client.RegionId
request.DBInstanceId = d.Id()
request.NodeId = node["node_id"].(string)
request.ClientToken = buildClientToken(request.GetActionName())
raw, err := client.WithDdsClient(func(ddsClient *dds.Client) (interface{}, error) {
return ddsClient.DeleteNode(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 1*time.Minute, server.RdsMongodbDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapError(err)
}
}
}
//motify node
for key := 0; key < len(stateList); key++ {
state := stateList[key].(map[string]interface{})
diff := diffList[key].(map[string]interface{})
if state["node_class"] != diff["node_class"] ||
state["node_storage"] != diff["node_storage"] {
request := dds.CreateModifyNodeSpecRequest()
if d.Get("instance_charge_type").(string) == "PrePaid" {
if v, ok := d.GetOk("order_type"); ok {
request.OrderType = v.(string)
}
}
request.RegionId = server.client.RegionId
request.DBInstanceId = d.Id()
request.NodeClass = diff["node_class"].(string)
request.ClientToken = buildClientToken(request.GetActionName())
if nodeType == MongoDBShardingNodeShard {
request.NodeStorage = requests.NewInteger(diff["node_storage"].(int))
}
request.NodeId = state["node_id"].(string)
raw, err := client.WithDdsClient(func(ddsClient *dds.Client) (interface{}, error) {
return ddsClient.ModifyNodeSpec(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 3*time.Minute, server.RdsMongodbDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapError(err)
}
}
}
return nil
}
func (s *MongoDBService) DescribeMongoDBBackupPolicy(id string) (*dds.DescribeBackupPolicyResponse, error) {
response := &dds.DescribeBackupPolicyResponse{}
request := dds.CreateDescribeBackupPolicyRequest()
request.RegionId = s.client.RegionId
request.DBInstanceId = id
raw, err := s.client.WithDdsClient(func(ddsClient *dds.Client) (interface{}, error) {
return ddsClient.DescribeBackupPolicy(request)
})
if err != nil {
return response, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*dds.DescribeBackupPolicyResponse)
return response, nil
}
func (s *MongoDBService) DescribeMongoDBTDEInfo(id string) (*dds.DescribeDBInstanceTDEInfoResponse, error) {
response := &dds.DescribeDBInstanceTDEInfoResponse{}
request := dds.CreateDescribeDBInstanceTDEInfoRequest()
request.RegionId = s.client.RegionId
request.DBInstanceId = id
raw, err := s.client.WithDdsClient(func(ddsClient *dds.Client) (interface{}, error) {
return ddsClient.DescribeDBInstanceTDEInfo(request)
})
if err != nil {
return response, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*dds.DescribeDBInstanceTDEInfoResponse)
return response, nil
}
func (s *MongoDBService) DescribeDBInstanceSSL(id string) (*dds.DescribeDBInstanceSSLResponse, error) {
response := &dds.DescribeDBInstanceSSLResponse{}
request := dds.CreateDescribeDBInstanceSSLRequest()
request.RegionId = s.client.RegionId
request.DBInstanceId = id
raw, err := s.client.WithDdsClient(func(ddsClient *dds.Client) (interface{}, error) {
return ddsClient.DescribeDBInstanceSSL(request)
})
if err != nil {
return response, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*dds.DescribeDBInstanceSSLResponse)
return response, nil
}
func (s *MongoDBService) MotifyMongoDBBackupPolicy(d *schema.ResourceData) error {
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 0*time.Second, s.RdsMongodbDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapError(err)
}
periodList := expandStringList(d.Get("backup_period").(*schema.Set).List())
backupPeriod := fmt.Sprintf("%s", strings.Join(periodList[:], COMMA_SEPARATED))
backupTime := d.Get("backup_time").(string)
request := dds.CreateModifyBackupPolicyRequest()
request.RegionId = s.client.RegionId
request.DBInstanceId = d.Id()
request.PreferredBackupPeriod = backupPeriod
request.PreferredBackupTime = backupTime
raw, err := s.client.WithDdsClient(func(ddsClient *dds.Client) (interface{}, error) {
return ddsClient.ModifyBackupPolicy(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
if _, err := stateConf.WaitForState(); err != nil {
return WrapError(err)
}
return nil
}
func (s *MongoDBService) ResetAccountPassword(d *schema.ResourceData, password string) error {
request := dds.CreateResetAccountPasswordRequest()
request.RegionId = s.client.RegionId
request.DBInstanceId = d.Id()
request.AccountName = "root"
request.AccountPassword = password
raw, err := s.client.WithDdsClient(func(ddsClient *dds.Client) (interface{}, error) {
return ddsClient.ResetAccountPassword(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return err
}
func (s *MongoDBService) setInstanceTags(d *schema.ResourceData) error {
oraw, nraw := d.GetChange("tags")
o := oraw.(map[string]interface{})
n := nraw.(map[string]interface{})
create, remove := s.diffTags(s.tagsFromMap(o), s.tagsFromMap(n))
if len(remove) > 0 {
var tagKey []string
for _, v := range remove {
tagKey = append(tagKey, v.Key)
}
request := dds.CreateUntagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.ResourceType = "INSTANCE"
request.TagKey = &tagKey
request.RegionId = s.client.RegionId
raw, err := s.client.WithDdsClient(func(ddsClient *dds.Client) (interface{}, error) {
return ddsClient.UntagResources(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
if len(create) > 0 {
request := dds.CreateTagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.Tag = &create
request.ResourceType = "INSTANCE"
request.RegionId = s.client.RegionId
raw, err := s.client.WithDdsClient(func(ddsClient *dds.Client) (interface{}, error) {
return ddsClient.TagResources(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
d.SetPartial("tags")
return nil
}
func (s *MongoDBService) tagsToMap(tags []dds.Tag) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !s.ignoreTag(t) {
result[t.Key] = t.Value
}
}
return result
}
func (s *MongoDBService) ignoreTag(t dds.Tag) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, t.Key)
ok, _ := regexp.MatchString(v, t.Key)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific t %s (val: %s), ignoring.\n", t.Key, t.Value)
return true
}
}
return false
}
func (s *MongoDBService) tagsInAttributeToMap(tags []dds.Tag) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !s.ignoreTagInAttribute(t) {
result[t.Key] = t.Value
}
}
return result
}
func (s *MongoDBService) ignoreTagInAttribute(t dds.Tag) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, t.Key)
ok, _ := regexp.MatchString(v, t.Key)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific t %s (val: %s), ignoring.\n", t.Key, t.Value)
return true
}
}
return false
}
func (s *MongoDBService) diffTags(oldTags, newTags []dds.TagResourcesTag) ([]dds.TagResourcesTag, []dds.TagResourcesTag) {
// First, we're creating everything we have
create := make(map[string]interface{})
for _, t := range newTags {
create[t.Key] = t.Value
}
// Build the list of what to remove
var remove []dds.TagResourcesTag
for _, t := range oldTags {
old, ok := create[t.Key]
if !ok || old != t.Value {
// Delete it!
remove = append(remove, t)
}
}
return s.tagsFromMap(create), remove
}
func (s *MongoDBService) tagsFromMap(m map[string]interface{}) []dds.TagResourcesTag {
result := make([]dds.TagResourcesTag, 0, len(m))
for k, v := range m {
result = append(result, dds.TagResourcesTag{
Key: k,
Value: v.(string),
})
}
return result
}
func (s *MongoDBService) DescribeMongodbAuditPolicy(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDdsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeAuditPolicy"
request := map[string]interface{}{
"DBInstanceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *MongoDBService) DescribeMongodbAccount(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDdsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeAccounts"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"AccountName": parts[1],
"DBInstanceId": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Accounts.Account", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Accounts.Account", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("MongoDB", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["AccountName"]) != parts[1] {
return object, WrapErrorf(Error(GetNotFoundMessage("MongoDB", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *MongoDBService) MongodbAccountStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeMongodbAccount(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["AccountStatus"]) == failState {
return object, fmt.Sprint(object["AccountStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["AccountStatus"])))
}
}
return object, fmt.Sprint(object["AccountStatus"]), nil
}
}
func (s *MongoDBService) DescribeSecurityIps(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDdsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeSecurityIps"
request := map[string]interface{}{
"DBInstanceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *MongoDBService) DescribeMongodbServerlessInstance(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDdsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDBInstanceAttribute"
request := map[string]interface{}{
"DBInstanceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("MongoDB:ServerlessInstance", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.DBInstances.DBInstance", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.DBInstances.DBInstance", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("MongoDB", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["DBInstanceId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("MongoDB", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *MongoDBService) MongodbServerlessInstanceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeMongodbServerlessInstance(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["DBInstanceStatus"]) == failState {
return object, fmt.Sprint(object["DBInstanceStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["DBInstanceStatus"])))
}
}
return object, fmt.Sprint(object["DBInstanceStatus"]), nil
}
}
func (s *MongoDBService) SetResourceTags(d *schema.ResourceData, resourceType string) error {
if d.HasChange("tags") {
added, removed := parsingTags(d)
conn, err := s.client.NewDdsClient()
if err != nil {
return WrapError(err)
}
removedTagKeys := make([]string, 0)
for _, v := range removed {
if !ignoredTags(v, "") {
removedTagKeys = append(removedTagKeys, v)
}
}
if len(removedTagKeys) > 0 {
action := "UntagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": d.Id(),
}
for i, key := range removedTagKeys {
request[fmt.Sprintf("TagKey.%d", i+1)] = key
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
action := "TagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": d.Id(),
}
count := 1
for key, value := range added {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("tags")
}
return nil
}
func (s *MongoDBService) ListTagResources(id string, resourceType string) (object interface{}, err error) {
conn, err := s.client.NewDdsClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListTagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": id,
}
tags := make([]interface{}, 0)
var response map[string]interface{}
for {
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.TagResources.TagResource", response)
if err != nil {
return resource.NonRetryableError(WrapErrorf(err, FailedGetAttributeMsg, id, "$.TagResources.TagResource", response))
}
if v != nil {
tags = append(tags, v.([]interface{})...)
}
return nil
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
if response["NextToken"] == nil {
break
}
request["NextToken"] = response["NextToken"]
}
return tags, nil
}
func (s *MongoDBService) DescribeMongodbShardingNetworkPublicAddress(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewDdsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeShardingNetworkAddress"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"DBInstanceId": parts[0],
"NodeId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound"}) {
return object, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.NetworkAddresses.NetworkAddress", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.NetworkAddresses.NetworkAddress", response)
}
exist := false
var networkAddress = make([]map[string]interface{}, 0)
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("MongoDB", id)), NotFoundWithResponse, response)
} else {
for _, item := range v.([]interface{}) {
if item.(map[string]interface{})["NetworkType"].(string) == "Public" {
exist = true
networkAddress = append(networkAddress, item.(map[string]interface{}))
}
}
if !exist {
return object, WrapErrorf(Error(GetNotFoundMessage("MongoDB", id)), NotFoundWithResponse, response)
}
}
object = make(map[string]interface{}, 0)
object["NetworkAddress"] = networkAddress
return object, nil
}
func (s *MongoDBService) DescribeShardingNodeType(id string) (string, error) {
var response map[string]interface{}
conn, err := s.client.NewDdsClient()
if err != nil {
return "", WrapError(err)
}
action := "DescribeShardingNetworkAddress"
parts, err := ParseResourceId(id, 2)
if err != nil {
return "", WrapError(err)
}
request := map[string]interface{}{
"DBInstanceId": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound"}) {
return "", WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return "", WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.NetworkAddresses.NetworkAddress", response)
if err != nil {
return "", WrapErrorf(err, FailedGetAttributeMsg, id, "$.NetworkAddresses.NetworkAddress", response)
}
var nodeType string
if len(v.([]interface{})) < 1 {
return "", WrapErrorf(Error(GetNotFoundMessage("MongoDB", id)), NotFoundWithResponse, response)
} else {
for _, item := range v.([]interface{}) {
if item.(map[string]interface{})["NodeId"].(string) == parts[1] {
nodeType = fmt.Sprint(item.(map[string]interface{})["NodeType"])
break
}
}
}
if nodeType == "" {
return "", WrapErrorf(Error(GetNotFoundMessage("MongoDB", id)), NotFoundWithResponse, response)
}
return nodeType, nil
}
func (s *MongoDBService) MongodbShardingNetworkPublicAddressStateRefreshFunc(id, nodeType string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
return nil, "", WrapError(err)
}
object, err := s.DescribeMongodbServerlessInstance(parts[0])
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
var status string
switch nodeType {
case "mongos":
status = fmt.Sprint(object["DBInstanceStatus"])
case "db":
list := object["ShardList"].(map[string]interface{})["ShardAttribute"]
for _, item := range list.([]interface{}) {
mongos := item.(map[string]interface{})
if mongos["NodeId"] == parts[1] {
status = fmt.Sprint(mongos["Status"])
break
}
}
case "cs":
list := object["ConfigserverList"].(map[string]interface{})["ConfigserverAttribute"]
for _, item := range list.([]interface{}) {
mongos := item.(map[string]interface{})
if mongos["NodeId"] == parts[1] {
status = fmt.Sprint(mongos["Status"])
break
}
}
}
for _, failState := range failStates {
if status == failState {
return object, status, WrapError(Error(FailedToReachTargetStatus, status))
}
}
return object, status, nil
}
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type MscOpenSubscriptionService struct {
client *connectivity.AliyunClient
}
func (s *MscOpenSubscriptionService) GetContact(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewMscopensubscriptionClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetContact"
request := map[string]interface{}{
"ContactId": id,
"Locale": "en",
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2021-07-13"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if IsExpectedErrorCodes(fmt.Sprint(response["Code"]), []string{"ResourceNotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("MscSub:Contact", id)), NotFoundMsg, ProviderERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.Contact", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Contact", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *MscOpenSubscriptionService) DescribeMscSubContact(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewMscopensubscriptionClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetContact"
request := map[string]interface{}{
"ContactId": id,
"Locale": "en",
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2021-07-13"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if IsExpectedErrors(err, []string{"ResourceNotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("MscSub:Contact", id)), NotFoundMsg, ProviderERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.Contact", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Contact", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *MscOpenSubscriptionService) DescribeMscSubSubscription(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewMscopensubscriptionClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetSubscriptionItem"
request := map[string]interface{}{
"ItemId": id,
"Locale": "en",
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2021-07-13"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.SubscriptionItem", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.SubscriptionItem", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *MscOpenSubscriptionService) DescribeMscSubWebhook(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewMscopensubscriptionClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetWebhook"
request := map[string]interface{}{
"WebhookId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2021-07-13"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ResourceNotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.Webhook", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Webhook", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type MseService struct {
client *connectivity.AliyunClient
}
func (s *MseService) DescribeMseCluster(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewMseClient()
if err != nil {
return nil, WrapError(err)
}
action := "QueryClusterDetail"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"InstanceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("QueryClusterDetail")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-05-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"mse-200-021"}) {
err = WrapErrorf(Error(GetNotFoundMessage("MseCluster", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Data", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *MseService) MseClusterStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeMseCluster(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["InitStatus"].(string) == failState {
return object, object["InitStatus"].(string), WrapError(Error(FailedToReachTargetStatus, object["InitStatus"].(string)))
}
}
return object, object["InitStatus"].(string), nil
}
}
package alicloud
import (
"fmt"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type NasService struct {
client *connectivity.AliyunClient
}
func (s *NasService) DescribeNasFileSystem(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewNasClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeFileSystems"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"FileSystemId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidFileSystem.NotFound", "Forbidden.NasNotFound", "Resource.NotFound", "InvalidFileSystemStatus.Ordering"}) {
err = WrapErrorf(Error(GetNotFoundMessage("NasFileSystem", id)), NotFoundWithResponse, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.FileSystems.FileSystem", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.FileSystems.FileSystem", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("NAS", id)), NotFoundWithResponse, response)
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *NasService) DescribeNasMountTarget(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewNasClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeMountTargets"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"FileSystemId": parts[0],
"MountTargetDomain": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"Forbidden.NasNotFound", "InvalidFileSystem.NotFound", "InvalidLBid.NotFound", "InvalidMountTarget.NotFound", "VolumeUnavailable"}) {
err = WrapErrorf(Error(GetNotFoundMessage("NasMountTarget", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.MountTargets.MountTarget", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.MountTargets.MountTarget", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("NAS", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["MountTargetDomain"].(string) != parts[1] {
return object, WrapErrorf(Error(GetNotFoundMessage("NAS", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *NasService) DescribeNasAccessGroup(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewNasClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeAccessGroups"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"AccessGroupName": parts[0],
"FileSystemType": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"Forbidden.NasNotFound", "InvalidAccessGroup.NotFound", "Resource.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("NasAccessGroup", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.AccessGroups.AccessGroup", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.AccessGroups.AccessGroup", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("NAS", id)), NotFoundWithResponse, response)
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *NasService) DescribeNasAccessRule(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewNasClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeAccessRules"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"AccessGroupName": parts[0],
"AccessRuleId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidAccessGroup.NotFound", "Forbidden.NasNotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("AccessRule", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.AccessRules.AccessRule", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.AccessRules.AccessRule", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("NAS", id)), NotFoundWithResponse, response)
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *NasService) NasMountTargetStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeNasMountTarget(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["Status"].(string) == failState {
return object, object["Status"].(string), WrapError(Error(FailedToReachTargetStatus, object["Status"].(string)))
}
}
return object, object["Status"].(string), nil
}
}
func (s *NasService) DescribeNasFileSystemStateRefreshFunc(id string, defaultRetryState string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeNasFileSystem(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, defaultRetryState, nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *NasService) DescribeNasSnapshot(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewNasClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeSnapshots"
request := map[string]interface{}{
"SnapshotIds": id,
"FileSystemType": "extreme",
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidFileSystem.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("NAS:Snapshot", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Snapshots.Snapshot", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Snapshots.Snapshot", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("NAS", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["SnapshotId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("NAS", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *NasService) NasSnapshotStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeNasSnapshot(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *NasService) DescribeNasFileset(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewNasClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeFilesets"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"FileSystemId": parts[0],
"MaxResults": 20,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidFileSystem.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("NAS:Snapshot", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Entries.Entrie", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Entries.Entrie", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("NAS", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["FsetId"]) == parts[1] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("NAS", id)), NotFoundWithResponse, response)
}
return
}
func (s *NasService) NasFilesetStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeNasFileset(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *NasService) ListTagResources(id string, resourceType string) (object interface{}, err error) {
conn, err := s.client.NewNasClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListTagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": id,
}
tags := make([]interface{}, 0)
var response map[string]interface{}
for {
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.TagResources.TagResource", response)
if err != nil {
return resource.NonRetryableError(WrapErrorf(err, FailedGetAttributeMsg, id, "$.TagResources.TagResource", response))
}
if v != nil {
tags = append(tags, v.([]interface{})...)
}
return nil
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
if response["NextToken"] == nil {
break
}
request["NextToken"] = response["NextToken"]
}
return tags, nil
}
func (s *NasService) SetResourceTags(d *schema.ResourceData, resourceType string) error {
if d.HasChange("tags") {
added, removed := parsingTags(d)
conn, err := s.client.NewNasClient()
if err != nil {
return WrapError(err)
}
removedTagKeys := make([]string, 0)
for _, v := range removed {
if !ignoredTags(v, "") {
removedTagKeys = append(removedTagKeys, v)
}
}
if len(removedTagKeys) > 0 {
action := "UntagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": d.Id(),
}
for i, key := range removedTagKeys {
request[fmt.Sprintf("TagKey.%d", i+1)] = key
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
action := "TagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": d.Id(),
}
count := 1
for key, value := range added {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("tags")
}
return nil
}
func (s *NasService) DescribeNasAutoSnapshotPolicy(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewNasClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeAutoSnapshotPolicies"
request := map[string]interface{}{
"AutoSnapshotPolicyId": id,
"FileSystemType": "extreme",
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidLifecyclePolicy.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("NAS:AutoSnapshotPolicy", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.AutoSnapshotPolicies.AutoSnapshotPolicy", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.AutoSnapshotPolicies.AutoSnapshotPolicy", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("NAS", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["AutoSnapshotPolicyId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("NAS", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *NasService) NasAutoSnapshotPolicyStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeNasAutoSnapshotPolicy(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *NasService) DescribeNasLifecyclePolicy(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewNasClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeLifecyclePolicies"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"FileSystemId": parts[0],
"PageNumber": 1,
"PageSize": PageSizeMedium,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2017-06-26"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidFileSystem.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("NAS:LifecyclePolicy", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.LifecyclePolicies", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.LifecyclePolicies", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("NAS", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["LifecyclePolicyName"]) == parts[1] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("NAS", id)), NotFoundWithResponse, response)
}
return
}
func (s *NasService) DescribeNasDataFlow(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewNasClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDataFlows"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"FileSystemId": parts[0],
"MaxResults": 20,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-06-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidFileSystem.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("NAS:DataFlow", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.DataFlowInfo.DataFlow", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.DataFlowInfo.DataFlow", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("NAS", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["DataFlowId"]) == parts[1] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("NAS", id)), NotFoundWithResponse, response)
}
return
}
func (s *NasService) NasDataFlowStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeNasDataFlow(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type OnsService struct {
client *connectivity.AliyunClient
}
func (s *OnsService) DescribeOnsInstance(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewOnsClient()
if err != nil {
return nil, WrapError(err)
}
action := "OnsInstanceBaseInfo"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"InstanceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-02-14"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"INSTANCE_NOT_FOUNDError", "InvalidDomainName.NoExist"}) {
err = WrapErrorf(Error(GetNotFoundMessage("OnsInstance", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.InstanceBaseInfo", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.InstanceBaseInfo", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *OnsService) DescribeOnsTopic(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewOnsClient()
if err != nil {
return nil, WrapError(err)
}
action := "OnsTopicList"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"InstanceId": parts[0],
"Topic": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-02-14"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"AUTH_RESOURCE_OWNER_ERROR", "INSTANCE_NOT_FOUND"}) {
err = WrapErrorf(Error(GetNotFoundMessage("OnsTopic", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Data.PublishInfoDo", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data.PublishInfoDo", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("Ons", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["Topic"].(string) != parts[1] {
return object, WrapErrorf(Error(GetNotFoundMessage("Ons", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *OnsService) DescribeOnsGroup(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewOnsClient()
if err != nil {
return nil, WrapError(err)
}
action := "OnsGroupList"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"GroupId": parts[1],
"InstanceId": parts[0],
"GroupType": "all",
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-02-14"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"AUTH_RESOURCE_OWNER_ERROR", "INSTANCE_NOT_FOUND"}) {
err = WrapErrorf(Error(GetNotFoundMessage("OnsGroup", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Data.SubscribeInfoDo", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data.SubscribeInfoDo", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("Ons", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["GroupId"].(string) != parts[1] {
return object, WrapErrorf(Error(GetNotFoundMessage("Ons", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *OnsService) SetResourceTags(d *schema.ResourceData, resourceType string) error {
var parts []string
var err error
if resourceType == "GROUP" || resourceType == "TOPIC" {
parts, err = ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
}
}
if d.HasChange("tags") {
added, removed := parsingTags(d)
conn, err := s.client.NewOnsClient()
if err != nil {
return WrapError(err)
}
removedTagKeys := make([]string, 0)
for _, v := range removed {
if !ignoredTags(v, "") {
removedTagKeys = append(removedTagKeys, v)
}
}
if len(removedTagKeys) > 0 {
action := "UntagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
}
if resourceType == "INSTANCE" {
request["ResourceId.1"] = d.Id()
}
if resourceType == "GROUP" || resourceType == "TOPIC" {
request["InstanceId"] = parts[0]
request["ResourceId.1"] = parts[1]
}
for i, key := range removedTagKeys {
request[fmt.Sprintf("TagKey.%d", i+1)] = key
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-02-14"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
action := "TagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
}
if resourceType == "INSTANCE" {
request["ResourceId.1"] = d.Id()
}
if resourceType == "GROUP" || resourceType == "TOPIC" {
request["InstanceId"] = parts[0]
request["ResourceId.1"] = parts[1]
}
count := 1
for key, value := range added {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-02-14"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("tags")
}
return nil
}
func (s *OnsService) OnsTopicStatus(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewOnsClient()
if err != nil {
return nil, WrapError(err)
}
action := "OnsTopicStatus"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"InstanceId": parts[0],
"Topic": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(11*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-02-14"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"Throttling.User"}) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"AUTH_RESOURCE_OWNER_ERROR", "INSTANCE_NOT_FOUND"}) {
err = WrapErrorf(Error(GetNotFoundMessage("OnsTopic", id)), NotFoundMsg, ProviderERROR)
return resource.NonRetryableError(err)
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Data", response)
if err != nil {
return resource.NonRetryableError(WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data", response))
}
object = v.(map[string]interface{})
return nil
})
return
}
func (s *OnsService) ListTagResources(id string, resourceType string) (object interface{}, err error) {
conn, err := s.client.NewOnsClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListTagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": id,
}
tags := make([]interface{}, 0)
var response map[string]interface{}
for {
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-02-14"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{Throttling}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.TagResources", response)
if err != nil {
return resource.NonRetryableError(WrapErrorf(err, FailedGetAttributeMsg, id, "$.TagResources.TagResource", response))
}
if v != nil {
if v != nil {
tags = append(tags, v.([]interface{})...)
}
}
return nil
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
if response["NextToken"] == nil {
break
}
request["NextToken"] = response["NextToken"]
}
return tags, nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type OosService struct {
client *connectivity.AliyunClient
}
func (s *OosService) DescribeOosTemplate(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewOosClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetTemplate"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"TemplateName": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Template"}) {
err = WrapErrorf(Error(GetNotFoundMessage("OosTemplate", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Template", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Template", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *OosService) DescribeOosExecution(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewOosClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListExecutions"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ExecutionId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Executions", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Executions", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("OOS", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["ExecutionId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("OOS", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *OosService) OosExecutionStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeOosExecution(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["Status"].(string) == failState {
return object, object["Status"].(string), WrapError(Error(FailedToReachTargetStatus, object["Status"].(string)))
}
}
return object, object["Status"].(string), nil
}
}
func (s *OosService) DescribeOosApplication(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewOosClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetApplication"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"Name": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Application"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Oos:Application", id)), NotFoundMsg, ProviderERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Application", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Application", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *OosService) DescribeOosApplicationGroup(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewOosClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetApplicationGroup"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"Name": parts[1],
"ApplicationName": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.ApplicationGroup"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Oos:ApplicationGroup", id)), NotFoundMsg, ProviderERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.ApplicationGroup", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ApplicationGroup", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *OosService) DescribeOosPatchBaseline(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewOosClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetPatchBaseline"
request := map[string]interface{}{
"Name": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.PatchBaseline"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Oos:Application", id)), NotFoundMsg, ProviderERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.PatchBaseline", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.PatchBaseline", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *OosService) DescribeOosStateConfiguration(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewOosClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListStateConfigurations"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.StateConfigurations", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.StateConfigurations", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("OOS", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["StateConfigurationId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("OOS", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *OosService) DescribeOosServiceSetting(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewOosClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetServiceSettings"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.ServiceSettings", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ServiceSettings", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *OosService) DescribeOosParameter(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewOosClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetParameter"
request := map[string]interface{}{
"Name": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Parameter"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Oos:Application", id)), NotFoundMsg, ProviderERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Parameter", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Parameter", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *OosService) DescribeOosSecretParameter(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewOosClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetSecretParameter"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"Name": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Parameter"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Oos:Application", id)), NotFoundMsg, ProviderERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Parameter", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Parameter", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type OpenSearchService struct {
client *connectivity.AliyunClient
}
func (s *OpenSearchService) DescribeOpenSearchAppGroup(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewOpensearchClient()
if err != nil {
return nil, WrapError(err)
}
action := "/v4/openapi/app-groups/" + id
body := map[string]interface{}{
"appGroupIdentity": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2017-12-25"), nil, StringPointer("GET"), StringPointer("AK"), StringPointer(action), nil, nil, body, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug("GET "+action, response, body)
if err != nil {
if IsExpectedErrors(err, []string{"App.NotFound"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return object, WrapError(fmt.Errorf("%s failed, response: %v", "POST "+action, response))
}
v, err := jsonpath.Get("$.result", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.result", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *OpenSearchService) OpenSearchAppStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeOpenSearchAppGroup(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["status"].(string) == failState {
return object, object["status"].(string), WrapError(Error(FailedToReachTargetStatus, object["status"].(string)))
}
}
return object, object["status"].(string), nil
}
}
package alicloud
import (
"strconv"
"time"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
)
// OssService *connectivity.AliyunClient
type OssService struct {
client *connectivity.AliyunClient
}
func (s *OssService) DescribeOssBucket(id string) (response oss.GetBucketInfoResult, err error) {
request := map[string]string{"bucketName": id}
var requestInfo *oss.Client
raw, err := s.client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
requestInfo = ossClient
return ossClient.GetBucketInfo(request["bucketName"])
})
if err != nil {
if ossNotFoundError(err) {
return response, WrapErrorf(err, NotFoundMsg, AliyunOssGoSdk)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, "GetBucketInfo", AliyunOssGoSdk)
}
addDebug("GetBucketInfo", raw, requestInfo, request)
response, _ = raw.(oss.GetBucketInfoResult)
return
}
func (s *OssService) WaitForOssBucket(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeOssBucket(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.BucketInfo.Name != "" && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.BucketInfo.Name, status, ProviderERROR)
}
}
}
func (s *OssService) WaitForOssBucketObject(bucket *oss.Bucket, id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
exist, err := bucket.IsObjectExist(id)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, id, "IsObjectExist", AliyunOssGoSdk)
}
addDebug("IsObjectExist", exist)
if !exist {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, strconv.FormatBool(exist), status, ProviderERROR)
}
}
}
package alicloud
import (
"strings"
"time"
"fmt"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ots"
"github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type OtsService struct {
client *connectivity.AliyunClient
}
func (s *OtsService) getPrimaryKeyType(primaryKeyType string) tablestore.PrimaryKeyType {
var keyType tablestore.PrimaryKeyType
t := PrimaryKeyTypeString(primaryKeyType)
switch t {
case IntegerType:
keyType = tablestore.PrimaryKeyType_INTEGER
case StringType:
keyType = tablestore.PrimaryKeyType_STRING
case BinaryType:
keyType = tablestore.PrimaryKeyType_BINARY
}
return keyType
}
func (s *OtsService) ListOtsTable(instanceName string) (table *tablestore.ListTableResponse, err error) {
if _, err := s.DescribeOtsInstance(instanceName); err != nil {
return nil, WrapError(err)
}
var raw interface{}
var requestInfo *tablestore.TableStoreClient
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithTableStoreClient(instanceName, func(tableStoreClient *tablestore.TableStoreClient) (interface{}, error) {
requestInfo = tableStoreClient
return tableStoreClient.ListTable()
})
if err != nil {
if strings.HasSuffix(err.Error(), "no such host") {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug("ListTable", raw, requestInfo)
return nil
})
if err != nil {
if strings.HasPrefix(err.Error(), "OTSObjectNotExist") {
return table, WrapErrorf(err, NotFoundMsg, AliyunTablestoreGoSdk)
}
return nil, WrapErrorf(err, DataDefaultErrorMsg, instanceName, "ListTable", AliyunTablestoreGoSdk)
}
table, _ = raw.(*tablestore.ListTableResponse)
if table == nil {
return table, WrapErrorf(Error(GetNotFoundMessage("OtsTable", instanceName)), NotFoundMsg, ProviderERROR)
}
return
}
func (s *OtsService) DescribeOtsTable(id string) (*tablestore.DescribeTableResponse, error) {
table := &tablestore.DescribeTableResponse{}
parts, err := ParseResourceId(id, 2)
if err != nil {
return table, WrapError(err)
}
instanceName, tableName := parts[0], parts[1]
request := new(tablestore.DescribeTableRequest)
request.TableName = tableName
if _, err := s.DescribeOtsInstance(instanceName); err != nil {
return table, WrapError(err)
}
var raw interface{}
var requestInfo *tablestore.TableStoreClient
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithTableStoreClient(instanceName, func(tableStoreClient *tablestore.TableStoreClient) (interface{}, error) {
requestInfo = tableStoreClient
return tableStoreClient.DescribeTable(request)
})
if err != nil {
if IsExpectedErrors(err, OtsTableIsTemporarilyUnavailable) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug("DescribeTable", raw, requestInfo, request)
return nil
})
if err != nil {
if strings.HasPrefix(err.Error(), "OTSObjectNotExist") {
return table, WrapErrorf(err, NotFoundMsg, AliyunTablestoreGoSdk)
}
return table, WrapErrorf(err, DefaultErrorMsg, id, "DescribeTable", AliyunTablestoreGoSdk)
}
table, _ = raw.(*tablestore.DescribeTableResponse)
if table == nil || table.TableMeta == nil || table.TableMeta.TableName != tableName {
return table, WrapErrorf(Error(GetNotFoundMessage("OtsTable", id)), NotFoundMsg, ProviderERROR)
}
return table, nil
}
func (s *OtsService) WaitForOtsTable(instanceName, tableName string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
id := fmt.Sprintf("%s%s%s", instanceName, COLON_SEPARATED, tableName)
for {
object, err := s.DescribeOtsTable(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.TableMeta.TableName == tableName && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.TableMeta.TableName, tableName, ProviderERROR)
}
}
}
// Convert tablestore.PrimaryKeyType to PrimaryKeyTypeString
func (s *OtsService) convertPrimaryKeyType(t tablestore.PrimaryKeyType) PrimaryKeyTypeString {
var typeString PrimaryKeyTypeString
switch t {
case tablestore.PrimaryKeyType_INTEGER:
typeString = IntegerType
case tablestore.PrimaryKeyType_BINARY:
typeString = BinaryType
case tablestore.PrimaryKeyType_STRING:
typeString = StringType
}
return typeString
}
func (s *OtsService) ListOtsInstance(pageSize int, pageNum int) ([]string, error) {
req := ots.CreateListInstanceRequest()
req.RegionId = s.client.RegionId
req.Method = "GET"
req.PageSize = requests.NewInteger(pageSize)
req.PageNum = requests.NewInteger(pageNum)
var allInstanceNames []string
for {
raw, err := s.client.WithOtsClient(func(otsClient *ots.Client) (interface{}, error) {
return otsClient.ListInstance(req)
})
if err != nil {
return nil, WrapErrorf(err, DefaultErrorMsg, "alicloud_ots_instances", req.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(req.GetActionName(), raw, req.RpcRequest, req)
response, _ := raw.(*ots.ListInstanceResponse)
if response == nil || len(response.InstanceInfos.InstanceInfo) < 1 {
break
}
for _, instance := range response.InstanceInfos.InstanceInfo {
allInstanceNames = append(allInstanceNames, instance.InstanceName)
}
if len(response.InstanceInfos.InstanceInfo) < PageSizeLarge {
break
}
if page, err := getNextpageNumber(req.PageNum); err != nil {
return nil, WrapError(err)
} else {
req.PageNum = page
}
}
return allInstanceNames, nil
}
func (s *OtsService) DescribeOtsInstance(id string) (inst ots.InstanceInfo, err error) {
request := ots.CreateGetInstanceRequest()
request.RegionId = s.client.RegionId
request.InstanceName = id
request.Method = "GET"
raw, err := s.client.WithOtsClient(func(otsClient *ots.Client) (interface{}, error) {
return otsClient.GetInstance(request)
})
// OTS instance not found error code is "NotFound"
if err != nil {
if NotFoundError(err) {
return inst, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return inst, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ots.GetInstanceResponse)
if response.InstanceInfo.InstanceName != id {
return inst, WrapErrorf(Error(GetNotFoundMessage("OtsInstance", id)), NotFoundMsg, ProviderERROR)
}
return response.InstanceInfo, nil
}
func (s *OtsService) DescribeOtsInstanceAttachment(id string) (inst ots.VpcInfo, err error) {
request := ots.CreateListVpcInfoByInstanceRequest()
request.RegionId = s.client.RegionId
request.Method = "GET"
request.InstanceName = id
raw, err := s.client.WithOtsClient(func(otsClient *ots.Client) (interface{}, error) {
return otsClient.ListVpcInfoByInstance(request)
})
if err != nil {
if NotFoundError(err) {
return inst, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return inst, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
resp, _ := raw.(*ots.ListVpcInfoByInstanceResponse)
if resp.TotalCount < 1 {
return inst, WrapErrorf(Error(GetNotFoundMessage("OtsInstanceAttachment", id)), NotFoundMsg, ProviderERROR)
}
return resp.VpcInfos.VpcInfo[0], nil
}
func (s *OtsService) WaitForOtsInstanceVpc(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeOtsInstanceAttachment(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.InstanceName == id && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.InstanceName, id, ProviderERROR)
}
}
}
func (s *OtsService) ListOtsInstanceVpc(id string) (inst []ots.VpcInfo, err error) {
request := ots.CreateListVpcInfoByInstanceRequest()
request.RegionId = s.client.RegionId
request.Method = "GET"
request.InstanceName = id
raw, err := s.client.WithOtsClient(func(otsClient *ots.Client) (interface{}, error) {
return otsClient.ListVpcInfoByInstance(request)
})
if err != nil {
return inst, WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ots_instance_attachments", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
resp, _ := raw.(*ots.ListVpcInfoByInstanceResponse)
if resp.TotalCount < 1 {
return inst, WrapErrorf(Error(GetNotFoundMessage("OtsInstanceAttachment", id)), NotFoundMsg, ProviderERROR)
}
var retInfos []ots.VpcInfo
for _, vpcInfo := range resp.VpcInfos.VpcInfo {
vpcInfo.InstanceName = id
retInfos = append(retInfos, vpcInfo)
}
return retInfos, nil
}
func (s *OtsService) WaitForOtsInstance(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeOtsInstance(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.Status == convertOtsInstanceStatus(status) {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, fmt.Sprint(object.Status), status, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *OtsService) DescribeOtsInstanceTypes() (types []string, err error) {
request := ots.CreateListClusterTypeRequest()
request.Method = requests.GET
raw, err := s.client.WithOtsClient(func(otsClient *ots.Client) (interface{}, error) {
return otsClient.ListClusterType(request)
})
if err != nil {
return nil, WrapErrorf(err, DefaultErrorMsg, "alicloud_ots_instance", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
resp, _ := raw.(*ots.ListClusterTypeResponse)
if resp != nil {
return resp.ClusterTypeInfos.ClusterType, nil
}
return
}
package alicloud
import (
"encoding/json"
"log"
"regexp"
"strings"
"time"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/alibaba-cloud-sdk-go/services/polardb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type PolarDBService struct {
client *connectivity.AliyunClient
}
func (s *PolarDBService) DescribePolarDBCluster(id string) (instance *polardb.DBCluster, err error) {
request := polardb.CreateDescribeDBClustersRequest()
request.RegionId = s.client.RegionId
dbClusterIds := []string{}
dbClusterIds = append(dbClusterIds, id)
request.DBClusterIds = id
raw, err := s.client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.DescribeDBClusters(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return nil, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*polardb.DescribeDBClustersResponse)
if len(response.Items.DBCluster) < 1 {
return nil, WrapErrorf(Error(GetNotFoundMessage("Cluster", id)), NotFoundMsg, ProviderERROR)
}
return &response.Items.DBCluster[0], nil
}
func (s *PolarDBService) DescribePolarDBClusterAttribute(id string) (instance *polardb.DescribeDBClusterAttributeResponse, err error) {
request := polardb.CreateDescribeDBClusterAttributeRequest()
request.RegionId = s.client.RegionId
request.DBClusterId = id
raw, err := s.client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.DescribeDBClusterAttribute(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
return instance, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return instance, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*polardb.DescribeDBClusterAttributeResponse)
return response, nil
}
func (s *PolarDBService) DescribePolarDBAutoRenewAttribute(id string) (instance *polardb.AutoRenewAttribute, err error) {
request := polardb.CreateDescribeAutoRenewAttributeRequest()
request.RegionId = s.client.RegionId
request.DBClusterIds = id
raw, err := s.client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.DescribeAutoRenewAttribute(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
return instance, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return instance, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*polardb.DescribeAutoRenewAttributeResponse)
if len(response.Items.AutoRenewAttribute) < 1 {
return nil, WrapErrorf(Error(GetNotFoundMessage("Cluster", id)), NotFoundMsg, ProviderERROR)
}
return &response.Items.AutoRenewAttribute[0], nil
}
func (s *PolarDBService) DescribeParameters(id string) (ds *polardb.DescribeDBClusterParametersResponse, err error) {
request := polardb.CreateDescribeDBClusterParametersRequest()
request.RegionId = s.client.RegionId
request.DBClusterId = id
raw, err := s.client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.DescribeDBClusterParameters(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return nil, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*polardb.DescribeDBClusterParametersResponse)
return response, err
}
func (s *PolarDBService) GrantPolarDBAccountPrivilege(id, dbName string) error {
parts, err := ParseResourceId(id, 3)
if err != nil {
return WrapError(err)
}
request := polardb.CreateGrantAccountPrivilegeRequest()
request.RegionId = s.client.RegionId
request.DBClusterId = parts[0]
request.AccountName = parts[1]
request.DBName = dbName
request.AccountPrivilege = parts[2]
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.GrantAccountPrivilege(request)
})
if err != nil {
if IsExpectedErrors(err, OperationDeniedDBStatus) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
if err := s.WaitForPolarDBAccountPrivilege(id, dbName, Available, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
return nil
}
func (s *PolarDBService) RevokePolarDBAccountPrivilege(id, dbName string) error {
parts, err := ParseResourceId(id, 3)
if err != nil {
return WrapError(err)
}
request := polardb.CreateRevokeAccountPrivilegeRequest()
request.RegionId = s.client.RegionId
request.DBClusterId = parts[0]
request.AccountName = parts[1]
request.DBName = dbName
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.RevokeAccountPrivilege(request)
})
if err != nil {
if IsExpectedErrors(err, OperationDeniedDBStatus) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
if err := s.WaitForPolarDBAccountPrivilegeRevoked(id, dbName, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
return nil
}
func (s *PolarDBService) WaitForPolarDBAccountPrivilegeRevoked(id, dbName string, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribePolarDBAccountPrivilege(id)
if err != nil {
return WrapError(err)
}
exist := false
if object != nil {
for _, dp := range object.DatabasePrivileges {
if dp.DBName == dbName {
exist = true
break
}
}
}
if !exist {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, "", dbName, ProviderERROR)
}
}
return nil
}
func (s *PolarDBService) WaitForPolarDBAccountPrivilege(id, dbName string, status Status, timeout int) error {
parts, err := ParseResourceId(id, 3)
if err != nil {
return WrapError(err)
}
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribePolarDBAccountPrivilege(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
ready := false
if object != nil {
for _, dp := range object.DatabasePrivileges {
if dp.DBName == dbName && dp.AccountPrivilege == parts[2] {
ready = true
break
}
}
}
if status == Deleted && !ready {
break
}
if status != Deleted && ready {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, "", dbName, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *PolarDBService) DescribePolarDBAccountPrivilege(id string) (account *polardb.DBAccount, err error) {
parts, err := ParseResourceId(id, 3)
if err != nil {
err = WrapError(err)
return
}
request := polardb.CreateDescribeAccountsRequest()
request.RegionId = s.client.RegionId
request.DBClusterId = parts[0]
request.AccountName = parts[1]
invoker := NewInvoker()
invoker.AddCatcher(DBInstanceStatusCatcher)
var response *polardb.DescribeAccountsResponse
if err := invoker.Run(func() error {
raw, err := s.client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.DescribeAccounts(request)
})
if err != nil {
return WrapError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*polardb.DescribeAccountsResponse)
return nil
}); err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return nil, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
if len(response.Accounts) < 1 {
return nil, WrapErrorf(Error(GetNotFoundMessage("DBAccountPrivilege", id)), NotFoundMsg, ProviderERROR)
}
return &response.Accounts[0], nil
}
func (s *PolarDBService) WaitForPolarDBConnection(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribePolarDBConnection(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if status != Deleted && object != nil && object.ConnectionString != "" {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.ConnectionString, id, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *PolarDBService) WaitPolardbEndpointConfigEffect(id string, item map[string]string, timeout int) error {
parts, err := ParseResourceId(id, 2)
if err != nil {
return WrapError(err)
}
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
effected := true
object, err := s.DescribePolarDBInstanceNetInfo(parts[0])
if err != nil {
if NotFoundError(err) {
return WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return WrapError(err)
}
var endpoint polardb.DBEndpoint
if object != nil {
for _, o := range object {
if o.DBEndpointId == parts[1] {
endpoint = o
break
}
}
}
if value, ok := item["Nodes"]; ok {
if endpoint.Nodes != value {
effected = false
}
}
if value, ok := item["ReadWriteMode"]; ok {
if endpoint.ReadWriteMode != value {
effected = false
}
}
if value, ok := item["AutoAddNewNodes"]; ok {
if endpoint.AutoAddNewNodes != value {
effected = false
}
}
if value, ok := item["EndpointConfig"]; ok {
expectConfig := make(map[string]string)
actualConfig := make(map[string]string)
err = json.Unmarshal([]byte(value), &expectConfig)
err = json.Unmarshal([]byte(endpoint.EndpointConfig), &actualConfig)
for k, v := range expectConfig {
if subVal, ok := actualConfig[k]; !ok || subVal != v {
effected = false
break
}
}
}
if effected {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, endpoint, item, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *PolarDBService) WaitForPolarDBEndpoints(d *schema.ResourceData, status Status, endpointIds *schema.Set, timeout int) (string, error) {
var dbEndpointId string
if d.Id() != "" {
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return "", WrapError(err)
}
dbEndpointId = parts[1]
}
dbClusterId := d.Get("db_cluster_id").(string)
endpointType := d.Get("endpoint_type").(string)
newEndpoint := make(map[string]string)
newEndpoint["endpoint_type"] = endpointType
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
endpoints, err := s.DescribePolarDBInstanceNetInfo(dbClusterId)
if err != nil {
return "", WrapError(err)
}
var deleted bool
deleted = true
for _, value := range endpoints {
if status == Deleted {
if dbEndpointId == value.DBEndpointId {
deleted = false
}
continue
}
if !endpointIds.Contains(value.DBEndpointId) && value.EndpointType == endpointType {
return value.DBEndpointId, nil
}
}
if status == Deleted && deleted {
return "", nil
}
if time.Now().After(deadline) {
return "", WrapErrorf(err, WaitTimeoutMsg, dbClusterId, GetFunc(1), timeout, endpoints, newEndpoint, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *PolarDBService) DescribePolarDBConnection(id string) (*polardb.Address, error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
return nil, WrapError(err)
}
deadline := time.Now().Add(time.Duration(DefaultIntervalLong) * time.Second)
for {
object, err := s.DescribePolarDBInstanceNetInfo(parts[0])
if err != nil {
if NotFoundError(err) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return nil, WrapError(err)
}
if object != nil {
for _, o := range object {
if o.DBEndpointId == parts[1] {
for _, p := range o.AddressItems {
if p.NetType == "Public" {
return &p, nil
}
}
}
}
}
time.Sleep(DefaultIntervalMini * time.Second)
if time.Now().After(deadline) {
break
}
}
return nil, WrapErrorf(Error(GetNotFoundMessage("DBConnection", id)), NotFoundMsg, ProviderERROR)
}
func (s *PolarDBService) DescribePolarDBInstanceNetInfo(id string) ([]polardb.DBEndpoint, error) {
request := polardb.CreateDescribeDBClusterEndpointsRequest()
request.RegionId = s.client.RegionId
request.DBClusterId = id
raw, err := s.client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.DescribeDBClusterEndpoints(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return nil, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*polardb.DescribeDBClusterEndpointsResponse)
if len(response.Items) < 1 {
return nil, WrapErrorf(Error(GetNotFoundMessage("DBInstanceNetInfo", id)), NotFoundMsg, ProviderERROR)
}
return response.Items, nil
}
func (s *PolarDBService) DescribePolarDBClusterEndpoint(id string) (*polardb.DBEndpoint, error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
return nil, WrapError(err)
}
dbClusterId := parts[0]
dbEndpointId := parts[1]
request := polardb.CreateDescribeDBClusterEndpointsRequest()
request.RegionId = s.client.RegionId
request.DBClusterId = dbClusterId
request.DBEndpointId = dbEndpointId
var raw interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.DescribeDBClusterEndpoints(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
response, _ := raw.(*polardb.DescribeDBClusterEndpointsResponse)
if len(response.Items) < 1 {
return nil, WrapErrorf(Error(GetNotFoundMessage("DBEndpoint", dbEndpointId)), NotFoundMsg, ProviderERROR)
}
return &response.Items[0], nil
}
func (s *PolarDBService) DescribePolarDBClusterSSL(d *schema.ResourceData) (ssl *polardb.DescribeDBClusterSSLResponse, err error) {
parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return nil, WrapError(err)
}
dbClusterId := parts[0]
request := polardb.CreateDescribeDBClusterSSLRequest()
request.RegionId = s.client.RegionId
request.DBClusterId = dbClusterId
var raw interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.DescribeDBClusterSSL(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
response, _ := raw.(*polardb.DescribeDBClusterSSLResponse)
return response, nil
}
func (s *PolarDBService) DescribePolarDBDatabase(id string) (ds *polardb.Database, err error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
return nil, WrapError(err)
}
dbName := parts[1]
request := polardb.CreateDescribeDatabasesRequest()
request.RegionId = s.client.RegionId
request.DBClusterId = parts[0]
request.DBName = dbName
var raw interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.DescribeDatabases(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return nil, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*polardb.DescribeDatabasesResponse)
if len(response.Databases.Database) < 1 {
return nil, WrapErrorf(Error(GetNotFoundMessage("DBDatabase", dbName)), NotFoundMsg, ProviderERROR)
}
ds = &response.Databases.Database[0]
return ds, nil
}
func (s *PolarDBService) WaitForPolarDBDatabase(id string, status Status, timeout int) error {
parts, err := ParseResourceId(id, 2)
if err != nil {
return WrapError(err)
}
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribePolarDBDatabase(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
}
return WrapError(err)
}
if status != Deleted && object != nil && object.DBName == parts[1] {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.DBName, parts[1], ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *PolarDBService) WaitForPolarDBAccount(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribePolarDBAccount(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.AccountStatus == string(status) {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.AccountStatus, status, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *PolarDBService) DescribePolarDBAccount(id string) (ds *polardb.DBAccount, err error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := polardb.CreateDescribeAccountsRequest()
request.RegionId = s.client.RegionId
request.DBClusterId = parts[0]
request.AccountName = parts[1]
invoker := NewInvoker()
invoker.AddCatcher(DBInstanceStatusCatcher)
var response *polardb.DescribeAccountsResponse
if err := invoker.Run(func() error {
raw, err := s.client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.DescribeAccounts(request)
})
if err != nil {
return err
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*polardb.DescribeAccountsResponse)
return nil
}); err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return nil, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
if len(response.Accounts) < 1 {
return nil, WrapErrorf(Error(GetNotFoundMessage("DBAccount", id)), NotFoundMsg, ProviderERROR)
}
return &response.Accounts[0], nil
}
// WaitForInstance waits for instance to given status
func (s *PolarDBService) WaitForPolarDBInstance(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribePolarDBCluster(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if strings.ToLower(object.DBClusterStatus) == strings.ToLower(string(status)) {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.DBClusterStatus, status, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *PolarDBService) WaitForPolarDBConnectionPrefix(id, prefix string, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribePolarDBConnection(id)
if err != nil {
return WrapError(err)
}
parts := strings.Split(object.ConnectionString, ".")
if prefix == parts[0] {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, parts[0], prefix, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *PolarDBService) RefreshEndpointConfig(d *schema.ResourceData) error {
var config map[string]interface{}
config = make(map[string]interface{}, 0)
documented, ok := d.GetOk("endpoint_config")
if !ok {
d.Set("endpoint_config", config)
return nil
}
object, err := s.DescribePolarDBClusterEndpoint(d.Id())
if err != nil {
return WrapError(err)
}
var endpointConfig = make(map[string]interface{})
err = json.Unmarshal([]byte(object.EndpointConfig), &endpointConfig)
if err != nil {
return WrapError(err)
}
for k, v := range documented.(map[string]interface{}) {
if _, ok := endpointConfig[k]; ok {
config[k] = v
}
}
if err := d.Set("endpoint_config", config); err != nil {
return WrapError(err)
}
return nil
}
func (s *PolarDBService) RefreshParameters(d *schema.ResourceData) error {
var param []map[string]interface{}
documented, ok := d.GetOk("parameters")
if !ok {
d.Set("parameters", param)
return nil
}
object, err := s.DescribeParameters(d.Id())
if err != nil {
return WrapError(err)
}
var parameters = make(map[string]interface{})
for _, i := range object.RunningParameters.Parameter {
if i.ParameterName != "" {
parameter := map[string]interface{}{
"name": i.ParameterName,
"value": i.ParameterValue,
}
parameters[i.ParameterName] = parameter
}
}
for _, parameter := range documented.(*schema.Set).List() {
name := parameter.(map[string]interface{})["name"]
for _, value := range parameters {
if value.(map[string]interface{})["name"] == name {
param = append(param, value.(map[string]interface{}))
break
}
}
}
if err := d.Set("parameters", param); err != nil {
return WrapError(err)
}
return nil
}
func (s *PolarDBService) ModifyParameters(d *schema.ResourceData) error {
request := polardb.CreateModifyDBClusterParametersRequest()
request.RegionId = s.client.RegionId
request.DBClusterId = d.Id()
config := make(map[string]string)
allConfig := make(map[string]string)
o, n := d.GetChange("parameters")
os, ns := o.(*schema.Set), n.(*schema.Set)
add := ns.Difference(os).List()
if len(add) > 0 {
for _, i := range add {
key := i.(map[string]interface{})["name"].(string)
value := i.(map[string]interface{})["value"].(string)
config[key] = value
}
cfg, _ := json.Marshal(config)
request.Parameters = string(cfg)
// wait instance status is Normal before modifying
if err := s.WaitForCluster(d.Id(), Running, DefaultLongTimeout); err != nil {
return WrapError(err)
}
raw, err := s.client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.ModifyDBClusterParameters(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
// wait instance parameter expect after modifying
for _, i := range ns.List() {
key := i.(map[string]interface{})["name"].(string)
value := i.(map[string]interface{})["value"].(string)
allConfig[key] = value
}
if err := s.WaitForPolarDBParameter(d.Id(), DefaultTimeoutMedium, allConfig); err != nil {
return WrapError(err)
}
}
d.SetPartial("parameters")
return nil
}
func (s *PolarDBService) setClusterTags(d *schema.ResourceData) error {
if d.HasChange("tags") {
oraw, nraw := d.GetChange("tags")
o := oraw.(map[string]interface{})
n := nraw.(map[string]interface{})
create, remove := s.diffTags(s.tagsFromMap(o), s.tagsFromMap(n))
if len(remove) > 0 {
var tagKey []string
for _, v := range remove {
tagKey = append(tagKey, v.Key)
}
request := polardb.CreateUntagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.ResourceType = "cluster"
request.TagKey = &tagKey
request.RegionId = s.client.RegionId
raw, err := s.client.WithPolarDBClient(func(client *polardb.Client) (interface{}, error) {
return client.UntagResources(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
if len(create) > 0 {
request := polardb.CreateTagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.Tag = &create
request.ResourceType = "cluster"
request.RegionId = s.client.RegionId
raw, err := s.client.WithPolarDBClient(func(client *polardb.Client) (interface{}, error) {
return client.TagResources(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
d.SetPartial("tags")
}
return nil
}
func (s *PolarDBService) diffTags(oldTags, newTags []polardb.TagResourcesTag) ([]polardb.TagResourcesTag, []polardb.TagResourcesTag) {
// First, we're creating everything we have
create := make(map[string]interface{})
for _, t := range newTags {
create[t.Key] = t.Value
}
// Build the list of what to remove
var remove []polardb.TagResourcesTag
for _, t := range oldTags {
old, ok := create[t.Key]
if !ok || old != t.Value {
// Delete it!
remove = append(remove, t)
}
}
return s.tagsFromMap(create), remove
}
func (s *PolarDBService) tagsToMap(tags []polardb.TagResource) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !s.ignoreTag(t) {
result[t.TagKey] = t.TagValue
}
}
return result
}
func (s *PolarDBService) tagsFromMap(m map[string]interface{}) []polardb.TagResourcesTag {
result := make([]polardb.TagResourcesTag, 0, len(m))
for k, v := range m {
result = append(result, polardb.TagResourcesTag{
Key: k,
Value: v.(string),
})
}
return result
}
func (s *PolarDBService) ignoreTag(t polardb.TagResource) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, t.TagKey)
ok, _ := regexp.MatchString(v, t.TagValue)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific t %s (val: %s), ignoring.\n", t.TagKey, t.TagValue)
return true
}
}
return false
}
func (s *PolarDBService) DescribeTags(resourceId string, resourceType TagResourceType) (tags []polardb.TagResource, err error) {
request := polardb.CreateListTagResourcesRequest()
request.RegionId = s.client.RegionId
request.ResourceType = string(resourceType)
request.ResourceId = &[]string{resourceId}
raw, err := s.client.WithPolarDBClient(func(client *polardb.Client) (interface{}, error) {
return client.ListTagResources(request)
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, resourceId, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*polardb.ListTagResourcesResponse)
return response.TagResources.TagResource, nil
}
// WaitForCluster waits for cluster to given status
func (s *PolarDBService) WaitForCluster(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribePolarDBClusterAttribute(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if strings.ToLower(object.DBClusterStatus) == strings.ToLower(string(status)) {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.DBClusterStatus, status, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *PolarDBService) DescribeDBSecurityIps(clusterId string, dbClusterIPArrayName string) (ips []string, err error) {
request := polardb.CreateDescribeDBClusterAccessWhitelistRequest()
request.RegionId = s.client.RegionId
request.DBClusterId = clusterId
raw, err := s.client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.DescribeDBClusterAccessWhitelist(request)
})
if err != nil {
return ips, WrapErrorf(err, DefaultErrorMsg, clusterId, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
resp, _ := raw.(*polardb.DescribeDBClusterAccessWhitelistResponse)
var ipstr, separator string
ipsMap := make(map[string]string)
for _, ip := range resp.Items.DBClusterIPArray {
if ip.DBClusterIPArrayName == dbClusterIPArrayName {
ipstr += separator + ip.SecurityIps
separator = COMMA_SEPARATED
}
}
for _, ip := range strings.Split(ipstr, COMMA_SEPARATED) {
ipsMap[ip] = ip
}
var finalIps []string
if len(ipsMap) > 0 {
for key := range ipsMap {
finalIps = append(finalIps, key)
}
}
return finalIps, nil
}
func (s *PolarDBService) ModifyDBSecurityIps(clusterId, ips string) error {
request := polardb.CreateModifyDBClusterAccessWhitelistRequest()
request.RegionId = s.client.RegionId
request.DBClusterId = clusterId
request.SecurityIps = ips
raw, err := s.client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.ModifyDBClusterAccessWhitelist(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, clusterId, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
if err := s.WaitForCluster(clusterId, Running, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
return nil
}
func (s *PolarDBService) DescribeBackupPolicy(id string) (policy *polardb.DescribeBackupPolicyResponse, err error) {
request := polardb.CreateDescribeBackupPolicyRequest()
request.DBClusterId = id
request.RegionId = s.client.RegionId
raw, err := s.client.WithPolarDBClient(func(polardbClient *polardb.Client) (interface{}, error) {
return polardbClient.DescribeBackupPolicy(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return policy, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return raw.(*polardb.DescribeBackupPolicyResponse), nil
}
func (s *PolarDBService) ModifyDBBackupPolicy(clusterId, backupTime, backupPeriod string) error {
request := polardb.CreateModifyBackupPolicyRequest()
request.RegionId = s.client.RegionId
request.DBClusterId = clusterId
request.PreferredBackupPeriod = backupPeriod
request.PreferredBackupTime = backupTime
raw, err := s.client.WithPolarDBClient(func(polardbClient *polardb.Client) (interface{}, error) {
return polardbClient.ModifyBackupPolicy(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, clusterId, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
if err := s.WaitForCluster(clusterId, Running, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
return nil
}
func (s *PolarDBService) DescribeDBAuditLogCollectorStatus(id string) (collectorStatus string, err error) {
request := polardb.CreateDescribeDBClusterAuditLogCollectorRequest()
request.RegionId = s.client.RegionId
request.DBClusterId = id
raw, err := s.client.WithPolarDBClient(func(polardbClient *polardb.Client) (interface{}, error) {
return polardbClient.DescribeDBClusterAuditLogCollector(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBClusterId.NotFound"}) {
return "", WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return collectorStatus, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response := raw.(*polardb.DescribeDBClusterAuditLogCollectorResponse)
return response.CollectorStatus, nil
}
func (s *PolarDBService) PolarDBClusterStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribePolarDBClusterAttribute(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.DBClusterStatus == failState {
return object, object.DBClusterStatus, WrapError(Error(FailedToReachTargetStatus, object.DBClusterStatus))
}
}
return object, object.DBClusterStatus, nil
}
}
// WaitForDBParameter waits for instance parameter to given value.
// Status of DB instance is Running after ModifyParameters API was
// call, so we can not just wait for instance status become
// Running, we should wait until parameters have expected values.
func (s *PolarDBService) WaitForPolarDBParameter(clusterId string, timeout int, expects map[string]string) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeParameters(clusterId)
if err != nil {
return WrapError(err)
}
var actuals = make(map[string]string)
for _, i := range object.RunningParameters.Parameter {
actuals[i.ParameterName] = i.ParameterValue
}
match := true
got_value := ""
expected_value := ""
for name, expect := range expects {
if actual, ok := actuals[name]; ok {
if expect != actual {
match = false
got_value = actual
expected_value = expect
break
}
} else {
match = false
}
}
if match {
break
}
time.Sleep(DefaultIntervalShort * time.Second)
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, clusterId, GetFunc(1), timeout, got_value, expected_value, ProviderERROR)
}
}
return nil
}
func (s *PolarDBService) DescribeDBClusterTDE(id string) (map[string]interface{}, error) {
action := "DescribeDBClusterTDE"
request := map[string]interface{}{
"DBClusterId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
conn, err := s.client.NewPolarDBClient()
if err != nil {
return nil, WrapError(err)
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-08-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return nil, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
return response, nil
}
func (s *PolarDBService) WaitForPolarDBTDEStatus(id string, status string, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Minute)
for {
object, err := s.DescribeDBClusterTDE(id)
if err != nil {
return WrapError(err)
}
if object["TDEStatus"] == status {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object, status, ProviderERROR)
}
time.Sleep(DefaultIntervalMedium * time.Second)
}
return nil
}
func (s *PolarDBService) WaitForPolarDBNodeClass(id string, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
clusters, err := s.DescribePolarDBCluster(id)
if err != nil {
return WrapError(err)
}
clusterAttribute, err := s.DescribePolarDBClusterAttribute(id)
if err != nil {
return WrapError(err)
}
if len(clusters.DBNodes.DBNode) == len(clusterAttribute.DBNodes) {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, ProviderERROR)
}
time.Sleep(DefaultIntervalMedium * time.Second)
}
return nil
}
func (s *PolarDBService) WaitForPolarDBPayType(id string, status string, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
clusters, err := s.DescribePolarDBCluster(id)
if err != nil {
return WrapError(err)
}
if clusters.PayType == status {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, clusters, status, ProviderERROR)
}
time.Sleep(DefaultIntervalMedium * time.Second)
}
return nil
}
func (s *PolarDBService) PolarDBClusterTDEStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeDBClusterTDE(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["TDEStatus"].(string) == failState {
return object, object["TDEStatus"].(string), WrapError(Error(FailedToReachTargetStatus, object["TDEStatus"].(string)))
}
}
return object, object["TDEStatus"].(string), nil
}
}
func (s *PolarDBService) DescribeDBSecurityGroups(clusterId string) ([]string, error) {
request := polardb.CreateDescribeDBClusterAccessWhitelistRequest()
request.RegionId = s.client.RegionId
request.DBClusterId = clusterId
raw, err := s.client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.DescribeDBClusterAccessWhitelist(request)
})
if err != nil {
return nil, WrapErrorf(err, DefaultErrorMsg, clusterId, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
resp, _ := raw.(*polardb.DescribeDBClusterAccessWhitelistResponse)
groups := make([]string, 0)
dbClusterSecurityGroups := resp.DBClusterSecurityGroups.DBClusterSecurityGroup
for _, group := range dbClusterSecurityGroups {
groups = append(groups, group.SecurityGroupId)
}
return groups, nil
}
func (s *PolarDBService) ModifyDBAccessWhitelistSecurityIps(d *schema.ResourceData) error {
if l, ok := d.GetOk("db_cluster_ip_array"); ok {
for _, e := range l.(*schema.Set).List() {
pack := e.(map[string]interface{})
//ips expand string list
ipList := expandStringList(pack["security_ips"].(*schema.Set).List())
ipstr := strings.Join(ipList[:], COMMA_SEPARATED)
// default disable connect from outside
if ipstr == "" {
ipstr = LOCAL_HOST_IP
}
request := polardb.CreateModifyDBClusterAccessWhitelistRequest()
request.RegionId = s.client.RegionId
request.DBClusterId = d.Id()
request.SecurityIps = ipstr
request.DBClusterIPArrayName = pack["db_cluster_ip_array_name"].(string)
request.ModifyMode = pack["modify_mode"].(string)
raw, err := s.client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.ModifyDBClusterAccessWhitelist(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
if err := s.WaitForCluster(d.Id(), Running, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
}
}
d.SetPartial("db_cluster_ip_array")
return nil
}
func (s *PolarDBService) DBClusterIPArrays(d *schema.ResourceData, attribute string, dbClusterIPArrayName string) error {
request := polardb.CreateDescribeDBClusterAccessWhitelistRequest()
request.RegionId = s.client.RegionId
request.DBClusterId = d.Id()
raw, err := s.client.WithPolarDBClient(func(polarDBClient *polardb.Client) (interface{}, error) {
return polarDBClient.DescribeDBClusterAccessWhitelist(request)
})
if err != nil {
return WrapError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*polardb.DescribeDBClusterAccessWhitelistResponse)
dbClusterIPArray := response.Items.DBClusterIPArray
var dbClusterIPArrays = make([]map[string]interface{}, 0, len(dbClusterIPArray))
for _, i := range dbClusterIPArray {
if i.DBClusterIPArrayName == dbClusterIPArrayName {
l := map[string]interface{}{
"db_cluster_ip_array_name": i.DBClusterIPArrayName,
"security_ips": convertPolarDBIpsSetToString(i.SecurityIps),
}
dbClusterIPArrays = append(dbClusterIPArrays, l)
}
}
if err := d.Set(attribute, dbClusterIPArrays); err != nil {
return WrapError(err)
}
return nil
}
func convertPolarDBIpsSetToString(sourceIps string) []string {
ipsMap := make(map[string]string)
for _, ip := range strings.Split(sourceIps, COMMA_SEPARATED) {
ipsMap[ip] = ip
}
var ips []string
if len(ipsMap) > 0 {
for key := range ipsMap {
ips = append(ips, key)
}
}
return ips
}
package alicloud
import (
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type PrivatelinkService struct {
client *connectivity.AliyunClient
}
func (s *PrivatelinkService) ListVpcEndpointServiceResources(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewPrivatelinkClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListVpcEndpointServiceResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ServiceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"EndpointServiceNotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("PrivatelinkVpcEndpointService", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *PrivatelinkService) DescribePrivatelinkVpcEndpointService(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewPrivatelinkClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetVpcEndpointServiceAttribute"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ServiceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"EndpointServiceNotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("PrivatelinkVpcEndpointService", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *PrivatelinkService) PrivatelinkVpcEndpointServiceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribePrivatelinkVpcEndpointService(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["ServiceStatus"].(string) == failState {
return object, object["ServiceStatus"].(string), WrapError(Error(FailedToReachTargetStatus, object["ServiceStatus"].(string)))
}
}
return object, object["ServiceStatus"].(string), nil
}
}
func (s *PrivatelinkService) DescribePrivatelinkVpcEndpointConnection(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewPrivatelinkClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListVpcEndpointConnections"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"EndpointId": parts[1],
"ServiceId": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"EndpointServiceNotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("PrivatelinkVpcEndpointConnection", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Connections", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Connections", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("PrivateLink", id)), NotFoundWithResponse, response)
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *PrivatelinkService) PrivatelinkVpcEndpointConnectionStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribePrivatelinkVpcEndpointConnection(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["ConnectionStatus"].(string) == failState {
return object, object["ConnectionStatus"].(string), WrapError(Error(FailedToReachTargetStatus, object["ConnectionStatus"].(string)))
}
}
return object, object["ConnectionStatus"].(string), nil
}
}
func (s *PrivatelinkService) ListVpcEndpointSecurityGroups(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewPrivatelinkClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListVpcEndpointSecurityGroups"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"EndpointId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"EndpointNotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("PrivatelinkVpcEndpoint", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *PrivatelinkService) ListVpcEndpointZones(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewPrivatelinkClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListVpcEndpointZones"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"EndpointId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"EndpointNotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("PrivatelinkVpcEndpoint", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *PrivatelinkService) DescribePrivatelinkVpcEndpoint(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewPrivatelinkClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetVpcEndpointAttribute"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"EndpointId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("GetVpcEndpointAttribute")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"EndpointNotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("PrivatelinkVpcEndpoint", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *PrivatelinkService) PrivatelinkVpcEndpointStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribePrivatelinkVpcEndpoint(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["EndpointStatus"].(string) == failState {
return object, object["EndpointStatus"].(string), WrapError(Error(FailedToReachTargetStatus, object["EndpointStatus"].(string)))
}
}
return object, object["EndpointStatus"].(string), nil
}
}
func (s *PrivatelinkService) DescribePrivatelinkVpcEndpointServiceResource(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewPrivatelinkClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListVpcEndpointServiceResources"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ServiceId": parts[0],
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"EndpointServiceNotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("PrivatelinkVpcEndpointServiceResource", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Resources", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Resources", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("PrivateLink", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if v.(map[string]interface{})["ResourceId"].(string) == parts[1] {
return v.(map[string]interface{}), nil
}
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
return object, nil
}
return
}
func (s *PrivatelinkService) DescribePrivatelinkVpcEndpointServiceUser(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewPrivatelinkClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListVpcEndpointServiceUsers"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ServiceId": parts[0],
"UserId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"EndpointServiceNotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("PrivatelinkVpcEndpointServiceUser", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Users", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Users", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("PrivateLink", id)), NotFoundWithResponse, response)
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *PrivatelinkService) DescribePrivatelinkVpcEndpointZone(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewPrivatelinkClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListVpcEndpointZones"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"EndpointId": parts[0],
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-04-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"EndpointNotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("PrivatelinkVpcEndpointZone", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Zones", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Zones", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("PrivateLink", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if v.(map[string]interface{})["ZoneId"].(string) == parts[1] {
return v.(map[string]interface{}), nil
}
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
return object, nil
}
return
}
func (s *PrivatelinkService) PrivatelinkVpcEndpointZoneStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribePrivatelinkVpcEndpointZone(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["ZoneStatus"].(string) == failState {
return object, object["ZoneStatus"].(string), WrapError(Error(FailedToReachTargetStatus, object["ZoneStatus"].(string)))
}
}
return object, object["ZoneStatus"].(string), nil
}
}
package alicloud
import (
"fmt"
"log"
"strconv"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"time"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
)
type PvtzService struct {
client *connectivity.AliyunClient
}
func (s *PvtzService) DescribePvtzZoneBasic(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewPvtzClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeZoneInfo"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ZoneId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"Zone.Invalid.Id", "Zone.Invalid.UserId", "Zone.NotExists", "ZoneVpc.NotExists.VpcId"}) {
err = WrapErrorf(Error(GetNotFoundMessage("PvtzZone", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *PvtzService) DescribePvtzZoneAttachment(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewPvtzClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeZoneInfo"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ZoneId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"Zone.Invalid.Id", "Zone.Invalid.UserId", "Zone.NotExists", "ZoneVpc.NotExists.VpcId"}) {
err = WrapErrorf(Error(GetNotFoundMessage("PvtzZoneAttachment", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *PvtzService) WaitForZoneAttachment(id string, vpcIdMap map[string]string, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
var vpcId string
for {
object, err := s.DescribePvtzZoneAttachment(id)
if err != nil && !NotFoundError(err) {
return WrapError(err)
}
equal := true
vpcs := object["BindVpcs"].(map[string]interface{})["Vpc"].([]interface{})
if len(vpcs) == len(vpcIdMap) {
for _, vpc := range vpcs {
vpc := vpc.(map[string]interface{})
if _, ok := vpcIdMap[vpc["VpcId"].(string)]; !ok {
equal = false
vpcId = vpc["VpcId"].(string)
break
}
}
} else {
equal = false
}
if equal {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, "", vpcId, ProviderERROR)
}
}
return nil
}
func (s *PvtzService) DescribePvtzZoneRecord(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewPvtzClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeZoneRecords"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ZoneId": parts[1],
"PageNumber": 1,
"PageSize": 20,
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"System.Busy", "ServiceUnavailable", "Throttling.User"}) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"Zone.Invalid.Id", "Zone.Invalid.UserId", "Zone.NotExists", "ZoneVpc.NotExists.VpcId"}) {
err = WrapErrorf(Error(GetNotFoundMessage("PvtzZoneRecord", id)), NotFoundMsg, ProviderERROR)
return resource.NonRetryableError(err)
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Records.Record", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Records.Record", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("PrivateZone", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(formatInt(v.(map[string]interface{})["RecordId"])) == parts[0] || fmt.Sprint(v.(map[string]interface{})["RecordId"]) == parts[0] {
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
return
}
func (s *PvtzService) WaitForPvtzZone(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribePvtzZone(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object["ZoneId"] == id {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object["ZoneId"], id, ProviderERROR)
}
}
}
func (s *PvtzService) WaitForPvtzZoneAttachment(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribePvtzZoneAttachment(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object["ZoneId"] == id {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object["ZoneId"], id, ProviderERROR)
}
}
}
func (s *PvtzService) WaitForPvtzZoneRecord(id string, status Status, timeout int) error {
parts, err := ParseResourceId(id, 2)
if err != nil {
return WrapError(err)
}
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribePvtzZoneRecord(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if strconv.FormatInt(object["RecordId"].(int64), 10) == parts[0] {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, strconv.FormatInt(object["RecordId"].(int64), 10), id, ProviderERROR)
}
}
}
func (s *PvtzService) DescribePvtzUserVpcAuthorization(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewPvtzClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeUserVpcAuthorizations"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"AuthType": parts[1],
"AuthorizedUserId": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"System.Busy"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("PrivateZone:UserVpcAuthorization", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Users", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Users", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("PrivateZone", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["AuthType"]) != parts[1] {
return object, WrapErrorf(Error(GetNotFoundMessage("PrivateZone", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *PvtzService) DescribePvtzEndpoint(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewPvtzClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeResolverEndpoint"
request := map[string]interface{}{
"EndpointId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ResolverEndpoint.NotExists"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("PrivateZone:Endpoint", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *PvtzService) PvtzEndpointStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribePvtzEndpoint(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *PvtzService) DescribePvtzRule(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewPvtzClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeResolverRule"
request := map[string]interface{}{
"RuleId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ResolverRule.NotExists"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("PrivateZone:Rule", id)), NotFoundMsg, ProviderERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *PvtzService) DescribePvtzRuleAttachment(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewPvtzClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeResolverRule"
request := map[string]interface{}{
"RuleId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ResolverRule.NotExists"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("PrivateZone:RuleAttachment", id)), NotFoundMsg, ProviderERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *PvtzService) DescribeSyncEcsHostTask(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewPvtzClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeSyncEcsHostTask"
request := map[string]interface{}{
"ZoneId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"System.Busy", "Ecs.SyncTask.NotExists", "ServiceUnavailable", "Throttling.User"}) {
err = WrapErrorf(Error(GetNotFoundMessage("PvtzZone", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *PvtzService) DescribePvtzZone(id string) (object map[string]interface{}, err error) {
object, err = s.DescribePvtzZoneBasic(id)
if err != nil {
return nil, WrapError(err)
}
syncObj, err := s.DescribeSyncEcsHostTask(id)
if err != nil {
if NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_pvtz_zone pvtzService.DescribeSyncEcsHostTask Failed!!! %s", err)
return object, nil
}
return nil, WrapError(err)
}
object["SyncHostTask"] = syncObj
return object, nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type QuickbiPublicService struct {
client *connectivity.AliyunClient
}
func (s *QuickbiPublicService) DescribeQuickBiUser(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewQuickbiClient()
if err != nil {
return nil, WrapError(err)
}
action := "QueryUserInfoByUserId"
request := map[string]interface{}{
"UserId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-08-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"User.Not.In.Organization"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("QuickBI:User", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Result", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Result", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *QuickbiPublicService) QueryUserInfoByUserId(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewQuickbiClient()
if err != nil {
return nil, WrapError(err)
}
action := "QueryUserInfoByUserId"
request := map[string]interface{}{
"UserId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-08-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"User.Not.In.Organization"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("QuickBI:User", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Result", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Result", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
)
type QuotasService struct {
client *connectivity.AliyunClient
}
func (s *QuotasService) DescribeQuotasQuotaAlarm(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewQuotasClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetQuotaAlarm"
request := map[string]interface{}{
"SourceIp": s.client.SourceIp,
"RegionId": s.client.RegionId,
"AlarmId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-05-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.QuotaAlarm", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.QuotaAlarm", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *QuotasService) DescribeQuotasQuotaApplication(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewQuotasClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetQuotaApplication"
request := map[string]interface{}{
"SourceIp": s.client.SourceIp,
"RegionId": s.client.RegionId,
"ApplicationId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-05-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.QuotaApplication", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.QuotaApplication", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
r_kvstore "github.com/aliyun/alibaba-cloud-sdk-go/services/r-kvstore"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type R_kvstoreService struct {
client *connectivity.AliyunClient
}
type RKvstoreService struct {
client *connectivity.AliyunClient
}
func (s *R_kvstoreService) DescribeInstanceSSL(id string) (object r_kvstore.DescribeInstanceSSLResponse, err error) {
request := r_kvstore.CreateDescribeInstanceSSLRequest()
request.RegionId = s.client.RegionId
request.InstanceId = id
raw, err := s.client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.DescribeInstanceSSL(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstance.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("KvstoreInstance", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*r_kvstore.DescribeInstanceSSLResponse)
return *response, nil
}
func (s *R_kvstoreService) DescribeSecurityIps(id string) (object r_kvstore.SecurityIpGroup, err error) {
request := r_kvstore.CreateDescribeSecurityIpsRequest()
request.RegionId = s.client.RegionId
request.InstanceId = id
raw, err := s.client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.DescribeSecurityIps(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstance.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("KvstoreInstance", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*r_kvstore.DescribeSecurityIpsResponse)
if len(response.SecurityIpGroups.SecurityIpGroup) < 1 {
err = WrapErrorf(Error(GetNotFoundMessage("KvstoreInstance", id)), NotFoundMsg, ProviderERROR, response.RequestId)
return object, err
}
return response.SecurityIpGroups.SecurityIpGroup[0], nil
}
func (s *R_kvstoreService) SetResourceTags(d *schema.ResourceData, resourceType string) error {
oldItems, newItems := d.GetChange("tags")
added := make([]r_kvstore.TagResourcesTag, 0)
for key, value := range newItems.(map[string]interface{}) {
added = append(added, r_kvstore.TagResourcesTag{
Key: key,
Value: value.(string),
})
}
removed := make([]string, 0)
for key, _ := range oldItems.(map[string]interface{}) {
removed = append(removed, key)
}
// 对系统 Tag 进行过滤
removedTagKeys := make([]string, 0)
for _, v := range removed {
if !ignoredTags(v, "") {
removedTagKeys = append(removedTagKeys, v)
}
}
if len(removedTagKeys) > 0 {
request := r_kvstore.CreateUntagResourcesRequest()
request.RegionId = s.client.RegionId
request.ResourceId = &[]string{d.Id()}
request.ResourceType = resourceType
request.TagKey = &removedTagKeys
raw, err := s.client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.UntagResources(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDbInstanceId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
request := r_kvstore.CreateTagResourcesRequest()
request.RegionId = s.client.RegionId
request.ResourceId = &[]string{d.Id()}
request.ResourceType = resourceType
request.Tag = &added
raw, err := s.client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.TagResources(request)
})
addDebug(request.GetActionName(), raw)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDbInstanceId.NotFound"}) {
return nil
}
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
return nil
}
func (s *R_kvstoreService) DescribeInstanceAutoRenewalAttribute(id string) (object r_kvstore.Item, err error) {
request := r_kvstore.CreateDescribeInstanceAutoRenewalAttributeRequest()
request.RegionId = s.client.RegionId
request.DBInstanceId = id
raw, err := s.client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.DescribeInstanceAutoRenewalAttribute(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstance.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("KvstoreInstance", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*r_kvstore.DescribeInstanceAutoRenewalAttributeResponse)
if len(response.Items.Item) < 1 {
err = WrapErrorf(Error(GetNotFoundMessage("KvstoreInstance", id)), NotFoundMsg, ProviderERROR, response.RequestId)
return object, err
}
return response.Items.Item[0], nil
}
func (s *R_kvstoreService) DescribeSecurityGroupConfiguration(id string) (object r_kvstore.ItemsInDescribeSecurityGroupConfiguration, err error) {
request := r_kvstore.CreateDescribeSecurityGroupConfigurationRequest()
request.RegionId = s.client.RegionId
request.InstanceId = id
raw, err := s.client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.DescribeSecurityGroupConfiguration(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstance.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("KvstoreInstance", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*r_kvstore.DescribeSecurityGroupConfigurationResponse)
if len(response.Items.EcsSecurityGroupRelation) < 1 {
err = WrapErrorf(Error(GetNotFoundMessage("KvstoreInstance", id)), NotFoundMsg, ProviderERROR, response.RequestId)
return object, err
}
return response.Items, nil
}
func (s *R_kvstoreService) DescribeKvstoreInstance(id string) (object r_kvstore.DBInstanceAttribute, err error) {
request := r_kvstore.CreateDescribeInstanceAttributeRequest()
request.RegionId = s.client.RegionId
request.InstanceId = id
raw, err := s.client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.DescribeInstanceAttribute(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidInstanceId.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("KvstoreInstance", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*r_kvstore.DescribeInstanceAttributeResponse)
if len(response.Instances.DBInstanceAttribute) < 1 {
err = WrapErrorf(Error(GetNotFoundMessage("KvstoreInstance", id)), NotFoundMsg, ProviderERROR, response.RequestId)
return object, err
}
return response.Instances.DBInstanceAttribute[0], nil
}
func (s *R_kvstoreService) KvstoreInstanceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeKvstoreInstance(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.InstanceStatus == failState {
return object, object.InstanceStatus, WrapError(Error(FailedToReachTargetStatus, object.InstanceStatus))
}
}
return object, object.InstanceStatus, nil
}
}
func (s *R_kvstoreService) DescribeKvstoreConnection(id string) (object []r_kvstore.InstanceNetInfo, err error) {
request := r_kvstore.CreateDescribeDBInstanceNetInfoRequest()
request.RegionId = s.client.RegionId
request.InstanceId = id
raw, err := s.client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.DescribeDBInstanceNetInfo(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidInstanceId.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("KvstoreConnection", id)), NotFoundMsg, ProviderERROR)
return
}
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*r_kvstore.DescribeDBInstanceNetInfoResponse)
if len(response.NetInfoItems.InstanceNetInfo) < 1 {
err = WrapErrorf(Error(GetNotFoundMessage("KvstoreConnection", id)), NotFoundMsg, ProviderERROR, response.RequestId)
return
}
return response.NetInfoItems.InstanceNetInfo, nil
}
func (s *R_kvstoreService) DescribeKvstoreAccount(id string) (object r_kvstore.Account, err error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := r_kvstore.CreateDescribeAccountsRequest()
request.RegionId = s.client.RegionId
request.AccountName = parts[1]
request.InstanceId = parts[0]
raw, err := s.client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.DescribeAccounts(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidInstanceId.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("KvstoreAccount", id)), NotFoundMsg, ProviderERROR)
return
}
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*r_kvstore.DescribeAccountsResponse)
if len(response.Accounts.Account) < 1 {
err = WrapErrorf(Error(GetNotFoundMessage("KvstoreAccount", id)), NotFoundMsg, ProviderERROR, response.RequestId)
return
}
return response.Accounts.Account[0], nil
}
func (s *R_kvstoreService) KvstoreAccountStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeKvstoreAccount(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.AccountStatus == failState {
return object, object.AccountStatus, WrapError(Error(FailedToReachTargetStatus, object.AccountStatus))
}
}
return object, object.AccountStatus, nil
}
}
func (s *R_kvstoreService) DescribeBackupPolicy(id string) (object r_kvstore.DescribeBackupPolicyResponse, err error) {
request := r_kvstore.CreateDescribeBackupPolicyRequest()
request.RegionId = s.client.RegionId
request.InstanceId = id
raw, err := s.client.WithRKvstoreClient(func(r_kvstoreClient *r_kvstore.Client) (interface{}, error) {
return r_kvstoreClient.DescribeBackupPolicy(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstance.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("KvstoreInstance", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*r_kvstore.DescribeBackupPolicyResponse)
return *response, nil
}
func (s *RKvstoreService) DescribeKvstoreAuditLogConfig(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewRedisaClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeAuditLogConfig"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"InstanceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidInstanceId.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Redis:AuditLogConfig", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *RKvstoreService) DescribeInstanceAttribute(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewRedisaClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeInstanceAttribute"
request := map[string]interface{}{
"InstanceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-01-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidInstanceId.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Redis:AuditLogConfig", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Instances.DBInstanceAttribute", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Instances.DBInstanceAttribute", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("Redis", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["InstanceId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("Redis", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *RKvstoreService) KvstoreAuditLogConfigStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeInstanceAttribute(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["InstanceStatus"]) == failState {
return object, fmt.Sprint(object["InstanceStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["InstanceStatus"])))
}
}
return object, fmt.Sprint(object["InstanceStatus"]), nil
}
}
package alicloud
import (
"encoding/json"
"fmt"
"reflect"
"sort"
"strconv"
"strings"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ram"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type Effect string
const (
Allow Effect = "Allow"
Deny Effect = "Deny"
)
type Principal struct {
Service []string
RAM []string
}
type RolePolicyStatement struct {
Effect Effect
Action string
Principal Principal
}
type RolePolicy struct {
Statement []RolePolicyStatement
Version string
}
type PolicyStatement struct {
Effect Effect
Action interface{}
Resource interface{}
}
type Policy struct {
Statement []PolicyStatement
Version string
}
type RamService struct {
client *connectivity.AliyunClient
}
func (s *RamService) ParseRolePolicyDocument(policyDocument string) (RolePolicy, error) {
var policy RolePolicy
err := json.Unmarshal([]byte(policyDocument), &policy)
if err != nil {
return RolePolicy{}, WrapError(err)
}
return policy, nil
}
func (s *RamService) ParsePolicyDocument(policyDocument string) (statement []map[string]interface{}, version string, err error) {
policy := Policy{}
err = json.Unmarshal([]byte(policyDocument), &policy)
if err != nil {
err = WrapError(err)
return
}
version = policy.Version
statement = make([]map[string]interface{}, 0, len(policy.Statement))
for _, v := range policy.Statement {
item := make(map[string]interface{})
item["effect"] = v.Effect
if val, ok := v.Action.([]interface{}); ok {
item["action"] = val
} else {
item["action"] = []interface{}{v.Action}
}
if val, ok := v.Resource.([]interface{}); ok {
item["resource"] = val
} else {
item["resource"] = []interface{}{v.Resource}
}
statement = append(statement, item)
}
return
}
func (s *RamService) AssembleRolePolicyDocument(ramUser, service []interface{}, version string) (string, error) {
services := expandStringList(service)
users := expandStringList(ramUser)
statement := RolePolicyStatement{
Effect: Allow,
Action: "sts:AssumeRole",
Principal: Principal{
RAM: users,
Service: services,
},
}
policy := RolePolicy{
Version: version,
Statement: []RolePolicyStatement{statement},
}
data, err := json.Marshal(policy)
if err != nil {
return "", WrapError(err)
}
return string(data), nil
}
func (s *RamService) AssemblePolicyDocument(document []interface{}, version string) (string, error) {
var statements []PolicyStatement
for _, v := range document {
doc := v.(map[string]interface{})
actions := expandStringList(doc["action"].([]interface{}))
resources := expandStringList(doc["resource"].([]interface{}))
statement := PolicyStatement{
Effect: Effect(doc["effect"].(string)),
Action: actions,
Resource: resources,
}
statements = append(statements, statement)
}
policy := Policy{
Version: version,
Statement: statements,
}
data, err := json.Marshal(policy)
if err != nil {
return "", WrapError(err)
}
return string(data), nil
}
// Judge whether the role policy contains service "ecs.aliyuncs.com"
func (s *RamService) JudgeRolePolicyPrincipal(roleName string) error {
request := ram.CreateGetRoleRequest()
request.RegionId = s.client.RegionId
request.RoleName = roleName
raw, err := s.client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.GetRole(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, roleName, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
resp, _ := raw.(*ram.GetRoleResponse)
policy, err := s.ParseRolePolicyDocument(resp.Role.AssumeRolePolicyDocument)
if err != nil {
return WrapError(err)
}
for _, v := range policy.Statement {
for _, val := range v.Principal.Service {
if strings.Trim(val, " ") == "ecs.aliyuncs.com" {
return nil
}
}
}
return WrapError(fmt.Errorf("Role policy services must contains 'ecs.aliyuncs.com', Now is \n%v.", resp.Role.AssumeRolePolicyDocument))
}
func (s *RamService) GetIntersection(dataMap []map[string]interface{}, allDataMap map[string]interface{}) (allData []interface{}) {
for _, v := range dataMap {
if len(v) > 0 {
for key := range allDataMap {
if _, ok := v[key]; !ok {
allDataMap[key] = nil
}
}
}
}
for _, v := range allDataMap {
if v != nil {
allData = append(allData, v)
}
}
return
}
func (s *RamService) DescribeRamUser(id string) (*ram.UserInGetUser, error) {
user := &ram.UserInGetUser{}
listUsersRequest := ram.CreateListUsersRequest()
listUsersRequest.RegionId = s.client.RegionId
listUsersRequest.MaxItems = requests.NewInteger(100)
var userName string
for {
raw, err := s.client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.ListUsers(listUsersRequest)
})
if err != nil {
return user, WrapErrorf(err, DefaultErrorMsg, id, listUsersRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(listUsersRequest.GetActionName(), raw, listUsersRequest.RegionId, listUsersRequest)
response, _ := raw.(*ram.ListUsersResponse)
for _, user := range response.Users.User {
// the d.Id() has changed from userName to userId since v1.44.0, add the logic for backward compatibility.
if user.UserId == id || user.UserName == id {
userName = user.UserName
break
}
}
if userName != "" || !response.IsTruncated {
break
}
listUsersRequest.Marker = response.Marker
}
if userName == "" {
return user, WrapErrorf(fmt.Errorf("there is no ram user with id or name is %s", id), NotFoundMsg, AlibabaCloudSdkGoERROR)
}
getUserRequest := ram.CreateGetUserRequest()
getUserRequest.RegionId = s.client.RegionId
getUserRequest.UserName = userName
raw, err := s.client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.GetUser(getUserRequest)
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist.User"}) {
return user, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return user, WrapErrorf(err, DefaultErrorMsg, id, getUserRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(getUserRequest.GetActionName(), raw, getUserRequest.RpcRequest, getUserRequest)
response, _ := raw.(*ram.GetUserResponse)
return &response.User, nil
}
func (s *RamService) WaitForRamUser(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeRamUser(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
}
return WrapError(err)
}
if object.UserId == id {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, DefaultTimeoutMsg, id, GetFunc(1), ProviderERROR)
}
}
return nil
}
func (s *RamService) DescribeRamGroupMembership(id string) (*ram.ListUsersForGroupResponse, error) {
response := &ram.ListUsersForGroupResponse{}
request := ram.CreateListUsersForGroupRequest()
request.RegionId = s.client.RegionId
request.GroupName = id
raw, err := s.client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.ListUsersForGroup(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response = raw.(*ram.ListUsersForGroupResponse)
if len(response.Users.User) > 0 {
return response, nil
}
return response, WrapErrorf(err, NotFoundMsg, ProviderERROR)
}
func (s *RamService) WaitForRamGroupMembership(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeRamGroupMembership(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, strconv.Itoa(len(object.Users.User)), status, ProviderERROR)
}
}
}
func (s *RamService) DescribeRamLoginProfile(id string) (*ram.GetLoginProfileResponse, error) {
response := &ram.GetLoginProfileResponse{}
request := ram.CreateGetLoginProfileRequest()
request.RegionId = s.client.RegionId
request.UserName = id
raw, err := s.client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.GetLoginProfile(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist.User.LoginProfile", "EntityNotExist.User"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response = raw.(*ram.GetLoginProfileResponse)
return response, nil
}
func (s *RamService) WaitForRamLoginProfile(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeRamLoginProfile(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.LoginProfile.UserName == id {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.LoginProfile.UserName, id, ProviderERROR)
}
}
}
func (s *RamService) DescribeRamGroupPolicyAttachment(id string) (*ram.PolicyInListPoliciesForGroup, error) {
response := &ram.PolicyInListPoliciesForGroup{}
request := ram.CreateListPoliciesForGroupRequest()
request.RegionId = s.client.RegionId
parts, err := ParseResourceId(id, 4)
if err != nil {
return response, WrapError(err)
}
request.GroupName = parts[3]
raw, err := s.client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.ListPoliciesForGroup(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist.Group"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
listPoliciesForGroupResponse, _ := raw.(*ram.ListPoliciesForGroupResponse)
if len(listPoliciesForGroupResponse.Policies.Policy) > 0 {
for _, v := range listPoliciesForGroupResponse.Policies.Policy {
if v.PolicyType == parts[2] && (v.PolicyName == parts[1] || strings.ToLower(v.PolicyName) == strings.ToLower(parts[1])) {
return &v, nil
}
}
}
return response, WrapErrorf(err, NotFoundMsg, ProviderERROR)
}
func (s *RamService) WaitForRamGroupPolicyAttachment(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
parts, err := ParseResourceId(id, 4)
if err != nil {
return WrapError(err)
}
for {
object, err := s.DescribeRamGroupPolicyAttachment(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.PolicyName, parts[1], ProviderERROR)
}
}
}
func (s *RamService) DescribeRamAccountAlias(id string) (*ram.GetAccountAliasResponse, error) {
response := &ram.GetAccountAliasResponse{}
request := ram.CreateGetAccountAliasRequest()
request.RegionId = s.client.RegionId
raw, err := s.client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.GetAccountAlias(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response = raw.(*ram.GetAccountAliasResponse)
return response, nil
}
func (s *RamService) DescribeRamAccessKey(id, userName string) (*ram.AccessKeyInListAccessKeys, error) {
key := &ram.AccessKeyInListAccessKeys{}
request := ram.CreateListAccessKeysRequest()
request.RegionId = s.client.RegionId
request.UserName = userName
raw, err := s.client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.ListAccessKeys(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist"}) {
return key, WrapErrorf(Error(GetNotFoundMessage("RamAccessKey", id)), NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return key, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*ram.ListAccessKeysResponse)
for _, accessKey := range response.AccessKeys.AccessKey {
if accessKey.AccessKeyId == id {
return &accessKey, nil
}
}
return key, WrapErrorf(Error(GetNotFoundMessage("RamAccessKey", id)), NotFoundMsg, AlibabaCloudSdkGoERROR)
}
func (s *RamService) WaitForRamAccessKey(id, useName string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeRamAccessKey(id, useName)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if string(status) == object.Status {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.Status, status, ProviderERROR)
}
}
}
func (s *RamService) DescribeRamPolicy(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewRamClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetPolicy"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"PolicyName": id,
"PolicyType": "Custom",
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-05-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist.Policy"}) {
err = WrapErrorf(Error(GetNotFoundMessage("RamPolicy", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *RamService) DescribeRamRoleAttachment(id string) (*ecs.DescribeInstanceRamRoleResponse, error) {
response := &ecs.DescribeInstanceRamRoleResponse{}
parts, err := ParseResourceId(id, 2)
if err != nil {
return response, WrapError(err)
}
request := ecs.CreateDescribeInstanceRamRoleRequest()
request.RegionId = s.client.RegionId
request.InstanceIds = parts[1]
var raw interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeInstanceRamRole(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"unexpected end of JSON input"}) {
return resource.RetryableError(WrapError(err))
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidRamRole.NotFound"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response = raw.(*ecs.DescribeInstanceRamRoleResponse)
instRoleSets := response.InstanceRamRoleSets.InstanceRamRoleSet
if len(instRoleSets) > 0 {
var instIds []string
for _, item := range instRoleSets {
if item.RamRoleName == parts[0] {
instIds = append(instIds, item.InstanceId)
}
}
ids := strings.Split(strings.TrimRight(strings.TrimLeft(strings.Replace(strings.Split(id, ":")[1], "\"", "", -1), "["), "]"), ",")
sort.Strings(instIds)
sort.Strings(ids)
if reflect.DeepEqual(instIds, ids) {
return response, nil
}
}
return response, WrapErrorf(err, NotFoundMsg, ProviderERROR)
}
func (s *RamService) WaitForRamRoleAttachment(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeRamRoleAttachment(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, strconv.Itoa(object.TotalCount), status, ProviderERROR)
}
}
}
func (s *RamService) DescribeRamRole(id string) (*ram.GetRoleResponse, error) {
response := &ram.GetRoleResponse{}
request := ram.CreateGetRoleRequest()
request.RegionId = s.client.RegionId
request.RoleName = id
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.GetRole(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser}) {
time.Sleep(2 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*ram.GetRoleResponse)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist.Role"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return response, nil
}
func (s *RamService) WaitForRamRole(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeRamRole(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.Role.RoleName == id && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.Role.RoleName, id, ProviderERROR)
}
}
}
func (s *RamService) DescribeRamUserPolicyAttachment(id string) (*ram.PolicyInListPoliciesForUser, error) {
response := &ram.PolicyInListPoliciesForUser{}
request := ram.CreateListPoliciesForUserRequest()
request.RegionId = s.client.RegionId
parts, err := ParseResourceId(id, 4)
if err != nil {
return response, WrapError(err)
}
request.UserName = parts[3]
var listPoliciesForUserResponse *ram.ListPoliciesForUserResponse
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.ListPoliciesForUser(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser}) {
time.Sleep(2 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
listPoliciesForUserResponse, _ = raw.(*ram.ListPoliciesForUserResponse)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
if len(listPoliciesForUserResponse.Policies.Policy) > 0 {
for _, v := range listPoliciesForUserResponse.Policies.Policy {
if v.PolicyType == parts[2] && (v.PolicyName == parts[1] || strings.ToLower(v.PolicyName) == strings.ToLower(parts[1])) {
return &v, nil
}
}
}
return response, WrapErrorf(err, NotFoundMsg, ProviderERROR)
}
func (s *RamService) WaitForRamUserPolicyAttachment(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
parts, err := ParseResourceId(id, 4)
if err != nil {
return WrapError(err)
}
for {
object, err := s.DescribeRamUserPolicyAttachment(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.PolicyName, parts[1], ProviderERROR)
}
}
}
func (s *RamService) DescribeRamRolePolicyAttachment(id string) (*ram.PolicyInListPoliciesForRole, error) {
response := &ram.PolicyInListPoliciesForRole{}
request := ram.CreateListPoliciesForRoleRequest()
request.RegionId = s.client.RegionId
parts, err := ParseResourceId(id, 4)
if err != nil {
return response, WrapError(err)
}
request.RoleName = parts[3]
var listPoliciesForRoleResponse *ram.ListPoliciesForRoleResponse
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.ListPoliciesForRole(request)
})
if err != nil {
if IsExpectedErrors(err, []string{ThrottlingUser}) {
time.Sleep(2 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
listPoliciesForRoleResponse, _ = raw.(*ram.ListPoliciesForRoleResponse)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist.Role"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
if len(listPoliciesForRoleResponse.Policies.Policy) > 0 {
for _, v := range listPoliciesForRoleResponse.Policies.Policy {
if v.PolicyType == parts[2] && (v.PolicyName == parts[1] || strings.ToLower(v.PolicyName) == strings.ToLower(parts[1])) {
return &v, nil
}
}
}
return response, WrapErrorf(err, NotFoundMsg, ProviderERROR)
}
func (s *RamService) WaitForRamRolePolicyAttachment(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
parts, err := ParseResourceId(id, 4)
if err != nil {
return WrapError(err)
}
for {
object, err := s.DescribeRamRolePolicyAttachment(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
}
return nil
} else {
return WrapError(err)
}
}
if status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.PolicyName, parts[1], ProviderERROR)
}
}
}
func (s *RamService) DescribeRamGroup(id string) (*ram.GetGroupResponse, error) {
response := &ram.GetGroupResponse{}
request := ram.CreateGetGroupRequest()
request.RegionId = s.client.RegionId
request.GroupName = id
raw, err := s.client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.GetGroup(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist.Group"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*ram.GetGroupResponse)
if response.Group.GroupName != id {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, nil
}
func (s *RamService) WaitForRamGroup(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeRamGroup(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.Group.GroupName == id && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.Group.GroupName, id, ProviderERROR)
}
}
}
func (s *RamService) DescribeRamAccountPasswordPolicy(id string) (*ram.GetPasswordPolicyResponse, error) {
response := &ram.GetPasswordPolicyResponse{}
request := ram.CreateGetPasswordPolicyRequest()
request.RegionId = s.client.RegionId
raw, err := s.client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.GetPasswordPolicy(request)
})
if err != nil {
return response, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*ram.GetPasswordPolicyResponse)
return response, nil
}
func (s *RamService) DescribeRamSecurityPreference(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewImsClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetSecurityPreference"
request := map[string]interface{}{}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.SecurityPreference", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.SecurityPreference", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"encoding/json"
"fmt"
"log"
"regexp"
"strconv"
"strings"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/denverdino/aliyungo/common"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type RdsService struct {
client *connectivity.AliyunClient
}
//
// _______________ _______________ _______________
// | | ______param______\ | | _____request_____\ | |
// | Business | | Service | | SDK/API |
// | | __________________ | | __________________ | |
// |______________| \ (obj, err) |______________| \ (status, cont) |______________|
// | |
// |A. {instance, nil} |a. {200, content}
// |B. {nil, error} |b. {200, nil}
// |c. {4xx, nil}
//
// The API return 200 for resource not found.
// When getInstance is empty, then throw InstanceNotfound error.
// That the business layer only need to check error.
var DBInstanceStatusCatcher = Catcher{"OperationDenied.DBInstanceStatus", 60, 5}
func (s *RdsService) DescribeDBInstance(id string) (map[string]interface{}, error) {
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDBInstanceAttribute"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": id,
"SourceIp": s.client.SourceIp,
}
var response map[string]interface{}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return nil, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Items.DBInstanceAttribute", response)
if err != nil {
return nil, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Items.DBInstanceAttribute", response)
}
if len(v.([]interface{})) < 1 {
return nil, WrapErrorf(Error(GetNotFoundMessage("DBAccount", id)), NotFoundMsg, ProviderERROR)
}
return v.([]interface{})[0].(map[string]interface{}), nil
}
func (s *RdsService) DescribeTasks(id string) (map[string]interface{}, error) {
action := "DescribeTasks"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": id,
"SourceIp": s.client.SourceIp,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, ProviderERROR)
}
return nil, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
return response, nil
}
func (s *RdsService) DescribeDBReadonlyInstance(id string) (map[string]interface{}, error) {
action := "DescribeDBInstanceAttribute"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": id,
"SourceIp": s.client.SourceIp,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return nil, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
dBInstanceAttributes := response["Items"].(map[string]interface{})["DBInstanceAttribute"].([]interface{})
if len(dBInstanceAttributes) < 1 {
return nil, WrapErrorf(Error(GetNotFoundMessage("DBInstance", id)), NotFoundMsg, ProviderERROR)
}
return dBInstanceAttributes[0].(map[string]interface{}), nil
}
func (s *RdsService) DescribeDBAccountPrivilege(id string) (map[string]interface{}, error) {
var ds map[string]interface{}
parts, err := ParseResourceId(id, 3)
if err != nil {
return ds, WrapError(err)
}
action := "DescribeAccounts"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": parts[0],
"AccountName": parts[1],
"SourceIp": s.client.SourceIp,
}
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
invoker := NewInvoker()
invoker.AddCatcher(DBInstanceStatusCatcher)
var response map[string]interface{}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
if err := invoker.Run(func() error {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
return nil
}); err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound"}) {
return ds, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return ds, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
dBInstanceAccounts := response["Accounts"].(map[string]interface{})["DBInstanceAccount"].([]interface{})
if len(dBInstanceAccounts) < 1 {
return ds, WrapErrorf(Error(GetNotFoundMessage("DBAccountPrivilege", id)), NotFoundMsg, ProviderERROR)
}
return dBInstanceAccounts[0].(map[string]interface{}), nil
}
func (s *RdsService) DescribeDBDatabase(id string) (map[string]interface{}, error) {
var ds map[string]interface{}
parts, err := ParseResourceId(id, 2)
if err != nil {
return ds, WrapError(err)
}
dbName := parts[1]
var response map[string]interface{}
action := "DescribeDatabases"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": parts[0],
"DBName": dbName,
"SourceIp": s.client.SourceIp,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InternalError", "OperationDenied.DBInstanceStatus"}) {
return resource.RetryableError(WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR))
}
if NotFoundError(err) || IsExpectedErrors(err, []string{"InvalidDBName.NotFound", "InvalidDBInstanceId.NotFoundError"}) {
return resource.NonRetryableError(WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR))
}
return resource.NonRetryableError(WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR))
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Databases.Database", response)
if err != nil {
return resource.NonRetryableError(WrapErrorf(err, FailedGetAttributeMsg, id, "$.Databases.Database", response))
}
if len(v.([]interface{})) < 1 {
return resource.NonRetryableError(WrapErrorf(Error(GetNotFoundMessage("DBDatabase", dbName)), NotFoundMsg, ProviderERROR))
}
ds = v.([]interface{})[0].(map[string]interface{})
return nil
})
return ds, err
}
func (s *RdsService) DescribeParameters(id string) (map[string]interface{}, error) {
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeParameters"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": id,
"SourceIp": s.client.SourceIp,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return nil, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
return response, err
}
func (s *RdsService) SetTimeZone(d *schema.ResourceData) error {
targetParameterName := ""
engine := d.Get("engine")
if engine == string(MySQL) {
targetParameterName = "default_time_zone"
} else if engine == string(PostgreSQL) {
targetParameterName = "timezone"
}
if targetParameterName != "" {
paramsRes, err := s.DescribeParameters(d.Id())
if err != nil {
return WrapError(err)
}
parameters := paramsRes["RunningParameters"].(map[string]interface{})["DBInstanceParameter"].([]interface{})
for _, item := range parameters {
item := item.(map[string]interface{})
parameterName := item["ParameterName"]
if parameterName == targetParameterName {
d.Set("db_time_zone", item["ParameterValue"])
break
}
}
}
return nil
}
func (s *RdsService) RefreshParameters(d *schema.ResourceData, attribute string) error {
var param []map[string]interface{}
documented, ok := d.GetOk(attribute)
if !ok {
return nil
}
object, err := s.DescribeParameters(d.Id())
if err != nil {
return WrapError(err)
}
var parameters = make(map[string]interface{})
dBInstanceParameters := object["RunningParameters"].(map[string]interface{})["DBInstanceParameter"].([]interface{})
for _, i := range dBInstanceParameters {
i := i.(map[string]interface{})
if i["ParameterName"] != "" {
parameter := map[string]interface{}{
"name": i["ParameterName"],
"value": i["ParameterValue"],
}
parameters[i["ParameterName"].(string)] = parameter
}
}
dBInstanceParameters = object["ConfigParameters"].(map[string]interface{})["DBInstanceParameter"].([]interface{})
for _, i := range dBInstanceParameters {
i := i.(map[string]interface{})
if i["ParameterName"] != "" {
parameter := map[string]interface{}{
"name": i["ParameterName"],
"value": i["ParameterValue"],
}
parameters[i["ParameterName"].(string)] = parameter
}
}
for _, parameter := range documented.(*schema.Set).List() {
name := parameter.(map[string]interface{})["name"]
for _, value := range parameters {
if value.(map[string]interface{})["name"] == name {
param = append(param, value.(map[string]interface{}))
break
}
}
}
if len(param) > 0 {
if err := d.Set(attribute, param); err != nil {
return WrapError(err)
}
}
return nil
}
func (s *RdsService) RefreshPgHbaConf(d *schema.ResourceData, attribute string) error {
response, err := s.DescribePGHbaConfig(d.Id())
runningHbaItems := response["RunningHbaItems"].(map[string]interface{})["HbaItem"].([]interface{})
if err != nil {
return WrapError(err)
}
var items []map[string]interface{}
documented, ok := d.GetOk(attribute)
if !ok {
return nil
}
for _, item := range documented.(*schema.Set).List() {
item := item.(map[string]interface{})
for _, item2 := range runningHbaItems {
item2 := item2.(map[string]interface{})
if item["priority_id"] == formatInt(item2["PriorityId"]) {
mapping := map[string]interface{}{
"type": item2["Type"],
"database": item2["Database"],
"priority_id": formatInt(item2["PriorityId"]),
"address": item2["Address"],
"user": item2["User"],
"method": item2["Method"],
}
if item2["mask"] != nil && item2["mask"] != "" {
mapping["mask"] = item2["mask"]
}
if item2["option"] != nil && item2["option"] != "" {
mapping["option"] = item2["option"]
}
items = append(items, mapping)
}
}
}
if len(items) > 0 {
if err := d.Set(attribute, items); err != nil {
return WrapError(err)
}
}
return nil
}
func (s *RdsService) ModifyPgHbaConfig(d *schema.ResourceData, attribute string) error {
conn, err := s.client.NewRdsClient()
if err != nil {
return WrapError(err)
}
action := "ModifyPGHbaConfig"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": d.Id(),
"SourceIp": s.client.SourceIp,
}
request["OpsType"] = "update"
pgHbaConfig := d.Get("pg_hba_conf")
count := 1
for _, i := range pgHbaConfig.(*schema.Set).List() {
i := i.(map[string]interface{})
request[fmt.Sprint("HbaItem.", count, ".Type")] = i["type"]
if i["mask"] != nil && i["mask"] != "" {
request[fmt.Sprint("HbaItem.", count, ".Mask")] = i["mask"]
}
request[fmt.Sprint("HbaItem.", count, ".Database")] = i["database"]
request[fmt.Sprint("HbaItem.", count, ".PriorityId")] = i["priority_id"]
request[fmt.Sprint("HbaItem.", count, ".Address")] = i["address"]
request[fmt.Sprint("HbaItem.", count, ".User")] = i["user"]
request[fmt.Sprint("HbaItem.", count, ".Method")] = i["method"]
if i["option"] != nil && i["mask"] != "" {
request[fmt.Sprint("HbaItem.", count, ".Option")] = i["option"]
}
count = count + 1
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
var response map[string]interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InternalError"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapError(err)
}
if err := s.WaitForDBInstance(d.Id(), Running, DefaultLongTimeout); err != nil {
return WrapError(err)
}
desResponse, err := s.DescribePGHbaConfig(d.Id())
if err != nil {
return WrapError(err)
}
if desResponse["LastModifyStatus"] == "failed" {
return WrapError(Error(desResponse["ModifyStatusReason"].(string)))
}
d.SetPartial(attribute)
return nil
}
func (s *RdsService) ModifyParameters(d *schema.ResourceData, attribute string) error {
conn, err := s.client.NewRdsClient()
if err != nil {
return WrapError(err)
}
action := "ModifyParameter"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": d.Id(),
"Forcerestart": d.Get("force_restart"),
"SourceIp": s.client.SourceIp,
}
config := make(map[string]string)
allConfig := make(map[string]string)
o, n := d.GetChange(attribute)
os, ns := o.(*schema.Set), n.(*schema.Set)
add := ns.Difference(os).List()
if len(add) > 0 {
for _, i := range add {
key := i.(map[string]interface{})["name"].(string)
value := i.(map[string]interface{})["value"].(string)
config[key] = value
}
cfg, _ := json.Marshal(config)
request["Parameters"] = string(cfg)
// wait instance status is Normal before modifying
if err := s.WaitForDBInstance(d.Id(), Running, DefaultLongTimeout); err != nil {
return WrapError(err)
}
// Need to check whether some parameter needs restart
if !d.Get("force_restart").(bool) {
action := "DescribeParameterTemplates"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": d.Id(),
"Engine": d.Get("engine"),
"EngineVersion": d.Get("engine_version"),
"ClientToken": buildClientToken(action),
"SourceIp": s.client.SourceIp,
}
forceRestartMap := make(map[string]string)
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
stateConf := BuildStateConf([]string{}, []string{"Running"}, d.Timeout(schema.TimeoutUpdate), 3*time.Minute, s.RdsDBInstanceStateRefreshFunc(d.Id(), []string{"Deleting"}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
templateRecords := response["Parameters"].(map[string]interface{})["TemplateRecord"].([]interface{})
for _, para := range templateRecords {
para := para.(map[string]interface{})
if para["ForceRestart"] == "true" {
forceRestartMap[para["ParameterName"].(string)] = para["ForceRestart"].(string)
}
}
if len(forceRestartMap) > 0 {
for key, _ := range config {
if _, ok := forceRestartMap[key]; ok {
return WrapError(fmt.Errorf("Modifying RDS instance's parameter '%s' requires setting 'force_restart = true'.", key))
}
}
}
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
// wait instance parameter expect after modifying
for _, i := range ns.List() {
key := i.(map[string]interface{})["name"].(string)
value := i.(map[string]interface{})["value"].(string)
allConfig[key] = value
}
if err := s.WaitForDBParameter(d.Id(), DefaultTimeoutMedium, allConfig); err != nil {
return WrapError(err)
}
// wait instance status is Normal after modifying
if err := s.WaitForDBInstance(d.Id(), Running, DefaultLongTimeout); err != nil {
return WrapError(err)
}
}
d.SetPartial(attribute)
return nil
}
func (s *RdsService) DescribeDBInstanceNetInfo(id string) ([]interface{}, error) {
action := "DescribeDBInstanceNetInfo"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": id,
"SourceIp": s.client.SourceIp,
}
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
var response map[string]interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InternalError"}) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return nil, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
}
dBInstanceNetInfos := response["DBInstanceNetInfos"].(map[string]interface{})["DBInstanceNetInfo"].([]interface{})
if len(dBInstanceNetInfos) < 1 {
return nil, WrapErrorf(Error(GetNotFoundMessage("DBInstanceNetInfo", id)), NotFoundMsg, ProviderERROR)
}
return dBInstanceNetInfos, nil
}
func (s *RdsService) DescribeDBConnection(id string) (map[string]interface{}, error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
return nil, WrapError(err)
}
object, err := s.DescribeDBInstanceNetInfo(parts[0])
if err != nil {
if IsExpectedErrors(err, []string{"InvalidCurrentConnectionString.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return nil, WrapError(err)
}
if object != nil {
for _, o := range object {
o := o.(map[string]interface{})
if strings.HasPrefix(o["ConnectionString"].(string), parts[1]) {
return o, nil
}
}
}
return nil, WrapErrorf(Error(GetNotFoundMessage("DBConnection", id)), NotFoundMsg, ProviderERROR)
}
func (s *RdsService) DescribeDBReadWriteSplittingConnection(id string) (map[string]interface{}, error) {
object, err := s.DescribeDBInstanceNetInfo(id)
if err != nil && !NotFoundError(err) {
return nil, err
}
if object != nil {
for _, conn := range object {
conn := conn.(map[string]interface{})
if conn["ConnectionStringType"] != "ReadWriteSplitting" {
continue
}
if conn["MaxDelayTime"] == nil {
continue
}
if _, err := strconv.Atoi(conn["MaxDelayTime"].(string)); err != nil {
return nil, err
}
return conn, nil
}
}
return nil, WrapErrorf(Error(GetNotFoundMessage("ReadWriteSplittingConnection", id)), NotFoundMsg, ProviderERROR)
}
func (s *RdsService) GrantAccountPrivilege(id, dbName string) error {
parts, err := ParseResourceId(id, 3)
if err != nil {
return WrapError(err)
}
action := "GrantAccountPrivilege"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": parts[0],
"AccountName": parts[1],
"DBName": dbName,
"AccountPrivilege": parts[2],
"SourceIp": s.client.SourceIp,
}
runtime := util.RuntimeOptions{}
var response map[string]interface{}
conn, err := s.client.NewRdsClient()
if err != nil {
return WrapError(err)
}
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, OperationDeniedDBStatus) || IsExpectedErrors(err, []string{"InvalidDB.NotFound"}) || NeedRetry(err) {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if err := s.WaitForAccountPrivilege(id, dbName, Available, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
return nil
}
func (s *RdsService) RevokeAccountPrivilege(id, dbName string) error {
parts, err := ParseResourceId(id, 3)
if err != nil {
return WrapError(err)
}
action := "RevokeAccountPrivilege"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": parts[0],
"AccountName": parts[1],
"DBName": dbName,
"SourceIp": s.client.SourceIp,
}
runtime := util.RuntimeOptions{}
conn, err := s.client.NewRdsClient()
if err != nil {
return WrapError(err)
}
err = resource.Retry(3*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, OperationDeniedDBStatus) || NeedRetry(err) {
return resource.RetryableError(err)
} else if IsExpectedErrors(err, []string{"InvalidDB.NotFound"}) {
log.Printf("[WARN] Resource alicloud_db_account_privilege RevokeAccountPrivilege Failed!!! %s", err)
return nil
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if err := s.WaitForAccountPrivilegeRevoked(id, dbName, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
return nil
}
func (s *RdsService) ReleaseDBPublicConnection(instanceId, connection string) error {
action := "ReleaseInstancePublicConnection"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": instanceId,
"CurrentConnectionString": connection,
"SourceIp": s.client.SourceIp,
}
conn, err := s.client.NewRdsClient()
if err != nil {
return WrapError(err)
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, instanceId, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
return nil
}
func (s *RdsService) ModifyDBBackupPolicy(d *schema.ResourceData, updateForData, updateForLog bool) error {
enableBackupLog := "1"
backupPeriod := ""
if v, ok := d.GetOk("preferred_backup_period"); ok && v.(*schema.Set).Len() > 0 {
periodList := expandStringList(v.(*schema.Set).List())
backupPeriod = fmt.Sprintf("%s", strings.Join(periodList[:], COMMA_SEPARATED))
} else {
periodList := expandStringList(d.Get("backup_period").(*schema.Set).List())
backupPeriod = fmt.Sprintf("%s", strings.Join(periodList[:], COMMA_SEPARATED))
}
backupTime := "02:00Z-03:00Z"
if v, ok := d.GetOk("preferred_backup_time"); ok && v.(string) != "02:00Z-03:00Z" {
backupTime = v.(string)
} else if v, ok := d.GetOk("backup_time"); ok && v.(string) != "" {
backupTime = v.(string)
}
retentionPeriod := "7"
if v, ok := d.GetOk("backup_retention_period"); ok && v.(int) != 7 {
retentionPeriod = strconv.Itoa(v.(int))
} else if v, ok := d.GetOk("retention_period"); ok && v.(int) != 0 {
retentionPeriod = strconv.Itoa(v.(int))
}
logBackupRetentionPeriod := ""
if v, ok := d.GetOk("log_backup_retention_period"); ok && v.(int) != 0 {
logBackupRetentionPeriod = strconv.Itoa(v.(int))
} else if v, ok := d.GetOk("log_retention_period"); ok && v.(int) != 0 {
logBackupRetentionPeriod = strconv.Itoa(v.(int))
}
localLogRetentionHours := ""
if v, ok := d.GetOk("local_log_retention_hours"); ok {
localLogRetentionHours = strconv.Itoa(v.(int))
}
localLogRetentionSpace := ""
if v, ok := d.GetOk("local_log_retention_space"); ok {
localLogRetentionSpace = strconv.Itoa(v.(int))
}
highSpaceUsageProtection := d.Get("high_space_usage_protection").(string)
if !d.Get("enable_backup_log").(bool) {
enableBackupLog = "0"
}
if d.HasChange("log_backup_retention_period") {
if d.Get("log_backup_retention_period").(int) > d.Get("backup_retention_period").(int) {
logBackupRetentionPeriod = retentionPeriod
}
}
logBackupFrequency := ""
if v, ok := d.GetOk("log_backup_frequency"); ok {
logBackupFrequency = v.(string)
}
compressType := ""
if v, ok := d.GetOk("compress_type"); ok {
compressType = v.(string)
}
archiveBackupRetentionPeriod := "0"
if v, ok := d.GetOk("archive_backup_retention_period"); ok {
archiveBackupRetentionPeriod = strconv.Itoa(v.(int))
}
archiveBackupKeepCount := "1"
if v, ok := d.GetOk("archive_backup_keep_count"); ok {
archiveBackupKeepCount = strconv.Itoa(v.(int))
}
archiveBackupKeepPolicy := "0"
if v, ok := d.GetOk("archive_backup_keep_policy"); ok {
archiveBackupKeepPolicy = v.(string)
}
releasedKeepPolicy := ""
if v, ok := d.GetOk("released_keep_policy"); ok {
releasedKeepPolicy = v.(string)
}
instance, err := s.DescribeDBInstance(d.Id())
if err != nil {
return WrapError(err)
}
if updateForData {
conn, err := s.client.NewRdsClient()
if err != nil {
return WrapError(err)
}
action := "ModifyBackupPolicy"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": d.Id(),
"PreferredBackupPeriod": backupPeriod,
"PreferredBackupTime": backupTime,
"BackupRetentionPeriod": retentionPeriod,
"CompressType": compressType,
"BackupPolicyMode": "DataBackupPolicy",
"SourceIp": s.client.SourceIp,
"ReleasedKeepPolicy": releasedKeepPolicy,
}
if instance["Engine"] == "SQLServer" && logBackupFrequency == "LogInterval" {
request["LogBackupFrequency"] = logBackupFrequency
}
if instance["Engine"] == "MySQL" && instance["DBInstanceStorageType"] == "local_ssd" {
request["ArchiveBackupRetentionPeriod"] = archiveBackupRetentionPeriod
request["ArchiveBackupKeepCount"] = archiveBackupKeepCount
request["ArchiveBackupKeepPolicy"] = archiveBackupKeepPolicy
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
if err := s.WaitForDBInstance(d.Id(), Running, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
}
// At present, the sql server database does not support setting logBackupRetentionPeriod
if updateForLog && instance["Engine"] != "SQLServer" {
conn, err := s.client.NewRdsClient()
if err != nil {
return WrapError(err)
}
action := "ModifyBackupPolicy"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": d.Id(),
"EnableBackupLog": enableBackupLog,
"LocalLogRetentionHours": localLogRetentionHours,
"LocalLogRetentionSpace": localLogRetentionSpace,
"HighSpaceUsageProtection": highSpaceUsageProtection,
"BackupPolicyMode": "LogBackupPolicy",
"LogBackupRetentionPeriod": logBackupRetentionPeriod,
"SourceIp": s.client.SourceIp,
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
if err := s.WaitForDBInstance(d.Id(), Running, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
}
return nil
}
func (s *RdsService) ModifyDBSecurityIps(instanceId, ips string) error {
conn, err := s.client.NewRdsClient()
if err != nil {
return WrapError(err)
}
action := "ModifySecurityIps"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": instanceId,
"SecurityIps": ips,
"SourceIp": s.client.SourceIp,
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, instanceId, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
if err := s.WaitForDBInstance(instanceId, Running, DefaultTimeoutMedium); err != nil {
return WrapError(err)
}
return nil
}
func (s *RdsService) DescribeDBSecurityIps(instanceId string) ([]interface{}, error) {
action := "DescribeDBInstanceIPArrayList"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": instanceId,
"SourceIp": s.client.SourceIp,
}
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return nil, WrapErrorf(err, DefaultErrorMsg, instanceId, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
return response["Items"].(map[string]interface{})["DBInstanceIPArray"].([]interface{}), nil
}
func (s *RdsService) DescribeParameterTemplates(instanceId, engine, engineVersion string) ([]interface{}, error) {
action := "DescribeParameterTemplates"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": instanceId,
"Engine": engine,
"EngineVersion": engineVersion,
"SourceIp": s.client.SourceIp,
}
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return nil, WrapErrorf(err, DefaultErrorMsg, instanceId, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
return response["Parameters"].(map[string]interface{})["TemplateRecord"].([]interface{}), nil
}
func (s *RdsService) GetSecurityIps(instanceId string, dbInstanceIpArrayName string) ([]string, error) {
object, err := s.DescribeDBSecurityIps(instanceId)
if err != nil {
return nil, WrapError(err)
}
var ips, separator string
ipsMap := make(map[string]string)
for _, ip := range object {
ip := ip.(map[string]interface{})
if ip["DBInstanceIPArrayName"].(string) == dbInstanceIpArrayName {
ips += separator + ip["SecurityIPList"].(string)
separator = COMMA_SEPARATED
}
}
for _, ip := range strings.Split(ips, COMMA_SEPARATED) {
ipsMap[ip] = ip
}
var finalIps []string
if len(ipsMap) > 0 {
for key := range ipsMap {
finalIps = append(finalIps, key)
}
}
return finalIps, nil
}
func (s *RdsService) DescribeSecurityGroupConfiguration(id string) ([]string, error) {
action := "DescribeSecurityGroupConfiguration"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": id,
"SourceIp": s.client.SourceIp,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return nil, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
groupIds := make([]string, 0)
ecsSecurityGroupRelations := response["Items"].(map[string]interface{})["EcsSecurityGroupRelation"].([]interface{})
for _, v := range ecsSecurityGroupRelations {
v := v.(map[string]interface{})
groupIds = append(groupIds, v["SecurityGroupId"].(string))
}
return groupIds, nil
}
func (s *RdsService) DescribeDBInstanceSSL(id string) (map[string]interface{}, error) {
action := "DescribeDBInstanceSSL"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": id,
"SourceIp": s.client.SourceIp,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return nil, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
return response, nil
}
func (s *RdsService) DescribeDBInstanceEncryptionKey(id string) (map[string]interface{}, error) {
action := "DescribeDBInstanceEncryptionKey"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": id,
"SourceIp": s.client.SourceIp,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return nil, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
return response, nil
}
func (s *RdsService) DescribeHASwitchConfig(id string) (map[string]interface{}, error) {
action := "DescribeHASwitchConfig"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": id,
"SourceIp": s.client.SourceIp,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return nil, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
return response, nil
}
func (s *RdsService) DescribeRdsTDEInfo(id string) (map[string]interface{}, error) {
action := "DescribeDBInstanceTDE"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": id,
"SourceIp": s.client.SourceIp,
}
statErr := s.WaitForDBInstance(id, Running, DefaultLongTimeout)
if statErr != nil {
return nil, WrapError(statErr)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return nil, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
return response, nil
}
func (s *RdsService) ModifySecurityGroupConfiguration(id string, groupid string) error {
conn, err := s.client.NewRdsClient()
if err != nil {
return WrapError(err)
}
action := "ModifySecurityGroupConfiguration"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": id,
"SourceIp": s.client.SourceIp,
}
//openapi required that input "Empty" if groupid is ""
if len(groupid) == 0 {
groupid = "Empty"
}
request["SecurityGroupId"] = groupid
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
return nil
}
// return multiIZ list of current region
func (s *RdsService) DescribeMultiIZByRegion() (izs []string, err error) {
action := "DescribeRegions"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"SourceIp": s.client.SourceIp,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return nil, WrapErrorf(err, DefaultErrorMsg, "MultiIZByRegion", action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
regions := response["Regions"].(map[string]interface{})["RDSRegion"].([]interface{})
zoneIds := []string{}
for _, r := range regions {
r := r.(map[string]interface{})
if r["RegionId"] == string(s.client.Region) && strings.Contains(r["ZoneId"].(string), MULTI_IZ_SYMBOL) {
zoneIds = append(zoneIds, r["ZoneId"].(string))
}
}
return zoneIds, nil
}
func (s *RdsService) DescribeBackupPolicy(id string) (map[string]interface{}, error) {
action := "DescribeBackupPolicy"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": id,
"SourceIp": s.client.SourceIp,
}
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return nil, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
return response, nil
}
func (s *RdsService) DescribeDbInstanceMonitor(id string) (monitoringPeriod int, err error) {
action := "DescribeDBInstanceMonitor"
request := map[string]interface{}{
"DBInstanceId": id,
"RegionId": s.client.RegionId,
"SourceIp": s.client.SourceIp,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
conn, err := s.client.NewRdsClient()
if err != nil {
return 0, WrapError(err)
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return 0, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
monPeriod, err := strconv.Atoi(response["Period"].(string))
if err != nil {
return 0, WrapError(err)
}
return monPeriod, nil
}
func (s *RdsService) DescribeSQLCollectorPolicy(id string) (map[string]interface{}, error) {
action := "DescribeSQLCollectorPolicy"
request := map[string]interface{}{
"DBInstanceId": id,
"RegionId": s.client.RegionId,
"SourceIp": s.client.SourceIp,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return nil, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
return response, nil
}
func (s *RdsService) DescribeSQLCollectorRetention(id string) (map[string]interface{}, error) {
action := "DescribeSQLCollectorRetention"
request := map[string]interface{}{
"DBInstanceId": id,
"RegionId": s.client.RegionId,
"SourceIp": s.client.SourceIp,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return nil, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
return response, nil
}
// WaitForInstance waits for instance to given status
func (s *RdsService) WaitForDBInstance(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeDBInstance(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object != nil && strings.ToLower(fmt.Sprint(object["DBInstanceStatus"])) == strings.ToLower(string(status)) {
break
}
time.Sleep(DefaultIntervalShort * time.Second)
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object["DBInstanceStatus"], status, ProviderERROR)
}
}
return nil
}
func (s *RdsService) RdsDBInstanceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeDBInstance(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["DBInstanceStatus"] == failState {
return object, object["DBInstanceStatus"].(string), WrapError(Error(FailedToReachTargetStatus, object["DBInstanceStatus"]))
}
}
return object, object["DBInstanceStatus"].(string), nil
}
}
func (s *RdsService) RdsTaskStateRefreshFunc(id string, taskAction string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeTasks(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
taskProgressInfos := object["Items"].(map[string]interface{})["TaskProgressInfo"].([]interface{})
for _, t := range taskProgressInfos {
t := t.(map[string]interface{})
if t["TaskAction"] == taskAction {
return object, t["Status"].(string), nil
}
}
return object, "Pending", nil
}
}
// WaitForDBParameter waits for instance parameter to given value.
// Status of DB instance is Running after ModifyParameters API was
// call, so we can not just wait for instance status become
// Running, we should wait until parameters have expected values.
func (s *RdsService) WaitForDBParameter(instanceId string, timeout int, expects map[string]string) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeParameters(instanceId)
if err != nil {
return WrapError(err)
}
var actuals = make(map[string]string)
dBInstanceParameters := object["RunningParameters"].(map[string]interface{})["DBInstanceParameter"].([]interface{})
for _, i := range dBInstanceParameters {
i := i.(map[string]interface{})
if i["ParameterName"] == nil || i["ParameterValue"] == nil {
continue
}
actuals[i["ParameterName"].(string)] = i["ParameterValue"].(string)
}
dBInstanceParameters = object["ConfigParameters"].(map[string]interface{})["DBInstanceParameter"].([]interface{})
for _, i := range dBInstanceParameters {
i := i.(map[string]interface{})
if i["ParameterName"] == nil || i["ParameterValue"] == nil {
continue
}
actuals[i["ParameterName"].(string)] = i["ParameterValue"].(string)
}
match := true
got_value := ""
expected_value := ""
for name, expect := range expects {
if actual, ok := actuals[name]; ok {
if expect != actual {
match = false
got_value = actual
expected_value = expect
break
}
} else {
match = false
}
}
if match {
break
}
time.Sleep(DefaultIntervalShort * time.Second)
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, instanceId, GetFunc(1), timeout, got_value, expected_value, ProviderERROR)
}
}
return nil
}
func (s *RdsService) WaitForDBConnection(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeDBConnection(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object != nil && object["ConnectionString"] != "" {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object["ConnectionString"], id, ProviderERROR)
}
}
}
func (s *RdsService) WaitForDBReadWriteSplitting(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeDBReadWriteSplittingConnection(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if err == nil {
break
}
time.Sleep(DefaultIntervalShort * time.Second)
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object["ConnectionString"], id, ProviderERROR)
}
}
return nil
}
func (s *RdsService) WaitForAccountPrivilege(id, dbName string, status Status, timeout int) error {
parts, err := ParseResourceId(id, 3)
if err != nil {
return WrapError(err)
}
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeDBDatabase(parts[0] + ":" + dbName)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
ready := false
if object != nil {
accountPrivilegeInfos := object["Accounts"].(map[string]interface{})["AccountPrivilegeInfo"].([]interface{})
for _, account := range accountPrivilegeInfos {
// At present, postgresql response has a bug, DBOwner will be changed to ALL
account := account.(map[string]interface{})
if account["Account"] == parts[1] && (account["AccountPrivilege"] == parts[2] || (parts[2] == "DBOwner" && account["AccountPrivilege"] == "ALL")) {
ready = true
break
}
}
}
if status == Deleted && !ready {
break
}
if ready {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, "", id, ProviderERROR)
}
}
return nil
}
func (s *RdsService) WaitForAccountPrivilegeRevoked(id, dbName string, timeout int) error {
parts, err := ParseResourceId(id, 3)
if err != nil {
return WrapError(err)
}
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeDBDatabase(parts[0] + ":" + dbName)
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
exist := false
if object != nil {
accountPrivilegeInfo := object["Accounts"].(map[string]interface{})["AccountPrivilegeInfo"].([]interface{})
for _, account := range accountPrivilegeInfo {
account := account.(map[string]interface{})
if account["Account"] == parts[1] && (account["AccountPrivilege"] == parts[2] || (parts[2] == "DBOwner" && account["AccountPrivilege"] == "ALL")) {
exist = true
break
}
}
}
if !exist {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, "", dbName, ProviderERROR)
}
}
return nil
}
func (s *RdsService) WaitForDBDatabase(id string, status Status, timeout int) error {
parts, err := ParseResourceId(id, 2)
if err != nil {
return WrapError(err)
}
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeDBDatabase(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
}
return WrapError(err)
}
if object != nil && object["DBName"] == parts[1] {
break
}
time.Sleep(DefaultIntervalShort * time.Second)
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object["DBName"], parts[1], ProviderERROR)
}
}
return nil
}
// turn period to TimeType
func (s *RdsService) TransformPeriod2Time(period int, chargeType string) (ut int, tt common.TimeType) {
if chargeType == string(Postpaid) {
return 1, common.Day
}
if period >= 1 && period <= 9 {
return period, common.Month
}
if period == 12 {
return 1, common.Year
}
if period == 24 {
return 2, common.Year
}
return 0, common.Day
}
// turn TimeType to Period
func (s *RdsService) TransformTime2Period(ut int, tt common.TimeType) (period int) {
if tt == common.Year {
return 12 * ut
}
return ut
}
func (s *RdsService) flattenDBSecurityIPs(list []interface{}) []map[string]interface{} {
result := make([]map[string]interface{}, 0, len(list))
for _, i := range list {
i := i.(map[string]interface{})
l := map[string]interface{}{
"security_ips": i["SecurityIPList"],
}
result = append(result, l)
}
return result
}
func (s *RdsService) setInstanceTags(d *schema.ResourceData) error {
if d.HasChange("tags") {
added, removed := parsingTags(d)
conn, err := s.client.NewRdsClient()
if err != nil {
return WrapError(err)
}
removedTagKeys := make([]string, 0)
for _, v := range removed {
if !ignoredTags(v, "") {
removedTagKeys = append(removedTagKeys, v)
}
}
if len(removedTagKeys) > 0 {
action := "UnTagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": "INSTANCE",
"ResourceId.1": d.Id(),
"SourceIp": s.client.SourceIp,
}
for i, key := range removedTagKeys {
request[fmt.Sprintf("TagKey.%d", i+1)] = key
}
wait := incrementalWait(1*time.Second, 2*time.Second)
runtime := util.RuntimeOptions{}
err = resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsThrottling(err) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
action := "TagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": "INSTANCE",
"ResourceId.1": d.Id(),
}
count := 1
for key, value := range added {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
wait := incrementalWait(1*time.Second, 2*time.Second)
runtime := util.RuntimeOptions{}
err = resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsThrottling(err) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("tags")
}
return nil
}
func (s *RdsService) describeTags(d *schema.ResourceData) (tags []Tag, err error) {
action := "DescribeTags"
request := map[string]interface{}{
"DBInstanceId": d.Id(),
"RegionId": s.client.RegionId,
"SourceIp": s.client.SourceIp,
}
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
return nil, WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
return s.respToTags(response["Items"].(map[string]interface{})["TagInfos"].([]interface{})), nil
}
func (s *RdsService) respToTags(tagSet []interface{}) (tags []Tag) {
result := make([]Tag, 0, len(tagSet))
for _, t := range tagSet {
t := t.(map[string]interface{})
tag := Tag{
Key: t["TagKey"].(string),
Value: t["TagValue"].(string),
}
result = append(result, tag)
}
return result
}
func (s *RdsService) tagsToMap(tags []Tag) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !s.ignoreTag(t) {
result[t.Key] = t.Value
}
}
return result
}
func (s *RdsService) ignoreTag(t Tag) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, t.Key)
ok, _ := regexp.MatchString(v, t.Key)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific t %s (val: %s), ignoring.\n", t.Key, t.Value)
return true
}
}
return false
}
func (s *RdsService) tagsToString(tags []Tag) string {
v, _ := json.Marshal(s.tagsToMap(tags))
return string(v)
}
func (s *RdsService) DescribeDBProxy(id string) (map[string]interface{}, error) {
action := "DescribeDBProxy"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": id,
"SourceIp": s.client.SourceIp,
}
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return nil, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
return response, nil
}
func (s *RdsService) DescribeDBProxyEndpoint(id string, endpointName string) (map[string]interface{}, error) {
action := "DescribeDBProxyEndpoint"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DBInstanceId": id,
"DBProxyEndpointId": endpointName,
"SourceIp": s.client.SourceIp,
}
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound", "Endpoint.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return nil, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
return response, nil
}
func (s *RdsService) DescribeRdsParameterGroup(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeParameterGroup"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ParameterGroupId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"ParamGroupsNotExistError"}) {
err = WrapErrorf(Error(GetNotFoundMessage("RdsParameterGroup", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.ParamGroup.ParameterGroup", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ParamGroup.ParameterGroup", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("RDS", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["ParameterGroupId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("RDS", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *RdsService) DescribeRdsAccount(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeAccounts"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"SourceIp": s.client.SourceIp,
"AccountName": parts[1],
"DBInstanceId": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDBInstanceId.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("RdsAccount", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Accounts.DBInstanceAccount", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Accounts.DBInstanceAccount", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("RDS", id)), NotFoundWithResponse, response)
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *RdsService) RdsAccountStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeRdsAccount(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["AccountStatus"].(string) == failState {
return object, object["AccountStatus"].(string), WrapError(Error(FailedToReachTargetStatus, object["AccountStatus"].(string)))
}
}
return object, object["AccountStatus"].(string), nil
}
}
func (s *RdsService) DescribeRdsBackup(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeBackups"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"SourceIp": s.client.SourceIp,
"BackupId": parts[1],
"DBInstanceId": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Items.Backup", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Items.Backup", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("RDS", id)), NotFoundWithResponse, response)
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *RdsService) DescribeBackupTasks(id string, backupJobId string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeBackupTasks"
request := map[string]interface{}{
"SourceIp": s.client.SourceIp,
"DBInstanceId": id,
"BackupJobId": backupJobId,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Items.BackupJob", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Items.BackupJob", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("RDS", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["BackupJobId"]) != backupJobId {
return object, WrapErrorf(Error(GetNotFoundMessage("RDS", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *RdsService) RdsBackupStateRefreshFunc(id string, backupJobId string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeBackupTasks(id, backupJobId)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["BackupStatus"] == failState {
return object, object["BackupStatus"].(string), WrapError(Error(FailedToReachTargetStatus, object["BackupStatus"]))
}
}
return object, object["BackupStatus"].(string), nil
}
}
func (s *RdsService) DescribeDBInstanceHAConfig(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDBInstanceHAConfig"
request := map[string]interface{}{
"SourceIp": s.client.SourceIp,
"DBInstanceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *RdsService) DescribeRdsCloneDbInstance(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDBInstanceAttribute"
request := map[string]interface{}{
"SourceIp": s.client.SourceIp,
"DBInstanceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Items.DBInstanceAttribute", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Items.DBInstanceAttribute", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("RDS", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["DBInstanceId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("RDS", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *RdsService) DescribePGHbaConfig(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribePGHbaConfig"
request := map[string]interface{}{
"SourceIp": s.client.SourceIp,
"DBInstanceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *RdsService) DescribeUpgradeMajorVersionPrecheckTask(id string, taskId int) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewRdsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeUpgradeMajorVersionPrecheckTask"
request := map[string]interface{}{
"SourceIp": s.client.SourceIp,
"DBInstanceId": id,
"TaskId": taskId,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-08-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Items", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Items", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("RDS", id)), NotFoundWithResponse, response)
} else {
if formatInt(v.([]interface{})[0].(map[string]interface{})["TaskId"]) != taskId {
return object, WrapErrorf(Error(GetNotFoundMessage("RDS", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *RdsService) RdsUpgradeMajorVersionRefreshFunc(id string, taskId int, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeUpgradeMajorVersionPrecheckTask(id, taskId)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["Result"] == failState {
return object, object["Result"].(string), WrapError(Error(FailedToReachTargetStatus, object["Result"]))
}
}
return object, object["Result"].(string), nil
}
}
package alicloud
import (
"fmt"
"log"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type ResourcemanagerService struct {
client *connectivity.AliyunClient
}
func (s *ResourcemanagerService) DescribeResourceManagerRole(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewResourcemanagerClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetRole"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"RoleName": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist.Role"}) {
err = WrapErrorf(Error(GetNotFoundMessage("ResourceManagerRole", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Role", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Role", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *ResourcemanagerService) DescribeResourceManagerResourceGroup(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewResourcemanagerClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetResourceGroup"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceGroupId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.ResourceGroup"}) {
err = WrapErrorf(Error(GetNotFoundMessage("ResourceManagerResourceGroup", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.ResourceGroup", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ResourceGroup", response)
}
if vv, ok := v.(map[string]interface{})["Status"].(string); ok && vv == "PendingDelete" {
log.Printf("[WARN] Removing ResourceManagerResourceGroup %s because it's already gone", id)
return v.(map[string]interface{}), WrapErrorf(Error(GetNotFoundMessage("ResourceManagerResourceGroup", id)), NotFoundMsg, ProviderERROR)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *ResourcemanagerService) ResourceManagerResourceGroupStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeResourceManagerResourceGroup(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["Status"].(string) == failState {
return object, object["Status"].(string), WrapError(Error(FailedToReachTargetStatus, object["Status"].(string)))
}
}
return object, object["Status"].(string), nil
}
}
func (s *ResourcemanagerService) DescribeResourceManagerFolder(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewResourcemanagerClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetFolder"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"FolderId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Folder", "EntityNotExists.ResourceDirectory"}) {
err = WrapErrorf(Error(GetNotFoundMessage("ResourceManagerFolder", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Folder", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Folder", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *ResourcemanagerService) DescribeResourceManagerHandshake(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewResourcemanagerClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetHandshake"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"HandshakeId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Handshake"}) {
err = WrapErrorf(Error(GetNotFoundMessage("ResourceManagerHandshake", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Handshake", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Handshake", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *ResourcemanagerService) GetPolicyVersion(id string, d *schema.ResourceData) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewResourcemanagerClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetPolicyVersion"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"PolicyName": id,
"PolicyType": "Custom",
}
if v, ok := d.GetOk("default_version"); ok {
request["VersionId"] = v.(string)
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist.Policy", "EntityNotExist.Policy.Version"}) {
err = WrapErrorf(Error(GetNotFoundMessage("ResourceManagerPolicy", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.PolicyVersion", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.PolicyVersion", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *ResourcemanagerService) DescribeResourceManagerPolicy(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewResourcemanagerClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetPolicy"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"PolicyName": id,
"PolicyType": "Custom",
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist.Policy"}) {
err = WrapErrorf(Error(GetNotFoundMessage("ResourceManagerPolicy", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Policy", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Policy", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *ResourcemanagerService) DescribeResourceManagerAccount(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewResourcemanagerClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetAccount"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"AccountId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Account", "EntityNotExists.ResourceDirectory"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("ResourceManager:Account", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Account", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Account", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *ResourcemanagerService) DescribeResourceManagerResourceDirectory(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewResourcemanagerClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetResourceDirectory"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"ResourceDirectoryNotInUse"}) {
err = WrapErrorf(Error(GetNotFoundMessage("ResourceManagerResourceDirectory", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.ResourceDirectory", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ResourceDirectory", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *ResourcemanagerService) DescribeResourceManagerPolicyVersion(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewResourcemanagerClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetPolicyVersion"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"PolicyName": parts[0],
"VersionId": parts[1],
"PolicyType": "Custom",
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist.Policy", "EntityNotExist.Policy.Version"}) {
err = WrapErrorf(Error(GetNotFoundMessage("ResourceManagerPolicyVersion", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.PolicyVersion", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.PolicyVersion", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *ResourcemanagerService) DescribeResourceManagerPolicyAttachment(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewResourcemanagerClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListPolicyAttachments"
parts, err := ParseResourceId(id, 5)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"PolicyName": parts[0],
"PolicyType": parts[1],
"PrincipalName": parts[2],
"PrincipalType": parts[3],
"ResourceGroupId": parts[4],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExist.Policy", "EntityNotExists.ResourceGroup"}) {
err = WrapErrorf(Error(GetNotFoundMessage("ResourceManagerPolicyAttachment", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.PolicyAttachments.PolicyAttachment", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.PolicyAttachments.PolicyAttachment", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ResourceManager", id)), NotFoundWithResponse, response)
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *ResourcemanagerService) DescribeResourceManagerControlPolicy(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewResourcemanagerClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetControlPolicy"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"PolicyId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.ControlPolicy"}) {
err = WrapErrorf(Error(GetNotFoundMessage("ResourceManagerControlPolicy", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.ControlPolicy", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ControlPolicy", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *ResourcemanagerService) DescribeResourceManagerControlPolicyAttachment(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewResourcemanagerClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListControlPolicyAttachmentsForTarget"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"TargetId": parts[1],
}
idExist := false
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"EntityNotExists.Target"}) {
err = WrapErrorf(Error(GetNotFoundMessage("ResourceManagerControlPolicyAttachment", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.ControlPolicyAttachments.ControlPolicyAttachment", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ControlPolicyAttachments.ControlPolicyAttachment", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ResourceManager", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if v.(map[string]interface{})["PolicyId"].(string) == parts[0] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("ResourceManager", id)), NotFoundWithResponse, response)
}
return object, nil
}
func (s *ResourcemanagerService) ResourceManagerResourceDirectoryStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeResourceManagerResourceDirectory(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["ScpStatus"].(string) == failState {
return object, object["ScpStatus"].(string), WrapError(Error(FailedToReachTargetStatus, object["ScpStatus"].(string)))
}
}
return object, object["ScpStatus"].(string), nil
}
}
func (s *ResourcemanagerService) GetPayerForAccount(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewResourcemanagerClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetPayerForAccount"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"AccountId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-03-31"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type ResourcesharingService struct {
client *connectivity.AliyunClient
}
func (s *ResourcesharingService) DescribeResourceManagerResourceShare(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewRessharingClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListResourceShares"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceShareIds": []string{id},
"ResourceOwner": "Self",
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.ResourceShares", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ResourceShares", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ResourceManager", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["ResourceShareId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ResourceManager", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *ResourcesharingService) ResourceManagerResourceShareStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeResourceManagerResourceShare(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["ResourceShareStatus"].(string) == failState {
return object, object["ResourceShareStatus"].(string), WrapError(Error(FailedToReachTargetStatus, object["ResourceShareStatus"].(string)))
}
}
return object, object["ResourceShareStatus"].(string), nil
}
}
func (s *ResourcesharingService) DescribeResourceManagerSharedResource(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewRessharingClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListResourceShareAssociations"
parts, err := ParseResourceId(id, 3)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceId": parts[1],
"ResourceShareIds": []string{parts[0]},
"AssociationType": "Resource",
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.ResourceShareAssociations", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ResourceShareAssociations", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ResourceManager", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if v.(map[string]interface{})["EntityType"].(string) == parts[2] {
return v.(map[string]interface{}), nil
}
}
if nextToken, ok := response["NextToken"].(string); ok && nextToken != "" {
request["NextToken"] = nextToken
} else {
break
}
return object, nil
}
return
}
func (s *ResourcesharingService) ResourceManagerSharedResourceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeResourceManagerSharedResource(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["AssociationStatus"].(string) == failState {
return object, object["AssociationStatus"].(string), WrapError(Error(FailedToReachTargetStatus, object["AssociationStatus"].(string)))
}
}
return object, object["AssociationStatus"].(string), nil
}
}
func (s *ResourcesharingService) DescribeResourceManagerSharedTarget(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewRessharingClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListResourceShareAssociations"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceShareIds": []string{parts[0]},
"Target": parts[1],
"AssociationType": "Target",
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.ResourceShareAssociations", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ResourceShareAssociations", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ResourceManager", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["EntityId"].(string) != parts[1] {
return object, WrapErrorf(Error(GetNotFoundMessage("ResourceManager", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *ResourcesharingService) ResourceManagerSharedTargetStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeResourceManagerSharedTarget(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["AssociationStatus"].(string) == failState {
return object, object["AssociationStatus"].(string), WrapError(Error(FailedToReachTargetStatus, object["AssociationStatus"].(string)))
}
}
return object, object["AssociationStatus"].(string), nil
}
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type RosService struct {
client *connectivity.AliyunClient
}
func (s *RosService) DescribeRosChangeSet(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewRosClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetChangeSet"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ChangeSetId": id,
"ShowTemplate": true,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"ChangeSetNotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("RosChangeSet", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *RosService) RosChangeSetStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeRosChangeSet(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["Status"].(string) == failState {
return object, object["Status"].(string), WrapError(Error(FailedToReachTargetStatus, object["Status"].(string)))
}
}
return object, object["Status"].(string), nil
}
}
func (s *RosService) DescribeRosStack(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewRosClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetStack"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"StackId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
request["ClientToken"] = buildClientToken("GetStack")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"StackNotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("RosStack", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *RosService) RosStackStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeRosStack(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["Status"].(string) == failState {
return object, object["Status"].(string), WrapError(Error(FailedToReachTargetStatus, object["Status"].(string)))
}
}
return object, object["Status"].(string), nil
}
}
func (s *RosService) GetStackPolicy(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewRosClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetStackPolicy"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"StackId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"StackNotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("RosStack", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *RosService) ListTagResources(id string, resourceType string) (object interface{}, err error) {
conn, err := s.client.NewRosClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListTagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": id,
}
tags := make([]interface{}, 0)
var response map[string]interface{}
for {
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{Throttling}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.TagResources", response)
if err != nil {
return resource.NonRetryableError(WrapErrorf(err, FailedGetAttributeMsg, id, "$.TagResources.TagResource", response))
}
if v != nil {
tags = append(tags, v.([]interface{})...)
}
return nil
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
if response["NextToken"] == nil {
break
}
request["NextToken"] = response["NextToken"]
}
return tags, nil
}
func (s *RosService) SetResourceTags(d *schema.ResourceData, resourceType string) error {
if d.HasChange("tags") {
added, removed := parsingTags(d)
conn, err := s.client.NewRosClient()
if err != nil {
return WrapError(err)
}
removedTagKeys := make([]string, 0)
for _, v := range removed {
if !ignoredTags(v, "") {
removedTagKeys = append(removedTagKeys, v)
}
}
if len(removedTagKeys) > 0 {
action := "UntagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": d.Id(),
}
for i, key := range removedTagKeys {
request[fmt.Sprintf("TagKey.%d", i+1)] = key
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
action := "TagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": string(resourceType),
"ResourceId.1": d.Id(),
}
count := 1
for key, value := range added {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("tags")
}
return nil
}
func (s *RosService) DescribeRosStackGroup(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewRosClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetStackGroup"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"StackGroupName": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"StackGroupNotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("RosStackGroup", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.StackGroup", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.StackGroup", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *RosService) RosStackGroupStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeRosStackGroup(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["Status"].(string) == failState {
return object, object["Status"].(string), WrapError(Error(FailedToReachTargetStatus, object["Status"].(string)))
}
}
return object, object["Status"].(string), nil
}
}
func (s *RosService) DescribeRosTemplate(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewRosClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetTemplate"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"TemplateId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"ChangeSetNotFound", "StackNotFound", "TemplateNotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("RosTemplate", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *RosService) DescribeRosStackInstance(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewRosClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetStackInstance"
parts, err := ParseResourceId(id, 3)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"StackGroupName": parts[0],
"StackInstanceAccountId": parts[1],
"StackInstanceRegionId": parts[2],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"StackInstanceNotFound", "StackGroupNotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("ROS:StackInstance", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.StackInstance", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.StackInstance", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *RosService) RosStackInstanceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeRosStackInstance(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *RosService) DescribeRosTemplateScratch(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewRosClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetTemplateScratch"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"TemplateScratchId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"TemplateScratchNotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("ROS:TemplateScratch", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.TemplateScratch", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.TemplateScratch", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *RosService) RosTemplateScratchStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeRosTemplateScratch(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
package alicloud
import (
"encoding/json"
"fmt"
"strconv"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type SaeService struct {
client *connectivity.AliyunClient
}
func (s *SaeService) DescribeSaeNamespace(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewServerlessClient()
if err != nil {
return nil, WrapError(err)
}
action := "/pop/v1/paas/namespace"
request := map[string]*string{
"NamespaceId": StringPointer(id),
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("GET"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidNamespaceId.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("SAE:Namespace", id)), NotFoundMsg, ProviderERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, "alicloud_sae_namespace", "GET "+action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
addDebug(action, response, request)
if IsExpectedErrorCodes(fmt.Sprint(response["Code"]), []string{"InvalidNamespaceId.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("SAE:Namespace", id)), NotFoundMsg, ProviderERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", "GET "+action, response))
}
v, err := jsonpath.Get("$.Data", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *SaeService) DescribeSaeConfigMap(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewServerlessClient()
if err != nil {
return nil, WrapError(err)
}
action := "/pop/v1/sam/configmap/configMap"
request := map[string]*string{
"ConfigMapId": StringPointer(id),
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("GET"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"NotFound.ConfigMap"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("SAE:ConfigMap", id)), NotFoundMsg, ProviderERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
addDebug(action, response, request)
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.Data", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *SaeService) DescribeApplicationStatus(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewServerlessClient()
if err != nil {
return nil, WrapError(err)
}
action := "/pop/v1/sam/app/describeApplicationStatus"
request := map[string]*string{
"AppId": StringPointer(id),
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("GET"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return object, WrapError(fmt.Errorf("%s failed, response: %v", "Put "+action, response))
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.Data", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *SaeService) DescribeSaeApplication(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewServerlessClient()
if err != nil {
return nil, WrapError(err)
}
action := "/pop/v1/sam/app/describeApplicationConfig"
request := map[string]*string{
"AppId": StringPointer(id),
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("GET"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidAppId.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("SAE:Application", id)), NotFoundMsg, ProviderERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return object, WrapError(fmt.Errorf("%s failed, response: %v", "Put "+action, response))
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.Data", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *SaeService) DescribeSaeIngress(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewServerlessClient()
if err != nil {
return nil, WrapError(err)
}
action := "/pop/v1/sam/ingress/Ingress"
request := map[string]*string{
"IngressId": StringPointer(id),
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("GET"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if IsExpectedErrors(err, []string{"InvalidParameter.WithMessage"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("SAE:Ingress", id)), NotFoundMsg, ProviderERROR)
}
addDebug(action, response, request)
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return object, WrapError(fmt.Errorf("%s failed, response: %v", "GET "+action, response))
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.Data", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *SaeService) DescribeApplicationImage(id, imageUrl string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewServerlessClient()
if err != nil {
return nil, WrapError(err)
}
action := "/pop/v1/sam/container/describeApplicationImage"
request := map[string]*string{
"AppId": StringPointer(id),
"ImageUrl": StringPointer(imageUrl),
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("GET"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return object, WrapError(fmt.Errorf("%s failed, response: %v", "Put "+action, response))
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.Data", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *SaeService) DescribeIngress(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewServerlessClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeIngress"
request := map[string]*string{
"IngressId": StringPointer(id),
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("GET"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return object, WrapError(fmt.Errorf("%s failed, response: %v", "GET "+action, response))
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.Data", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *SaeService) DescribeApplicationSlb(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewServerlessClient()
if err != nil {
return nil, WrapError(err)
}
action := "/pop/v1/sam/app/slb"
request := map[string]*string{
"AppId": StringPointer(id),
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("GET"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return object, WrapError(fmt.Errorf("%s failed, response: %v", "Put "+action, response))
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.Data", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *SaeService) UpdateSlb(d *schema.ResourceData) error {
if d.HasChange("intranet") || d.HasChange("internet") || d.HasChange("internet_slb_id") || d.HasChange("intranet_slb_id") {
update := false
request := map[string]*string{
"AppId": StringPointer(d.Id()),
}
//unbind intranet
if d.HasChange("intranet") {
oraw, nraw := d.GetChange("intranet")
remove := oraw.(*schema.Set).Difference(nraw.(*schema.Set)).List()
if len(remove) != 0 {
update = true
request["Intranet"] = StringPointer(strconv.FormatBool(true))
}
}
//unbind internet
if d.HasChange("internet") {
oraw, nraw := d.GetChange("internet")
remove := oraw.(*schema.Set).Difference(nraw.(*schema.Set)).List()
if len(remove) != 0 {
update = true
request["Internet"] = StringPointer(strconv.FormatBool(true))
}
}
if update {
action := "/pop/v1/sam/app/slb"
conn, err := s.client.NewServerlessClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
var response map[string]interface{}
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("DELETE"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Application.InvalidStatus", "Application.ChangerOrderRunning"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "POST "+action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return WrapError(fmt.Errorf("%s failed, response: %v", "POST "+action, response))
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", "POST "+action, response))
}
return nil
}
update = false
request = map[string]*string{
"AppId": StringPointer(d.Id()),
}
if d.HasChange("internet_slb_id") {
update = true
if v, exist := d.GetOk("internet_slb_id"); exist {
request["InternetSlbId"] = StringPointer(v.(string))
}
}
if d.HasChange("intranet_slb_id") {
update = true
if v, exist := d.GetOk("intranet_slb_id"); exist {
request["IntranetSlbId"] = StringPointer(v.(string))
}
}
if d.HasChange("intranet") {
update = true
for _, intranet := range d.Get("intranet").(*schema.Set).List() {
intranetMap := intranet.(map[string]interface{})
intranetReq := []interface{}{
map[string]interface{}{
"httpsCertId": intranetMap["https_cert_id"],
"protocol": intranetMap["protocol"],
"targetPort": intranetMap["target_port"],
"port": intranetMap["port"],
},
}
obj, err := json.Marshal(intranetReq)
if err != nil {
return WrapError(err)
}
request["Intranet"] = StringPointer(string(obj))
}
}
if d.HasChange("internet") {
update = true
for _, internet := range d.Get("internet").(*schema.Set).List() {
internetMap := internet.(map[string]interface{})
internetReq := []interface{}{
map[string]interface{}{
"httpsCertId": internetMap["https_cert_id"],
"protocol": internetMap["protocol"],
"targetPort": internetMap["target_port"],
"port": internetMap["port"],
},
}
obj, err := json.Marshal(internetReq)
if err != nil {
return WrapError(err)
}
request["Internet"] = StringPointer(string(obj))
}
}
if update {
action := "/pop/v1/sam/app/slb"
conn, err := s.client.NewServerlessClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
var response map[string]interface{}
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer("2019-05-06"), nil, StringPointer("POST"), StringPointer("AK"), StringPointer(action), request, nil, nil, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{"Application.InvalidStatus", "Application.ChangerOrderRunning"}) || NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), "POST "+action, AlibabaCloudSdkGoERROR)
}
if respBody, isExist := response["body"]; isExist {
response = respBody.(map[string]interface{})
} else {
return WrapError(fmt.Errorf("%s failed, response: %v", "POST "+action, response))
}
if fmt.Sprint(response["Success"]) == "false" {
return WrapError(fmt.Errorf("%s failed, response: %v", "POST "+action, response))
}
}
}
return nil
}
func (s *SaeService) SaeApplicationStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeApplicationStatus(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil if nothing matched
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["LastChangeOrderStatus"]) == failState {
return object, fmt.Sprint(object["LastChangeOrderStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["LastChangeOrderStatus"])))
}
}
return object, fmt.Sprint(object["LastChangeOrderStatus"]), nil
}
}
package alicloud
import (
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/smartag"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type SagService struct {
client *connectivity.AliyunClient
}
func (s *SagService) DescribeCloudConnectNetwork(id string) (c smartag.CloudConnectNetwork, err error) {
request := smartag.CreateDescribeCloudConnectNetworksRequest()
request.RegionId = s.client.RegionId
request.CcnId = id
var raw interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithSagClient(func(ccnClient *smartag.Client) (interface{}, error) {
return ccnClient.DescribeCloudConnectNetworks(request)
})
if err != nil {
if IsExpectedErrors(err, []string{AliyunGoClientFailure, "ServiceUnavailable", Throttling, "Throttling.User"}) {
time.Sleep(DefaultIntervalShort * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"CcnNotExist"}) {
return c, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return c, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*smartag.DescribeCloudConnectNetworksResponse)
if len(response.CloudConnectNetworks.CloudConnectNetwork) <= 0 || response.CloudConnectNetworks.CloudConnectNetwork[0].CcnId != id {
return c, WrapErrorf(Error(GetNotFoundMessage("CloudConnectNetwork ", id)), NotFoundMsg, ProviderERROR)
}
c = response.CloudConnectNetworks.CloudConnectNetwork[0]
return c, nil
}
func (s *SagService) DescribeCloudConnectNetworkGrant(id string) (c smartag.GrantRule, err error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
return c, WrapError(err)
}
request := smartag.CreateDescribeGrantRulesRequest()
request.RegionId = s.client.RegionId
request.AssociatedCcnId = parts[0]
var raw interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithSagClient(func(ccnClient *smartag.Client) (interface{}, error) {
return ccnClient.DescribeGrantRules(request)
})
if err != nil {
if IsExpectedErrors(err, []string{AliyunGoClientFailure, "ServiceUnavailable", Throttling, "Throttling.User"}) {
time.Sleep(DefaultIntervalShort * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"CcnNotExist"}) {
return c, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return c, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*smartag.DescribeGrantRulesResponse)
for _, value := range response.GrantRules.GrantRule {
if value.CcnInstanceId == parts[0] && value.CenInstanceId == parts[1] {
return value, nil
}
}
return c, WrapErrorf(Error(GetNotFoundMessage("CloudConnectNetworkGrant", id)), NotFoundMsg, ProviderERROR)
}
func (s *SagService) DescribeCloudConnectNetworkAttachment(id string) (c smartag.SmartAccessGateway, err error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
return c, WrapError(err)
}
ccnId := parts[0]
sagId := parts[1]
request := smartag.CreateDescribeSmartAccessGatewaysRequest()
request.RegionId = s.client.RegionId
request.SmartAGId = sagId
var raw interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithSagClient(func(ccnClient *smartag.Client) (interface{}, error) {
return ccnClient.DescribeSmartAccessGateways(request)
})
if err != nil {
if IsExpectedErrors(err, []string{AliyunGoClientFailure, "ServiceUnavailable", Throttling, "Throttling.User"}) {
time.Sleep(DefaultIntervalShort * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"SmartAccessGatewayNotExist"}) {
return c, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return c, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*smartag.DescribeSmartAccessGatewaysResponse)
if len(response.SmartAccessGateways.SmartAccessGateway) <= 0 || response.SmartAccessGateways.SmartAccessGateway[0].AssociatedCcnId != ccnId || response.SmartAccessGateways.SmartAccessGateway[0].SmartAGId != sagId {
return c, WrapErrorf(Error(GetNotFoundMessage("SmartAccessGatewayAttachment", id)), NotFoundMsg, ProviderERROR)
}
c = response.SmartAccessGateways.SmartAccessGateway[0]
return c, nil
}
func (s *SagService) DescribeSagAcl(id string) (c smartag.Acl, err error) {
request := smartag.CreateDescribeACLsRequest()
request.RegionId = s.client.RegionId
request.AclIds = id
var raw interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.DescribeACLs(request)
})
if err != nil {
if IsExpectedErrors(err, []string{AliyunGoClientFailure, "ServiceUnavailable", Throttling, "Throttling.User"}) {
time.Sleep(DefaultIntervalShort * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"SagAclNotExist"}) {
return c, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return c, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*smartag.DescribeACLsResponse)
if len(response.Acls.Acl) <= 0 || response.Acls.Acl[0].AclId != id {
return c, WrapErrorf(Error(GetNotFoundMessage("Sag Acl", id)), NotFoundMsg, ProviderERROR)
}
c = response.Acls.Acl[0]
return c, nil
}
func (s *SagService) DescribeSagAclRule(id string) (c smartag.Acr, err error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
return c, WrapError(err)
}
request := smartag.CreateDescribeACLAttributeRequest()
request.RegionId = s.client.RegionId
request.AclId = parts[0]
var raw interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.DescribeACLAttribute(request)
})
if err != nil {
if IsExpectedErrors(err, []string{AliyunGoClientFailure, "ServiceUnavailable", Throttling, "Throttling.User"}) {
time.Sleep(DefaultIntervalShort * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"SagAclRuleNotExist"}) {
return c, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return c, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*smartag.DescribeACLAttributeResponse)
for _, value := range response.Acrs.Acr {
if value.AcrId == parts[1] {
return value, nil
}
}
return c, WrapErrorf(Error(GetNotFoundMessage("Sag Acl Rule", id)), NotFoundMsg, ProviderERROR)
}
func (s *SagService) DescribeSagClientUser(id string) (c smartag.User, err error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
return c, WrapError(err)
}
request := smartag.CreateDescribeSmartAccessGatewayClientUsersRequest()
request.RegionId = s.client.RegionId
request.SmartAGId = parts[0]
var raw interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.DescribeSmartAccessGatewayClientUsers(request)
})
if err != nil {
if IsExpectedErrors(err, []string{AliyunGoClientFailure, "ServiceUnavailable", Throttling, "Throttling.User"}) {
time.Sleep(DefaultIntervalShort * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"SagClientUserNotExist"}) {
return c, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return c, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*smartag.DescribeSmartAccessGatewayClientUsersResponse)
for _, value := range response.Users.User {
if value.UserName == parts[1] {
return value, nil
}
}
return c, WrapErrorf(Error(GetNotFoundMessage("Sag Client User", id)), NotFoundMsg, ProviderERROR)
}
func (s *SagService) DescribeSagSnatEntry(id string) (c smartag.SnatEntry, err error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
return c, WrapError(err)
}
request := smartag.CreateDescribeSnatEntriesRequest()
request.RegionId = s.client.RegionId
request.SmartAGId = parts[0]
var raw interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.DescribeSnatEntries(request)
})
if err != nil {
if IsExpectedErrors(err, []string{AliyunGoClientFailure, "ServiceUnavailable", Throttling, "Throttling.User"}) {
time.Sleep(DefaultIntervalShort * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"SnatEntryiesNotExist"}) {
return c, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return c, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*smartag.DescribeSnatEntriesResponse)
for _, value := range response.SnatEntries.SnatEntry {
if value.InstanceId == parts[1] {
return value, nil
}
}
return c, WrapErrorf(Error(GetNotFoundMessage("sag_snat_entry", id)), NotFoundMsg, ProviderERROR)
}
func (s *SagService) DescribeSagDnatEntry(id string) (c smartag.DnatEntry, err error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
return c, WrapError(err)
}
request := smartag.CreateDescribeDnatEntriesRequest()
request.RegionId = s.client.RegionId
request.SagId = parts[0]
var raw interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.DescribeDnatEntries(request)
})
if err != nil {
if IsExpectedErrors(err, []string{AliyunGoClientFailure, "ServiceUnavailable", Throttling, "Throttling.User"}) {
time.Sleep(DefaultIntervalShort * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"DnatEntryiesNotExist"}) {
return c, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return c, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*smartag.DescribeDnatEntriesResponse)
for _, value := range response.DnatEntries.DnatEntry {
if value.DnatEntryId == parts[1] {
return value, nil
}
}
return c, WrapErrorf(Error(GetNotFoundMessage("sag_dnat_entry", id)), NotFoundMsg, ProviderERROR)
}
func (s *SagService) DescribeSagQos(id string) (c smartag.Qos, err error) {
request := smartag.CreateDescribeQosesRequest()
request.RegionId = s.client.RegionId
request.QosIds = id
var raw interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.DescribeQoses(request)
})
if err != nil {
if IsExpectedErrors(err, []string{AliyunGoClientFailure, "ServiceUnavailable", Throttling, "Throttling.User"}) {
time.Sleep(DefaultIntervalShort * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"SagQosNotExist"}) {
return c, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return c, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*smartag.DescribeQosesResponse)
if len(response.Qoses.Qos) <= 0 || response.Qoses.Qos[0].QosId != id {
return c, WrapErrorf(Error(GetNotFoundMessage("Sag Qos", id)), NotFoundMsg, ProviderERROR)
}
c = response.Qoses.Qos[0]
return c, nil
}
func (s *SagService) DescribeSagQosPolicy(id string) (c smartag.QosPolicy, err error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
return c, WrapError(err)
}
request := smartag.CreateDescribeQosPoliciesRequest()
request.RegionId = s.client.RegionId
request.QosId = parts[0]
request.QosPolicyId = parts[1]
var raw interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.DescribeQosPolicies(request)
})
if err != nil {
if IsExpectedErrors(err, []string{AliyunGoClientFailure, "ServiceUnavailable", Throttling, "Throttling.User"}) {
time.Sleep(DefaultIntervalShort * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"SagQosPolicyNotExist"}) {
return c, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return c, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*smartag.DescribeQosPoliciesResponse)
if len(response.QosPolicies.QosPolicy) <= 0 || response.QosPolicies.QosPolicy[0].QosPolicyId != parts[1] {
return c, WrapErrorf(Error(GetNotFoundMessage("Sag Qos Policy", id)), NotFoundMsg, ProviderERROR)
}
c = response.QosPolicies.QosPolicy[0]
return c, nil
}
func (s *SagService) DescribeSagQosCar(id string) (c smartag.QosCar, err error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
return c, WrapError(err)
}
request := smartag.CreateDescribeQosCarsRequest()
request.RegionId = s.client.RegionId
request.QosId = parts[0]
request.QosCarId = parts[1]
var raw interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithSagClient(func(sagClient *smartag.Client) (interface{}, error) {
return sagClient.DescribeQosCars(request)
})
if err != nil {
if IsExpectedErrors(err, []string{AliyunGoClientFailure, "ServiceUnavailable", Throttling, "Throttling.User"}) {
time.Sleep(DefaultIntervalShort * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"SagQosCarNotExist"}) {
return c, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return c, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*smartag.DescribeQosCarsResponse)
if len(response.QosCars.QosCar) <= 0 || response.QosCars.QosCar[0].QosCarId != parts[1] {
return c, WrapErrorf(Error(GetNotFoundMessage("Sag Qos Car", id)), NotFoundMsg, ProviderERROR)
}
c = response.QosCars.QosCar[0]
return c, nil
}
func (s *SagService) WaitForCloudConnectNetwork(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeCloudConnectNetwork(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
}
return WrapError(err)
}
if object.CcnId == id && status != Deleted {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.CcnId, id, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *SagService) WaitForCloudConnectNetworkGrant(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
parts, err := ParseResourceId(id, 2)
if err != nil {
return WrapError(err)
}
for {
object, err := s.DescribeCloudConnectNetworkGrant(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
}
return WrapError(err)
}
if object.CenInstanceId == parts[1] && status != Deleted {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.CenInstanceId, parts[1], ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *SagService) WaitForCloudConnectNetworkAttachment(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
parts, err := ParseResourceId(id, 2)
if err != nil {
return WrapError(err)
}
ccnId := parts[0]
for {
object, err := s.DescribeCloudConnectNetworkAttachment(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
}
return WrapError(err)
}
if object.AssociatedCcnId == ccnId && status != Deleted {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.AssociatedCcnId, ccnId, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *SagService) WaitForSagAcl(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeSagAcl(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
}
return WrapError(err)
}
if object.AclId == id && status != Deleted {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.AclId, id, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *SagService) WaitForSagAclRule(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
parts, err := ParseResourceId(id, 2)
if err != nil {
return WrapError(err)
}
for {
object, err := s.DescribeSagAclRule(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
}
return WrapError(err)
}
if object.AcrId == parts[1] && status != Deleted {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.AcrId, parts[1], ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *SagService) WaitForSagQos(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeSagQos(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
}
return WrapError(err)
}
if object.QosId == id && status != Deleted {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.QosId, id, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *SagService) WaitForSagQosPolicy(id string, status Status, timeout int) error {
parts, err := ParseResourceId(id, 2)
if err != nil {
return WrapError(err)
}
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeSagQosPolicy(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
}
return WrapError(err)
}
if object.QosPolicyId == parts[1] && status != Deleted {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.QosPolicyId, parts[1], ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *SagService) WaitForSagQosCar(id string, status Status, timeout int) error {
parts, err := ParseResourceId(id, 2)
if err != nil {
return WrapError(err)
}
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeSagQosCar(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
}
return WrapError(err)
}
if object.QosCarId == parts[1] && status != Deleted {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.QosCarId, parts[1], ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *SagService) WaitForSagSnatEntry(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
parts, err := ParseResourceId(id, 2)
if err != nil {
return WrapError(err)
}
for {
object, err := s.DescribeSagSnatEntry(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
}
return WrapError(err)
}
if object.InstanceId == parts[1] && status != Deleted {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.InstanceId, parts[1], ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *SagService) WaitForSagDnatEntry(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
parts, err := ParseResourceId(id, 2)
if err != nil {
return WrapError(err)
}
for {
object, err := s.DescribeSagDnatEntry(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
}
return WrapError(err)
}
if object.DnatEntryId == parts[1] && status != Deleted {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.DnatEntryId, parts[1], ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *SagService) WaitForSagClientUser(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
parts, err := ParseResourceId(id, 2)
if err != nil {
return WrapError(err)
}
for {
object, err := s.DescribeSagClientUser(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
}
return WrapError(err)
}
if object.UserName == parts[1] && status != Deleted {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.UserName, parts[1], ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type SasService struct {
client *connectivity.AliyunClient
}
func (s *SasService) DescribeAllGroups(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewSasClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeAllGroups"
request := map[string]interface{}{}
idExist := false
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-03"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Groups", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Groups", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("SecurityCenter", id)), NotFoundWithResponse, response)
}
for _, vv := range v.([]interface{}) {
if fmt.Sprint(vv.(map[string]interface{})["GroupId"]) == id {
idExist = true
return vv.(map[string]interface{}), nil
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("SecurityCenter", id)), NotFoundWithResponse, response)
}
return object, nil
}
func (s *SasService) DescribeSecurityCenterServiceLinkedRole(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewSasClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeServiceLinkedRoleStatus"
request := map[string]interface{}{}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2018-12-03"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.RoleStatus", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.RoleStatus", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *SasService) SecurityCenterServiceLinkedRoleStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeSecurityCenterServiceLinkedRole(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
package alicloud
import (
"encoding/json"
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type ScdnService struct {
client *connectivity.AliyunClient
}
func (s *ScdnService) DescribeScdnDomainCertificateInfo(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewScdnClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeScdnDomainCertificateInfo"
request := map[string]interface{}{
"DomainName": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-11-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.CertInfos.CertInfo", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.CertInfos.CertInfo", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("SCDN", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["DomainName"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("SCDN", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *ScdnService) convertFunctionsToString(v []interface{}) (string, error) {
arrayMaps := make([]interface{}, len(v))
for i, vv := range v {
item := vv.(map[string]interface{})
temp := map[string]interface{}{
"ConfigId": item["config_id"],
"FunctionName": item["function_name"],
"Status": item["status"],
}
functionArgs := item["function_args"].(*schema.Set).List()
functionArgsMaps := make([]interface{}, len(functionArgs))
for j, functionArgsVal := range functionArgs {
functionArgsItem := functionArgsVal.(map[string]interface{})
functionArgsTemp := map[string]interface{}{
"ArgName": functionArgsItem["arg_name"],
"ArgValue": functionArgsItem["arg_value"],
}
functionArgsMaps[j] = functionArgsTemp
}
temp["function_args"] = functionArgsMaps
arrayMaps[i] = temp
}
maps, err := json.Marshal(arrayMaps)
if err != nil {
return "", WrapError(err)
}
return string(maps), nil
}
func (s *ScdnService) DescribeScdnDomain(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewScdnClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeScdnDomainDetail"
request := map[string]interface{}{
"DomainName": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-11-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDomain.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("SCDN:Domain", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.DomainDetail", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.DomainDetail", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *ScdnService) ScdnDomainStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeScdnDomain(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["DomainStatus"]) == failState {
return object, fmt.Sprint(object["DomainStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["DomainStatus"])))
}
}
return object, fmt.Sprint(object["DomainStatus"]), nil
}
}
func (s *ScdnService) DescribeScdnCertificateList(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewScdnClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeScdnCertificateList"
request := map[string]interface{}{
"DomainName": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-11-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.CertificateListModel.CertList.Cert", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.CertificateListModel.CertList.Cert", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("SCDN", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["DomainName"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("SCDN", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *ScdnService) DescribeScdnDomainCname(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewScdnClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeScdnDomainCname"
request := map[string]interface{}{
"DomainName": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2017-11-15"), StringPointer("AK"), request, nil, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.CnameDatas.Data", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.CnameDatas.Data", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("SCDN", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["DomainName"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("SCDN", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *ScdnService) DescribeScdnDomainConfigs(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewScdnClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeScdnDomainConfigs"
request := map[string]interface{}{
"DomainName": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-11-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.DomainConfigs.DomainConfig", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.DomainConfigs.DomainConfig", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("SCDN", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["DomainName"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("SCDN", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *ScdnService) DescribeScdnDomainDetail(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewScdnClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeScdnDomainDetail"
request := map[string]interface{}{
"DomainName": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-11-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDomain.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("SCDN:Domain", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.DomainDetail", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.DomainDetail", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *ScdnService) DescribeScdnDomainConfig(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewScdnClient()
if err != nil {
return nil, WrapError(err)
}
parts, err := ParseResourceId(id, 3)
if err != nil {
err = WrapError(err)
return
}
action := "DescribeScdnDomainConfigs"
request := map[string]interface{}{
"DomainName": parts[0],
"FunctionNames": parts[1],
}
if parts[2] != "" {
request["ConfigId"] = parts[2]
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-11-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDomain.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("ScdnDomainConfig", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.DomainConfigs.DomainConfig", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.DomainConfigs.DomainConfig", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("DCDN:DomainConfig", id)), NotFoundWithResponse, response)
} else if len(v.([]interface{})) > 0 {
object = v.([]interface{})[0].(map[string]interface{})
}
return object, nil
}
func (s *ScdnService) ScdnDomainConfigStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeScdnDomainConfig(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["Status"].(string) == failState {
return object, object["Status"].(string), WrapError(Error(FailedToReachTargetStatus, object["Status"].(string)))
}
}
return object, object["Status"].(string), nil
}
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type SddpService struct {
client *connectivity.AliyunClient
}
func (s *SddpService) DescribeSddpRule(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewSddpClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeRules"
request := map[string]interface{}{
"CurrentPage": 1,
"PageSize": 100,
"CustomType": 1,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-03"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Items", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Items", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("SDDP", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["Id"]) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["CurrentPage"] = request["CurrentPage"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("SDDP", id)), NotFoundWithResponse, response)
}
return
}
func (s *SddpService) DescribeSddpConfig(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewSddpClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeConfigs"
request := map[string]interface{}{
"Lang": "zh",
}
idExist := false
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-03"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.ConfigList", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ConfigList", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("SDDP", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["Code"]) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("SDDP", id)), NotFoundWithResponse, response)
}
return object, nil
}
func (s *SddpService) DescribeSddpInstance(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewSddpClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeUserStatus"
request := map[string]interface{}{}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-01-03"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.UserStatus", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.UserStatus", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type ServicemeshService struct {
client *connectivity.AliyunClient
}
func (s *ServicemeshService) DescribeServiceMeshServiceMesh(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewServicemeshClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeServiceMeshDetail"
request := map[string]interface{}{
"ServiceMeshId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"ServiceMesh.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("ServiceMesh:ServiceMesh", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.ServiceMesh", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ServiceMesh", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *ServicemeshService) DescribeServiceMeshDetail(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewServicemeshClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeServiceMeshDetail"
request := map[string]interface{}{
"ServiceMeshId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-01-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.ServiceMesh", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ServiceMesh", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *ServicemeshService) ServiceMeshServiceMeshStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeServiceMeshServiceMesh(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["ServiceMeshInfo"].(map[string]interface{})["State"]) == failState {
return object, fmt.Sprint(object["ServiceMeshInfo"].(map[string]interface{})["State"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["ServiceMeshInfo.State"])))
}
}
return object, fmt.Sprint(object["ServiceMeshInfo"].(map[string]interface{})["State"]), nil
}
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type SgwService struct {
client *connectivity.AliyunClient
}
func (s *SgwService) DescribeCloudStorageGatewayStorageBundle(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHcsSgwClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeStorageBundle"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"StorageBundleId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"StorageBundleNotExist"}) {
err = WrapErrorf(Error(GetNotFoundMessage("CloudStorageGatewayStorageBundle", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *SgwService) DescribeCloudStorageGatewayGateway(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHcsSgwClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeGateway"
request := map[string]interface{}{
"GatewayId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"GatewayNotExist"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudStorageGateway:Gateway", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *SgwService) DescribeGateway(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHcsSgwClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeGateway"
request := map[string]interface{}{
"GatewayId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"GatewayNotExist"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudStorageGateway:Gateway", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *SgwService) DescribeCloudStorageGatewayGatewaySmbUser(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHcsSgwClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeGatewaySMBUsers"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"GatewayId": parts[0],
"PageSize": PageSizeLarge,
"PageNumber": 1,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"GatewayNotExist"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudStorageGateway:Gateway", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.Users.User", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Users.User", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudStorageGateway", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["Username"]) == parts[1] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudStorageGateway", id)), NotFoundWithResponse, response)
}
return
}
func (s *SgwService) DescribeTasks(id, taskId string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHcsSgwClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeTasks"
request := map[string]interface{}{
"TargetId": id,
"PageSize": PageSizeLarge,
"PageNumber": 1,
}
if taskId != "" {
request["TaskId"] = taskId
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"GatewayNotExist"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudStorageGateway:Gateway:Task", id+":"+taskId)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.Tasks.SimpleTask", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Tasks.SimpleTask", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudStorageGateway Task", id+":"+taskId)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if taskId != "" && fmt.Sprint(v.(map[string]interface{})["TaskId"]) == taskId {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudStorageGateway Task", id+":"+taskId)), NotFoundWithResponse, response)
}
return
}
func (s *SgwService) CloudStorageGatewayTaskStateRefreshFunc(id, taskId string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeTasks(id, taskId)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["StateCode"]) == failState {
return object, fmt.Sprint(object["StateCode"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["StateCode"])))
}
}
return object, fmt.Sprint(object["StateCode"]), nil
}
}
func (s *SgwService) DescribeCloudStorageGatewayGatewayCacheDisk(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHcsSgwClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeGatewayCaches"
parts, err := ParseResourceId(id, 3)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"GatewayId": parts[0],
}
idExist := false
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"GatewayNotExist"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudStorageGateway:Gateway:CacheDisk", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.Caches.Cache", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Caches.Cache", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudStorageGateway", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["CacheId"]) == parts[1] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudStorageGateway", id)), NotFoundWithResponse, response)
}
return object, nil
}
func (s *SgwService) DescribeCloudStorageGatewayGatewayLogging(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHcsSgwClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeGatewayLogging"
request := map[string]interface{}{
"GatewayId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"GatewayNotExist"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudStorageGateway:GatewayLogging", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
if v, ok := object["GatewayLoggingStatus"]; ok && v == "None" {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudStorageGateway:GatewayLogging", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, nil
}
func (s *SgwService) DescribeCloudStorageGatewayGatewayBlockVolume(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHcsSgwClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeGatewayBlockVolumes"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"GatewayId": parts[0],
"IndexId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"GatewayNotExist"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudStorageGateway:BlockVolume", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.BlockVolumes.BlockVolume", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.BlockVolumes.BlockVolume", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudStorageGateway", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["IndexId"]) != parts[1] {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudStorageGateway", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *SgwService) DescribeCloudStorageGatewayGatewayFileShare(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHcsSgwClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeGatewayFileShares"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"GatewayId": parts[0],
"IndexId": parts[1],
"Refresh": true,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"GatewayNotExist"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudStorageGateway:Gateway:CacheDisk", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.FileShares.FileShare", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.FileShares.FileShare", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudStorageGateway", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["IndexId"]) != parts[1] {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudStorageGateway", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *SgwService) DescribeExpressSyncShares(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHcsSgwClient()
if err != nil {
return nil, WrapError(err)
}
parts, err := ParseResourceId(id, 3)
if err != nil {
return nil, err
}
action := "DescribeExpressSyncShares"
request := map[string]interface{}{
"ExpressSyncIds": parts[0],
}
idExist := false
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"GatewayNotExist", "ExpressSyncNotExist"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudStorageGateway:ExpressSyncShareAttachment", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.Shares.Share", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Shares.Share", response)
}
for _, v := range v.([]interface{}) {
item := v.(map[string]interface{})
if fmt.Sprint(item["GatewayId"]) == parts[1] && fmt.Sprint(item["ShareName"]) == parts[2] {
idExist = true
return item, nil
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudStorageGateway", id)), NotFoundWithResponse, response)
}
return object, nil
}
func (s *SgwService) DescribeExpressSyncs(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewHcsSgwClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeExpressSyncs"
request := map[string]interface{}{}
idExist := false
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-05-11"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"GatewayNotExist", "ExpressSyncNotExist"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudStorageGateway:ExpressSync", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Success"]) == "false" {
return object, WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
v, err := jsonpath.Get("$.ExpressSyncs.ExpressSync", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ExpressSyncs.ExpressSync", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudStorageGateway", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["ExpressSyncId"]) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("CloudStorageGateway", id)), NotFoundWithResponse, response)
}
return object, nil
}
package alicloud
import (
"encoding/json"
"fmt"
"log"
"regexp"
"strconv"
"strings"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
"github.com/aliyun/alibaba-cloud-sdk-go/services/slb"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type SlbService struct {
client *connectivity.AliyunClient
}
type SlbTag struct {
TagKey string
TagValue string
}
const max_num_per_time = 50
const tags_max_num_per_time = 5
const tags_max_page_size = 50
func (s *SlbService) BuildSlbCommonRequest() (*requests.CommonRequest, error) {
// Get product code from the built request
slbReq := slb.CreateCreateLoadBalancerRequest()
req, err := s.client.NewCommonRequest(slbReq.GetProduct(), slbReq.GetLocationServiceCode(), strings.ToUpper(string(Https)), connectivity.ApiVersion20140515)
if err != nil {
return req, WrapError(err)
}
req.RegionId = s.client.RegionId
return req, err
}
func (s *SlbService) DescribeSlb(id string) (*slb.DescribeLoadBalancerAttributeResponse, error) {
response := &slb.DescribeLoadBalancerAttributeResponse{}
request := slb.CreateDescribeLoadBalancerAttributeRequest()
request.RegionId = s.client.RegionId
request.LoadBalancerId = id
raw, err := s.client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeLoadBalancerAttribute(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidLoadBalancerId.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("Slb", id)), NotFoundMsg, AlibabaCloudSdkGoERROR)
} else {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return response, err
}
addDebug(request.GetActionName(), raw, request.RpcRequest)
response, _ = raw.(*slb.DescribeLoadBalancerAttributeResponse)
if response.LoadBalancerId == "" {
err = WrapErrorf(Error(GetNotFoundMessage("Slb", id)), NotFoundMsg, ProviderERROR)
}
return response, err
}
func (s *SlbService) DescribeSlbRule(id string) (*slb.DescribeRuleAttributeResponse, error) {
response := &slb.DescribeRuleAttributeResponse{}
request := slb.CreateDescribeRuleAttributeRequest()
request.RegionId = s.client.RegionId
request.RuleId = id
raw, err := s.client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeRuleAttribute(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidRuleId.NotFound"}) {
return response, WrapErrorf(Error(GetNotFoundMessage("SlbRule", id)), NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*slb.DescribeRuleAttributeResponse)
if response.RuleId != id {
return response, WrapErrorf(Error(GetNotFoundMessage("SlbRule", id)), NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, nil
}
func (s *SlbService) DescribeSlbServerGroup(id string) (*slb.DescribeVServerGroupAttributeResponse, error) {
response := &slb.DescribeVServerGroupAttributeResponse{}
request := slb.CreateDescribeVServerGroupAttributeRequest()
request.RegionId = s.client.RegionId
request.VServerGroupId = id
raw, err := s.client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeVServerGroupAttribute(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"The specified VServerGroupId does not exist", "InvalidParameter"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*slb.DescribeVServerGroupAttributeResponse)
if response.VServerGroupId == "" {
return response, WrapErrorf(Error(GetNotFoundMessage("SlbServerGroup", id)), NotFoundMsg, ProviderERROR)
}
return response, err
}
func (s *SlbService) DescribeSlbMasterSlaveServerGroup(id string) (*slb.DescribeMasterSlaveServerGroupAttributeResponse, error) {
response := &slb.DescribeMasterSlaveServerGroupAttributeResponse{}
request := slb.CreateDescribeMasterSlaveServerGroupAttributeRequest()
request.RegionId = s.client.RegionId
request.MasterSlaveServerGroupId = id
raw, err := s.client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeMasterSlaveServerGroupAttribute(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"The specified MasterSlaveGroupId does not exist", "InvalidParameter"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultDebugMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*slb.DescribeMasterSlaveServerGroupAttributeResponse)
if response.MasterSlaveServerGroupId == "" {
return response, WrapErrorf(Error(GetNotFoundMessage("SlbMasterSlaveServerGroup", id)), NotFoundMsg, ProviderERROR)
}
return response, err
}
func (s *SlbService) DescribeSlbBackendServer(id string) (*slb.DescribeLoadBalancerAttributeResponse, error) {
response := &slb.DescribeLoadBalancerAttributeResponse{}
request := slb.CreateDescribeLoadBalancerAttributeRequest()
request.RegionId = s.client.RegionId
request.LoadBalancerId = id
raw, err := s.client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeLoadBalancerAttribute(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidLoadBalancerId.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("SlbBackendServers", id)), NotFoundMsg, AlibabaCloudSdkGoERROR)
} else {
err = WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
return response, err
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*slb.DescribeLoadBalancerAttributeResponse)
if response.LoadBalancerId == "" {
err = WrapErrorf(Error(GetNotFoundMessage("SlbBackendServers", id)), NotFoundMsg, ProviderERROR)
}
return response, err
}
func (s *SlbService) DescribeSlbListener(id string) (listener map[string]interface{}, err error) {
parts, err := ParseSlbListenerId(id)
if err != nil {
return nil, WrapError(err)
}
protocol := parts[1]
request, err := s.BuildSlbCommonRequest()
request.RegionId = s.client.RegionId
if err != nil {
err = WrapError(err)
return
}
request.ApiName = fmt.Sprintf("DescribeLoadBalancer%sListenerAttribute", strings.ToUpper(string(protocol)))
request.QueryParams["LoadBalancerId"] = parts[0]
port, _ := strconv.Atoi(parts[2])
request.QueryParams["ListenerPort"] = string(requests.NewInteger(port))
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.ProcessCommonRequest(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"The specified resource does not exist"}) {
return resource.NonRetryableError(WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR))
} else if IsExpectedErrors(err, SlbIsBusy) {
return resource.RetryableError(WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR))
}
return resource.NonRetryableError(WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR))
}
addDebug(request.GetActionName(), raw, request, request.QueryParams)
response, _ := raw.(*responses.CommonResponse)
if err = json.Unmarshal(response.GetHttpContentBytes(), &listener); err != nil {
return resource.NonRetryableError(WrapError(err))
}
if port, ok := listener["ListenerPort"]; ok && port.(float64) > 0 {
return nil
} else {
return resource.RetryableError(WrapErrorf(Error(GetNotFoundMessage("SlbListener", id)), NotFoundMsg, ProviderERROR))
}
})
return
}
func (s *SlbService) DescribeSlbAcl(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewSlbClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeAccessControlListAttribute"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"AclId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"AclNotExist"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("SLB:Acl", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *SlbService) WaitForSlb(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeSlb(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
} else if strings.ToLower(object.LoadBalancerStatus) == strings.ToLower(string(status)) {
//TODO
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.LoadBalancerStatus, status, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *SlbService) WaitForSlbListener(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeSlbListener(id)
if err != nil && !IsExpectedErrors(err, []string{"InvalidLoadBalancerId.NotFound"}) {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
gotStatus := ""
if value, ok := object["Status"]; ok {
gotStatus = strings.ToLower(value.(string))
}
if gotStatus == strings.ToLower(string(status)) {
//TODO
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, gotStatus, status, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *SlbService) WaitForSlbRule(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeSlbRule(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.RuleId == id && status != Deleted {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, "", id, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *SlbService) WaitForSlbServerGroup(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeSlbServerGroup(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.VServerGroupId == id {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.VServerGroupId, id, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *SlbService) WaitForSlbMasterSlaveServerGroup(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeSlbMasterSlaveServerGroup(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.MasterSlaveServerGroupId == id && status != Deleted {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.MasterSlaveServerGroupId, id, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *SlbService) WaitSlbAttribute(id string, instanceSet *schema.Set, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
RETRY:
object, err := s.DescribeSlb(id)
if err != nil {
if NotFoundError(err) {
return nil
}
return WrapError(err)
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, Null, id, ProviderERROR)
}
servers := object.BackendServers.BackendServer
if len(servers) > 0 {
for _, s := range servers {
if instanceSet.Contains(s.ServerId) {
goto RETRY
}
}
}
return nil
}
func (s *SlbService) slbRemoveAccessControlListEntryPerTime(list []interface{}, id string) error {
request := slb.CreateRemoveAccessControlListEntryRequest()
request.RegionId = s.client.RegionId
request.AclId = id
b, err := json.Marshal(list)
if err != nil {
return WrapError(err)
}
request.AclEntrys = string(b)
raw, err := s.client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.RemoveAccessControlListEntry(request)
})
if err != nil {
if !IsExpectedErrors(err, []string{"AclEntryEmpty"}) {
return WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}
func (s *SlbService) SlbRemoveAccessControlListEntry(list []interface{}, aclId string) error {
num := len(list)
if num <= 0 {
return nil
}
t := (num + max_num_per_time - 1) / max_num_per_time
for i := 0; i < t; i++ {
start := i * max_num_per_time
end := (i + 1) * max_num_per_time
if end > num {
end = num
}
slice := list[start:end]
if err := s.slbRemoveAccessControlListEntryPerTime(slice, aclId); err != nil {
return err
}
}
return nil
}
func (s *SlbService) slbAddAccessControlListEntryPerTime(list []interface{}, id string) error {
request := slb.CreateAddAccessControlListEntryRequest()
request.RegionId = s.client.RegionId
request.AclId = id
b, err := json.Marshal(list)
if err != nil {
return WrapError(err)
}
request.AclEntrys = string(b)
raw, err := s.client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.AddAccessControlListEntry(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}
func (s *SlbService) SlbAddAccessControlListEntry(list []interface{}, aclId string) error {
num := len(list)
if num <= 0 {
return nil
}
t := (num + max_num_per_time - 1) / max_num_per_time
for i := 0; i < t; i++ {
start := i * max_num_per_time
end := (i + 1) * max_num_per_time
if end > num {
end = num
}
slice := list[start:end]
if err := s.slbAddAccessControlListEntryPerTime(slice, aclId); err != nil {
return err
}
}
return nil
}
// Flattens an array of slb.AclEntry into a []map[string]string
func (s *SlbService) FlattenSlbAclEntryMappings(list []slb.AclEntry) []map[string]interface{} {
result := make([]map[string]interface{}, 0, len(list))
for _, i := range list {
l := map[string]interface{}{
"entry": i.AclEntryIP,
"comment": i.AclEntryComment,
}
result = append(result, l)
}
return result
}
// Flattens an array of slb.AclEntry into a []map[string]string
func (s *SlbService) flattenSlbRelatedListenerMappings(list []slb.RelatedListener) []map[string]interface{} {
result := make([]map[string]interface{}, 0, len(list))
for _, i := range list {
l := map[string]interface{}{
"load_balancer_id": i.LoadBalancerId,
"protocol": i.Protocol,
"frontend_port": i.ListenerPort,
"acl_type": i.AclType,
}
result = append(result, l)
}
return result
}
func (s *SlbService) DescribeSlbCACertificate(id string) (*slb.CACertificate, error) {
certificate := &slb.CACertificate{}
request := slb.CreateDescribeCACertificatesRequest()
request.RegionId = s.client.RegionId
request.CACertificateId = id
raw, err := s.client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeCACertificates(request)
})
if err != nil {
return certificate, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*slb.DescribeCACertificatesResponse)
if len(response.CACertificates.CACertificate) < 1 {
return certificate, WrapErrorf(Error(GetNotFoundMessage("SlbCACertificate", id)), NotFoundMsg, ProviderERROR)
}
return &response.CACertificates.CACertificate[0], nil
}
func (s *SlbService) WaitForSlbCACertificate(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeSlbCACertificate(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
} else {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.CACertificateId, id, ProviderERROR)
}
}
return nil
}
func (s *SlbService) DescribeSlbServerCertificate(id string) (*slb.ServerCertificate, error) {
certificate := &slb.ServerCertificate{}
request := slb.CreateDescribeServerCertificatesRequest()
request.RegionId = s.client.RegionId
request.ServerCertificateId = id
raw, err := s.client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeServerCertificates(request)
})
if err != nil {
return certificate, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*slb.DescribeServerCertificatesResponse)
if len(response.ServerCertificates.ServerCertificate) < 1 || response.ServerCertificates.ServerCertificate[0].ServerCertificateId != id {
return certificate, WrapErrorf(Error(GetNotFoundMessage("SlbServerCertificate", id)), NotFoundMsg, ProviderERROR)
}
return &response.ServerCertificates.ServerCertificate[0], nil
}
func (s *SlbService) WaitForSlbServerCertificate(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeSlbServerCertificate(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.ServerCertificateId == id {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.ServerCertificateId, id, ProviderERROR)
}
}
return nil
}
func toSlbTagsString(tags []Tag) string {
slbTags := make([]SlbTag, 0, len(tags))
for _, tag := range tags {
slbTag := SlbTag{
TagKey: tag.Key,
TagValue: tag.Value,
}
slbTags = append(slbTags, slbTag)
}
b, _ := json.Marshal(slbTags)
return string(b)
}
func (s *SlbService) DescribeDomainExtensionAttribute(domainExtensionId string) (*slb.DescribeDomainExtensionAttributeResponse, error) {
response := &slb.DescribeDomainExtensionAttributeResponse{}
request := slb.CreateDescribeDomainExtensionAttributeRequest()
request.DomainExtensionId = domainExtensionId
var raw interface{}
var err error
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithSlbClient(func(slbClient *slb.Client) (interface{}, error) {
return slbClient.DescribeDomainExtensionAttribute(request)
})
if err != nil {
if IsExpectedErrors(err, []string{AliyunGoClientFailure, "ServiceUnavailable", Throttling}) {
time.Sleep(10 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidParameter.DomainExtensionId", "InvalidParameter"}) {
return response, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return response, WrapErrorf(err, DefaultErrorMsg, domainExtensionId, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ = raw.(*slb.DescribeDomainExtensionAttributeResponse)
if response.DomainExtensionId != domainExtensionId {
return response, WrapErrorf(Error(GetNotFoundMessage("SLBDomainExtension", domainExtensionId)), NotFoundMsg, ProviderERROR)
}
return response, nil
}
func (s *SlbService) WaitForSlbDomainExtension(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
_, err := s.DescribeDomainExtensionAttribute(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, Null, string(status), ProviderERROR)
}
}
}
func (s *SlbService) setInstanceTags(d *schema.ResourceData, resourceType TagResourceType) error {
oraw, nraw := d.GetChange("tags")
o := oraw.(map[string]interface{})
n := nraw.(map[string]interface{})
create, remove := s.diffTags(s.tagsFromMap(o), s.tagsFromMap(n))
if len(remove) > 0 {
var tagKey []string
for _, v := range remove {
tagKey = append(tagKey, v.Key)
}
request := slb.CreateUntagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.ResourceType = string(resourceType)
request.TagKey = &tagKey
request.RegionId = s.client.RegionId
wait := incrementalWait(1*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithSlbClient(func(client *slb.Client) (interface{}, error) {
return client.UntagResources(request)
})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
if len(create) > 0 {
request := slb.CreateTagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.Tag = &create
request.ResourceType = string(resourceType)
request.RegionId = s.client.RegionId
wait := incrementalWait(1*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithSlbClient(func(client *slb.Client) (interface{}, error) {
return client.TagResources(request)
})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("tags")
return nil
}
func (s *SlbService) tagsToMap(tags []slb.TagResource) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !s.ignoreTag(t) {
result[t.TagKey] = t.TagValue
}
}
return result
}
func (s *SlbService) ignoreTag(t slb.TagResource) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, t.TagKey)
ok, _ := regexp.MatchString(v, t.TagKey)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific t %s (val: %s), ignoring.\n", t.TagKey, t.TagValue)
return true
}
}
return false
}
func (s *SlbService) diffTags(oldTags, newTags []slb.TagResourcesTag) ([]slb.TagResourcesTag, []slb.TagResourcesTag) {
// First, we're creating everything we have
create := make(map[string]interface{})
for _, t := range newTags {
create[t.Key] = t.Value
}
// Build the list of what to remove
var remove []slb.TagResourcesTag
for _, t := range oldTags {
old, ok := create[t.Key]
if !ok || old != t.Value {
// Delete it!
remove = append(remove, t)
}
}
return s.tagsFromMap(create), remove
}
func (s *SlbService) tagsFromMap(m map[string]interface{}) []slb.TagResourcesTag {
result := make([]slb.TagResourcesTag, 0, len(m))
for k, v := range m {
result = append(result, slb.TagResourcesTag{
Key: k,
Value: v.(string),
})
}
return result
}
func (s *SlbService) DescribeTags(resourceId string, resourceTags map[string]interface{}, resourceType TagResourceType) (tags []slb.TagResource, err error) {
request := slb.CreateListTagResourcesRequest()
request.RegionId = s.client.RegionId
request.ResourceType = string(resourceType)
request.ResourceId = &[]string{resourceId}
if resourceTags != nil && len(resourceTags) > 0 {
var reqTags []slb.ListTagResourcesTag
for key, value := range resourceTags {
reqTags = append(reqTags, slb.ListTagResourcesTag{
Key: key,
Value: value.(string),
})
}
request.Tag = &reqTags
}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithSlbClient(func(Client *slb.Client) (interface{}, error) {
return Client.ListTagResources(request)
})
if err != nil {
if IsExpectedErrors(err, []string{Throttling, "Throttling.User"}) {
time.Sleep(2 * time.Second)
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*slb.ListTagResourcesResponse)
tags = response.TagResources.TagResource
return nil
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, resourceId, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
return
}
func (s *SlbService) ListTagResources(id string, resourceType string) (object interface{}, err error) {
conn, err := s.client.NewSlbClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListTagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": id,
}
tags := make([]interface{}, 0)
var response map[string]interface{}
for {
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{Throttling}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.TagResources.TagResource", response)
if err != nil {
return resource.NonRetryableError(WrapErrorf(err, FailedGetAttributeMsg, id, "$.TagResources.TagResource", response))
}
if v != nil {
tags = append(tags, v.([]interface{})...)
}
return nil
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
if response["NextToken"] == nil {
break
}
request["NextToken"] = response["NextToken"]
}
return tags, nil
}
func (s *SlbService) SetResourceTags(d *schema.ResourceData, resourceType string) error {
if d.HasChange("tags") {
added, removed := parsingTags(d)
conn, err := s.client.NewSlbClient()
if err != nil {
return WrapError(err)
}
removedTagKeys := make([]string, 0)
for _, v := range removed {
if !ignoredTags(v, "") {
removedTagKeys = append(removedTagKeys, v)
}
}
if len(removedTagKeys) > 0 {
action := "UntagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": d.Id(),
}
for i, key := range removedTagKeys {
request[fmt.Sprintf("TagKey.%d", i+1)] = key
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
action := "TagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": d.Id(),
}
count := 1
for key, value := range added {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("tags")
}
return nil
}
func (s *SlbService) DescribeSlbLoadBalancer(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewSlbClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeLoadBalancerAttribute"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"LoadBalancerId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidLoadBalancerId.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("SLB:LoadBalancer", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *SlbService) SlbLoadBalancerStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeSlbLoadBalancer(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["LoadBalancerStatus"]) == failState {
return object, fmt.Sprint(object["LoadBalancerStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["LoadBalancerStatus"])))
}
}
return object, fmt.Sprint(object["LoadBalancerStatus"]), nil
}
}
func (s *SlbService) DescribeSlbCaCertificate(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewSlbClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeCACertificates"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"CACertificateId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.CACertificates.CACertificate", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.CACertificates.CACertificate", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("SLB", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["CACertificateId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("SLB", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *SlbService) DescribeSlbTlsCipherPolicy(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewSlbClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListTLSCipherPolicies"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"TLSCipherPolicyId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-15"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.TLSCipherPolicies", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.TLSCipherPolicies", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("SLB", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["InstanceId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("SLB", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *SlbService) convertAclEntriesToString(v []interface{}) (string, error) {
arrayMaps := make([]interface{}, len(v))
for i, vv := range v {
item := vv.(map[string]interface{})
temp := map[string]interface{}{
"comment": item["comment"],
"entry": item["entry"],
}
arrayMaps[i] = temp
}
maps, err := json.Marshal(arrayMaps)
if err != nil {
return "", WrapError(err)
}
return string(maps), nil
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type SwasOpenService struct {
client *connectivity.AliyunClient
}
func (s *SwasOpenService) DescribeSimpleApplicationServerInstance(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewSwasClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListInstances"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"InstanceIds": "[\"" + id + "\"]",
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InternalError"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("SimpleApplicationServer:Instance", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Instances", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Instances", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("SimpleApplicationServer", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["InstanceId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("SimpleApplicationServer", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *SwasOpenService) SimpleApplicationServerInstanceStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeSimpleApplicationServerInstance(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *SwasOpenService) DescribeSimpleApplicationServerFirewallRule(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewSwasClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListFirewallRules"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"InstanceId": parts[0],
"PageNumber": 1,
"PageSize": 10,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.FirewallRules", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.FirewallRules", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("SimpleApplicationServer", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["RuleId"]) == parts[1] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("SimpleApplicationServer", id)), NotFoundWithResponse, response)
}
return
}
func (s *SwasOpenService) DescribeSimpleApplicationServerSnapshot(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewSwasClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListSnapshots"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"SnapshotIds": fmt.Sprintf(`["%s"]`, id),
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDiskId.NotFound", "InvalidInstanceId.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("SimpleApplicationServer:Snapshot", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Snapshots", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Snapshots", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("SimpleApplicationServer", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["SnapshotId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("SimpleApplicationServer", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *SwasOpenService) SimpleApplicationServerSnapshotStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeSimpleApplicationServerSnapshot(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *SwasOpenService) DescribeSimpleApplicationServerCustomImage(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewSwasClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListImages"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ImageIds": fmt.Sprintf(`["%s"]`, id),
"ImageType": "custom",
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-01"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Images", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Images", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("SimpleApplicationServer", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["ImageId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("SimpleApplicationServer", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
package alicloud
import (
"fmt"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type VodService struct {
client *connectivity.AliyunClient
}
func (s *VodService) DescribeVodDomain(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVodClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeVodDomainDetail"
request := map[string]interface{}{
"DomainName": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-03-21"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidDomain.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.DomainDetail", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.DomainDetail", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *VodService) VodStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeVodDomain(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["DomainStatus"].(string) == failState {
return object, object["DomainStatus"].(string), WrapError(Error(FailedToReachTargetStatus, object["DomainStatus"].(string)))
}
}
return object, object["DomainStatus"].(string), nil
}
}
func (s *VodService) SetResourceTags(d *schema.ResourceData, resourceType string) error {
if d.HasChange("tags") {
added, removed := parsingTags(d)
conn, err := s.client.NewVodClient()
if err != nil {
return WrapError(err)
}
removedTagKeys := make([]string, 0)
for _, v := range removed {
if !ignoredTags(v, "") {
removedTagKeys = append(removedTagKeys, v)
}
}
if len(removedTagKeys) > 0 {
action := "UnTagVodResources"
request := map[string]interface{}{
"ResourceType": resourceType,
"ResourceId.1": d.Id(),
}
for i, key := range removedTagKeys {
request[fmt.Sprintf("TagKey.%d", i+1)] = key
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-03-21"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
action := "TagVodResources"
request := map[string]interface{}{
"ResourceType": resourceType,
"ResourceId.1": d.Id(),
}
count := 1
for key, value := range added {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-03-21"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("tags")
}
return nil
}
package alicloud
import (
"log"
"regexp"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"fmt"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
)
type VpcService struct {
client *connectivity.AliyunClient
}
func (s *VpcService) DescribeEip(id string) (eip vpc.EipAddress, err error) {
request := vpc.CreateDescribeEipAddressesRequest()
request.RegionId = string(s.client.Region)
request.AllocationId = id
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeEipAddresses(request)
})
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*vpc.DescribeEipAddressesResponse)
if len(response.EipAddresses.EipAddress) <= 0 || response.EipAddresses.EipAddress[0].AllocationId != id {
return resource.NonRetryableError(WrapErrorf(Error(GetNotFoundMessage("Eip", id)), NotFoundMsg, ProviderERROR))
}
eip = response.EipAddresses.EipAddress[0]
return nil
})
return
}
func (s *VpcService) DescribeEipAssociation(id string) (object vpc.EipAddress, err error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
object, err = s.DescribeEip(parts[0])
if err != nil {
err = WrapError(err)
return
}
if object.InstanceId != parts[1] {
err = WrapErrorf(Error(GetNotFoundMessage("Eip Association", id)), NotFoundMsg, ProviderERROR)
}
return
}
func (s *VpcService) DescribeNatGateway(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeNatGateways"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"NatGatewayId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidNatGatewayId.NotFound", "InvalidRegionId.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("NatGateway", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.NatGateways.NatGateway", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.NatGateways.NatGateway", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["NatGatewayId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *VpcService) DescribeVpc(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeVpcs"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"VpcId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"Forbidden.VpcNotFound", "InvalidVpcID.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("Vpc", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Vpcs.Vpc", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Vpcs.Vpc", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["VpcId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *VpcService) DescribeVpcWithTeadsl(id string) (object map[string]interface{}, err error) {
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeVpcs"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"VpcId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
invoker := NewInvoker()
err = invoker.Run(func() error {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidVpcID.NotFound", "Forbidden.VpcNotFound"}) {
return WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Vpcs.Vpc", response)
if err != nil {
return WrapErrorf(err, FailedGetAttributeMsg, id, "$.Vpcs.Vpc", response)
}
if len(v.([]interface{})) < 1 || v.([]interface{})[0].(map[string]interface{})["VpcId"].(string) != id {
return WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
object = v.([]interface{})[0].(map[string]interface{})
return nil
})
return
}
func (s *VpcService) ListTagResources(id string, resourceType string) (object interface{}, err error) {
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListTagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": id,
}
tags := make([]interface{}, 0)
var response map[string]interface{}
for {
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsExpectedErrors(err, []string{Throttling}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.TagResources.TagResource", response)
if err != nil {
return resource.NonRetryableError(WrapErrorf(err, FailedGetAttributeMsg, id, "$.TagResources.TagResource", response))
}
if v != nil {
tags = append(tags, v.([]interface{})...)
}
return nil
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
if response["NextToken"] == nil {
break
}
request["NextToken"] = response["NextToken"]
}
return tags, nil
}
func (s *VpcService) VpcStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeVpc(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["Status"].(string) == failState {
return object, object["Status"].(string), WrapError(Error(FailedToReachTargetStatus, object["Status"].(string)))
}
}
return object, object["Status"].(string), nil
}
}
func (s *VpcService) DescribeVSwitch(id string) (v vpc.DescribeVSwitchAttributesResponse, err error) {
request := vpc.CreateDescribeVSwitchAttributesRequest()
request.RegionId = s.client.RegionId
request.VSwitchId = id
invoker := NewInvoker()
err = invoker.Run(func() error {
raw, err := s.client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeVSwitchAttributes(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"InvalidVswitchID.NotFound"}) {
return WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*vpc.DescribeVSwitchAttributesResponse)
if response.VSwitchId != id {
return WrapErrorf(Error(GetNotFoundMessage("vswitch", id)), NotFoundMsg, ProviderERROR)
}
v = *response
return nil
})
return
}
func (s *VpcService) DescribeVSwitchWithTeadsl(id string) (object map[string]interface{}, err error) {
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeVSwitchAttributes"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"VSwitchId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidVswitchID.NotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return nil, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
if v, ok := response["VSwitchId"].(string); ok && v != id {
return nil, WrapErrorf(Error(GetNotFoundMessage("vswitch", id)), NotFoundMsg, ProviderERROR)
}
return response, nil
}
func (s *VpcService) VSwitchStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeVSwitch(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.Status == failState {
return object, object.Status, WrapError(Error(FailedToReachTargetStatus, object.Status))
}
}
return object, object.Status, nil
}
}
func (s *VpcService) DescribeSnatEntry(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeSnatTableEntries"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"SnatEntryId": parts[1],
"SnatTableId": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidSnatEntryId.NotFound", "InvalidSnatTableId.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC:SnatEntry", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.SnatTableEntries.SnatTableEntry", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.SnatTableEntries.SnatTableEntry", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["SnatEntryId"].(string) != parts[1] {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *VpcService) DescribeForwardEntry(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeForwardTableEntries"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ForwardEntryId": parts[1],
"ForwardTableId": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidForwardEntryId.NotFound", "InvalidForwardTableId.NotFound", "InvalidRegionId.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("ForwardEntry", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.ForwardTableEntries.ForwardTableEntry", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ForwardTableEntries.ForwardTableEntry", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["ForwardEntryId"].(string) != parts[1] {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *VpcService) QueryRouteTableById(routeTableId string) (rt vpc.RouteTable, err error) {
request := vpc.CreateDescribeRouteTablesRequest()
request.RegionId = s.client.RegionId
request.RouteTableId = routeTableId
invoker := NewInvoker()
err = invoker.Run(func() error {
raw, err := s.client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeRouteTables(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, routeTableId, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*vpc.DescribeRouteTablesResponse)
if len(response.RouteTables.RouteTable) == 0 ||
response.RouteTables.RouteTable[0].RouteTableId != routeTableId {
return WrapErrorf(Error(GetNotFoundMessage("RouteTable", routeTableId)), NotFoundMsg, ProviderERROR)
}
rt = response.RouteTables.RouteTable[0]
return nil
})
return
}
func (s *VpcService) DescribeRouteEntry(id string) (*vpc.RouteEntry, error) {
v := &vpc.RouteEntry{}
parts, err := ParseResourceId(id, 5)
if err != nil {
return v, WrapError(err)
}
rtId, cidr, nexthop_type, nexthop_id := parts[0], parts[2], parts[3], parts[4]
request := vpc.CreateDescribeRouteTablesRequest()
request.RegionId = s.client.RegionId
request.RouteTableId = rtId
invoker := NewInvoker()
for {
var raw interface{}
if err := invoker.Run(func() error {
response, err := s.client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeRouteTables(request)
})
raw = response
return err
}); err != nil {
return v, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*vpc.DescribeRouteTablesResponse)
if len(response.RouteTables.RouteTable) < 1 {
break
}
for _, table := range response.RouteTables.RouteTable {
for _, entry := range table.RouteEntrys.RouteEntry {
if entry.DestinationCidrBlock == cidr && entry.NextHopType == nexthop_type && entry.InstanceId == nexthop_id {
return &entry, nil
}
}
}
if len(response.RouteTables.RouteTable) < PageSizeLarge {
break
}
if page, err := getNextpageNumber(request.PageNumber); err != nil {
return v, WrapError(err)
} else {
request.PageNumber = page
}
}
return v, WrapErrorf(Error(GetNotFoundMessage("RouteEntry", id)), NotFoundMsg, ProviderERROR)
}
func (s *VpcService) DescribeRouterInterface(id, regionId string) (ri vpc.RouterInterfaceType, err error) {
request := vpc.CreateDescribeRouterInterfacesRequest()
request.RegionId = regionId
values := []string{id}
filter := []vpc.DescribeRouterInterfacesFilter{
{
Key: "RouterInterfaceId",
Value: &values,
},
}
request.Filter = &filter
invoker := NewInvoker()
err = invoker.Run(func() error {
raw, err := s.client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeRouterInterfaces(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*vpc.DescribeRouterInterfacesResponse)
if len(response.RouterInterfaceSet.RouterInterfaceType) <= 0 ||
response.RouterInterfaceSet.RouterInterfaceType[0].RouterInterfaceId != id {
return WrapErrorf(Error(GetNotFoundMessage("RouterInterface", id)), NotFoundMsg, ProviderERROR)
}
ri = response.RouterInterfaceSet.RouterInterfaceType[0]
return nil
})
return
}
func (s *VpcService) DescribeRouterInterfaceConnection(id, regionId string) (ri vpc.RouterInterfaceType, err error) {
ri, err = s.DescribeRouterInterface(id, regionId)
if err != nil {
return ri, WrapError(err)
}
if ri.OppositeInterfaceId == "" || ri.OppositeRouterType == "" ||
ri.OppositeRouterId == "" || ri.OppositeInterfaceOwnerId == "" {
return ri, WrapErrorf(Error(GetNotFoundMessage("RouterInterface", id)), NotFoundMsg, ProviderERROR)
}
return ri, nil
}
func (s *VpcService) DescribeCenInstanceGrant(id string) (rule vpc.CbnGrantRule, err error) {
request := vpc.CreateDescribeGrantRulesToCenRequest()
parts, err := ParseResourceId(id, 3)
if err != nil {
return rule, WrapError(err)
}
cenId := parts[0]
instanceId := parts[1]
instanceType, err := GetCenChildInstanceType(instanceId)
if err != nil {
return rule, WrapError(err)
}
request.RegionId = s.client.RegionId
request.InstanceId = instanceId
request.InstanceType = instanceType
invoker := NewInvoker()
err = invoker.Run(func() error {
raw, err := s.client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeGrantRulesToCen(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*vpc.DescribeGrantRulesToCenResponse)
ruleList := response.CenGrantRules.CbnGrantRule
if len(ruleList) <= 0 {
return WrapErrorf(Error(GetNotFoundMessage("GrantRules", id)), NotFoundMsg, ProviderERROR)
}
for ruleNum := 0; ruleNum <= len(response.CenGrantRules.CbnGrantRule)-1; ruleNum++ {
if ruleList[ruleNum].CenInstanceId == cenId {
rule = ruleList[ruleNum]
return nil
}
}
return WrapErrorf(Error(GetNotFoundMessage("GrantRules", id)), NotFoundMsg, ProviderERROR)
})
return
}
func (s *VpcService) WaitForCenInstanceGrant(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
parts, err := ParseResourceId(id, 3)
if err != nil {
return WrapError(err)
}
instanceId := parts[1]
ownerId := parts[2]
for {
object, err := s.DescribeCenInstanceGrant(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.CenInstanceId == instanceId && fmt.Sprint(object.CenOwnerId) == ownerId && status != Deleted {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.CenInstanceId, instanceId, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *VpcService) DescribeCommonBandwidthPackage(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeCommonBandwidthPackages"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"BandwidthPackageId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidRegionId.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("CommonBandwidthPackage", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.CommonBandwidthPackages.CommonBandwidthPackage", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.CommonBandwidthPackages.CommonBandwidthPackage", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["BandwidthPackageId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *VpcService) DescribeCommonBandwidthPackageAttachment(id string) (object map[string]interface{}, err error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
return object, WrapError(err)
}
bandwidthPackageId, ipInstanceId := parts[0], parts[1]
object, err = s.DescribeCommonBandwidthPackage(bandwidthPackageId)
if err != nil {
return object, WrapError(err)
}
if val, ok := object["PublicIpAddresses"].(map[string]interface{}); ok {
if vs, ok := val["PublicIpAddresse"]; ok {
for _, ipAddresse := range vs.([]interface{}) {
item := ipAddresse.(map[string]interface{})
if fmt.Sprint(item["AllocationId"]) == ipInstanceId {
return object, nil
}
}
}
}
return object, WrapErrorf(Error(GetNotFoundMessage("CommonBandWidthPackageAttachment", id)), NotFoundMsg, ProviderERROR)
}
func (s *VpcService) DescribeRouteTable(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeRouteTableList"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"RouteTableId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
addDebug(action, response, request)
if fmt.Sprintf(`%v`, response["Code"]) != "200" {
err = WrapErrorf(err, ResponseCodeMsg, id, action, response)
return object, err
}
v, err := jsonpath.Get("$.RouterTableList.RouterTableListType", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.RouterTableList.RouterTableListType", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["RouteTableId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *VpcService) DescribeRouteTableAttachment(id string) (v map[string]interface{}, err error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
return v, WrapError(err)
}
invoker := NewInvoker()
routeTableId := parts[0]
vSwitchId := parts[1]
err = invoker.Run(func() error {
object, err := s.DescribeRouteTable(routeTableId)
if err != nil {
return WrapError(err)
}
if val, ok := object["VSwitchIds"].(map[string]interface{}); ok {
if vs, ok := val["VSwitchId"]; ok {
for _, id := range vs.([]interface{}) {
if fmt.Sprint(id) == vSwitchId {
v = object
return nil
}
}
}
}
return WrapErrorf(Error(GetNotFoundMessage("RouteTableAttachment", id)), NotFoundMsg, ProviderERROR)
})
return v, WrapError(err)
}
func (s *VpcService) WaitForVSwitch(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeVSwitch(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.Status == string(status) {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.Status, string(status), ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *VpcService) WaitForRouteEntry(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeRouteEntry(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.Status == string(status) {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.Status, status, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *VpcService) WaitForAllRouteEntriesAvailable(routeTableId string, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
table, err := s.QueryRouteTableById(routeTableId)
if err != nil {
return WrapError(err)
}
success := true
for _, routeEntry := range table.RouteEntrys.RouteEntry {
if routeEntry.Status != string(Available) {
success = false
break
}
}
if success {
break
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, routeTableId, GetFunc(1), timeout, Available, Null, ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *VpcService) WaitForRouterInterface(id, regionId string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeRouterInterface(id, regionId)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.Status == string(status) {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.Status, string(status), ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *VpcService) WaitForRouterInterfaceConnection(id, regionId string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeRouterInterfaceConnection(id, regionId)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.Status == string(status) {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.Status, string(status), ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *VpcService) WaitForEip(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeEip(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.Status == string(status) {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.Status, string(status), ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *VpcService) WaitForEipAssociation(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeEipAssociation(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.Status == string(status) {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.Status, string(status), ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *VpcService) DeactivateRouterInterface(interfaceId string) error {
request := vpc.CreateDeactivateRouterInterfaceRequest()
request.RegionId = s.client.RegionId
request.RouterInterfaceId = interfaceId
raw, err := s.client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DeactivateRouterInterface(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "RouterInterface", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}
func (s *VpcService) ActivateRouterInterface(interfaceId string) error {
request := vpc.CreateActivateRouterInterfaceRequest()
request.RegionId = s.client.RegionId
request.RouterInterfaceId = interfaceId
raw, err := s.client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.ActivateRouterInterface(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "RouterInterface", request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}
func (s *VpcService) WaitForCommonBandwidthPackageAttachment(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeCommonBandwidthPackageAttachment(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if fmt.Sprint(object["Status"]) == string(status) {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, fmt.Sprint(object["Status"]), string(status), ProviderERROR)
}
}
}
// Flattens an array of vpc.public_ip_addresses into a []map[string]string
func (s *VpcService) FlattenPublicIpAddressesMappings(list []vpc.PublicIpAddresse) []map[string]interface{} {
result := make([]map[string]interface{}, 0, len(list))
for _, i := range list {
l := map[string]interface{}{
"ip_address": i.IpAddress,
"allocation_id": i.AllocationId,
}
result = append(result, l)
}
return result
}
func (s *VpcService) WaitForRouteTableAttachment(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeRouteTableAttachment(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if fmt.Sprint(object["Status"]) == string(status) {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, fmt.Sprint(object["Status"]), string(status), ProviderERROR)
}
time.Sleep(3 * time.Second)
}
}
func (s *VpcService) DescribeNetworkAcl(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeNetworkAclAttributes"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"NetworkAclId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidNetworkAcl.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC:NetworkAcl", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.NetworkAclAttribute", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.NetworkAclAttribute", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *VpcService) DescribeNetworkAclAttachment(id string, resource []vpc.Resource) (err error) {
invoker := NewInvoker()
return invoker.Run(func() error {
object, err := s.DescribeNetworkAcl(id)
if err != nil {
return WrapError(err)
}
resources, _ := object["Resources"].(map[string]interface{})["Resource"].([]interface{})
if len(resources) < 1 {
return WrapErrorf(Error(GetNotFoundMessage("Network Acl Attachment", id)), NotFoundMsg, ProviderERROR)
}
success := true
for _, source := range resources {
success = false
for _, res := range resource {
item := source.(map[string]interface{})
if fmt.Sprint(item["ResourceId"]) == res.ResourceId {
success = true
}
}
if success == false {
return WrapErrorf(Error(GetNotFoundMessage("Network Acl Attachment", id)), NotFoundMsg, ProviderERROR)
}
}
return nil
})
}
func (s *VpcService) WaitForNetworkAcl(networkAclId string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeNetworkAcl(networkAclId)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
success := true
resources, _ := object["Resources"].(map[string]interface{})["Resource"].([]interface{})
// Check Acl's binding resources
for _, res := range resources {
item := res.(map[string]interface{})
if fmt.Sprint(item["Status"]) != string(BINDED) {
success = false
}
}
if fmt.Sprint(object["Status"]) == string(status) && success == true {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, networkAclId, GetFunc(1), timeout, fmt.Sprint(object["Status"]), string(status), ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *VpcService) WaitForNetworkAclAttachment(id string, resource []vpc.Resource, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
err := s.DescribeNetworkAclAttachment(id, resource)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
object, err := s.DescribeNetworkAcl(id)
success := true
resources, _ := object["Resources"].(map[string]interface{})["Resource"].([]interface{})
// Check Acl's binding resources
for _, res := range resources {
item := res.(map[string]interface{})
if fmt.Sprint(item["Status"]) != string(BINDED) {
success = false
}
}
if fmt.Sprint(object["Status"]) == string(status) && success == true {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, fmt.Sprint(object["Status"]), string(status), ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *VpcService) DescribeTags(resourceId string, resourceTags map[string]interface{}, resourceType TagResourceType) (tags []vpc.TagResource, err error) {
request := vpc.CreateListTagResourcesRequest()
request.RegionId = s.client.RegionId
request.ResourceType = string(resourceType)
request.ResourceId = &[]string{resourceId}
if resourceTags != nil && len(resourceTags) > 0 {
var reqTags []vpc.ListTagResourcesTag
for key, value := range resourceTags {
reqTags = append(reqTags, vpc.ListTagResourcesTag{
Key: key,
Value: value.(string),
})
}
request.Tag = &reqTags
}
wait := incrementalWait(3*time.Second, 5*time.Second)
var raw interface{}
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
raw, err = s.client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.ListTagResources(request)
})
if err != nil {
if IsExpectedErrors(err, []string{Throttling}) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, resourceId, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
response, _ := raw.(*vpc.ListTagResourcesResponse)
return response.TagResources.TagResource, nil
}
func (s *VpcService) setInstanceTags(d *schema.ResourceData, resourceType TagResourceType) error {
if d.HasChange("tags") {
added, removed := parsingTags(d)
conn, err := s.client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if len(removed) > 0 {
action := "UnTagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceId.1": d.Id(),
"ResourceType": string(resourceType),
}
for i, key := range removed {
request[fmt.Sprintf("TagKey.%d", i+1)] = key
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
action := "TagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceId.1": d.Id(),
"ResourceType": string(resourceType),
}
count := 1
for key, value := range added {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value ", count)] = value
count++
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("tags")
}
return nil
}
func (s *VpcService) tagsToMap(tags []vpc.TagResource) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !s.ignoreTag(t) {
result[t.TagKey] = t.TagValue
}
}
return result
}
func (s *VpcService) ignoreTag(t vpc.TagResource) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, t.TagKey)
ok, _ := regexp.MatchString(v, t.TagKey)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific t %s (val: %s), ignoring.\n", t.TagKey, t.TagValue)
return true
}
}
return false
}
func (s *VpcService) SetInstanceSecondaryCidrBlocks(d *schema.ResourceData) error {
if d.HasChange("secondary_cidr_blocks") {
oraw, nraw := d.GetChange("secondary_cidr_blocks")
removed := oraw.([]interface{})
added := nraw.([]interface{})
conn, err := s.client.NewVpcClient()
if err != nil {
return WrapError(err)
}
if len(removed) > 0 {
action := "UnassociateVpcCidrBlock"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"VpcId": d.Id(),
}
for _, item := range removed {
request["SecondaryCidrBlock"] = item
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
}
}
if len(added) > 0 {
action := "AssociateVpcCidrBlock"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"VpcId": d.Id(),
}
for _, item := range added {
request["SecondaryCidrBlock"] = item
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
}
}
d.SetPartial("secondary_cidr_blocks")
}
return nil
}
func (s *VpcService) DescribeNatGatewayTransform(id string) ([]interface{}, error) {
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetNatGatewayConvertStatus"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"NatGatewayId": id,
}
request["ClientToken"] = buildClientToken("GetNatGatewayConvertStatus")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err1 := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err1 != nil {
if IsExpectedErrors(err1, []string{"InvalidVpcID.NotFound", "Forbidden.VpcNotFound"}) {
return nil, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return nil, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
addDebug(action, response, request)
ob, err2 := jsonpath.Get("$.ConvertSteps", response)
if err2 != nil {
return nil, WrapErrorf(err2, FailedGetAttributeMsg, id, "$.ConvertSteps", response)
}
natType, err3 := jsonpath.Get("$.DstNatType", response)
if err3 != nil {
return nil, WrapErrorf(err3, FailedGetAttributeMsg, id, "$.DstNatType", response)
}
object := ob.([]interface{})
if len(object) < 1 || natType.(string) != "Enhanced" {
return nil, WrapErrorf(Error(GetNotFoundMessage("NAT", id)), NotFoundWithResponse, response)
}
return object, nil
}
func (s *VpcService) WaitForNatGatewayTransform(id string, timeout int64) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeNatGatewayTransform(id)
if err != nil {
if NotFoundError(err) {
return err
}
if IsExpectedErrors(err, []string{"OperationFailed.NatGwRouteInMiddleStatusError"}) {
return nil
}
return err
}
isOk := false
for _, v := range object {
val := v.(map[string]interface{})
if val["StepName"].(string) == "end_success" && val["StepStatus"].(string) == "successful" {
isOk = true
break
}
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, "", "", ProviderERROR)
}
if isOk {
break
}
time.Sleep(DefaultIntervalShort * time.Second)
}
return nil
}
func (s *VpcService) DescribeRouteTableList(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeRouteTableList"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"VpcId": id,
"PageSize": PageSizeLarge,
"PageNumber": 1,
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err := resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "200" {
err = fmt.Errorf("DescribeRouteTableList failed, response: %v ", response)
return object, err
}
v, err := jsonpath.Get("$.RouterTableList.RouterTableListType", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.RouterTableList.RouterTableListType", response)
}
result, _ := v.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if item["RouteTableType"] == "System" {
object = item
return object, nil
}
}
if len(result) < PageSizeLarge {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
func (s *VpcService) SetResourceTags(d *schema.ResourceData, resourceType string) error {
if d.HasChange("tags") {
added, removed := parsingTags(d)
conn, err := s.client.NewVpcClient()
if err != nil {
return WrapError(err)
}
removedTagKeys := make([]string, 0)
for _, v := range removed {
if !ignoredTags(v, "") {
removedTagKeys = append(removedTagKeys, v)
}
}
if len(removedTagKeys) > 0 {
action := "UnTagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": d.Id(),
}
for i, key := range removedTagKeys {
request[fmt.Sprintf("TagKey.%d", i+1)] = key
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
if len(added) > 0 {
action := "TagResources"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"ResourceType": resourceType,
"ResourceId.1": d.Id(),
}
count := 1
for key, value := range added {
request[fmt.Sprintf("Tag.%d.Key", count)] = key
request[fmt.Sprintf("Tag.%d.Value", count)] = value
count++
}
wait := incrementalWait(2*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
}
d.SetPartial("tags")
}
return nil
}
func (s *VpcService) DescribeVswitch(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeVSwitchAttributes"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"VSwitchId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidVSwitchId.NotFound", "InvalidVswitchID.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("Vswitch", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
if fmt.Sprint(object["VSwitchId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("vswitch", id)), NotFoundMsg, ProviderERROR)
}
return object, nil
}
func (s *VpcService) VswitchStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeVswitch(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["Status"].(string) == failState {
return object, object["Status"].(string), WrapError(Error(FailedToReachTargetStatus, object["Status"].(string)))
}
}
return object, object["Status"].(string), nil
}
}
func (s *VpcService) SnatEntryStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeSnatEntry(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *VpcService) ForwardEntryStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeForwardEntry(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["Status"].(string) == failState {
return object, object["Status"].(string), WrapError(Error(FailedToReachTargetStatus, object["Status"].(string)))
}
}
return object, object["Status"].(string), nil
}
}
func (s *VpcService) RouteTableStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeRouteTable(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["Status"].(string) == failState {
return object, object["Status"].(string), WrapError(Error(FailedToReachTargetStatus, object["Status"].(string)))
}
}
return object, object["Status"].(string), nil
}
}
func (s *VpcService) CommonBandwidthPackageStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeCommonBandwidthPackage(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["Status"].(string) == failState {
return object, object["Status"].(string), WrapError(Error(FailedToReachTargetStatus, object["Status"].(string)))
}
}
return object, object["Status"].(string), nil
}
}
func (s *VpcService) DescribeHavip(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeHaVips"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"PageNumber": 1,
"PageSize": 20,
}
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidFilterKey.ValueNotSupported", "InvalidHaVipId.NotFound", "InvalidRegionId.NotFound"}) {
err = WrapErrorf(Error(GetNotFoundMessage("Havip", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.HaVips.HaVip", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.HaVips.HaVip", response)
}
result, _ := v.([]interface{})
if len(result) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
for _, v := range result {
if v.(map[string]interface{})["HaVipId"].(string) == id {
return v.(map[string]interface{}), nil
}
}
if len(result) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
func (s *VpcService) HavipStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeHavip(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["Status"].(string) == failState {
return object, object["Status"].(string), WrapError(Error(FailedToReachTargetStatus, object["Status"].(string)))
}
}
return object, object["Status"].(string), nil
}
}
func (s *VpcService) NatGatewayStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeNatGateway(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["Status"].(string) == failState {
return object, object["Status"].(string), WrapError(Error(FailedToReachTargetStatus, object["Status"].(string)))
}
}
return object, object["Status"].(string), nil
}
}
func (s *VpcService) DescribeVpcFlowLog(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeFlowLogs"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"FlowLogId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.FlowLogs.FlowLog", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.FlowLogs.FlowLog", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["FlowLogId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *VpcService) VpcFlowLogStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeVpcFlowLog(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object["Status"].(string) == failState {
return object, object["Status"].(string), WrapError(Error(FailedToReachTargetStatus, object["Status"].(string)))
}
}
return object, object["Status"].(string), nil
}
}
func (s *VpcService) NetworkAclStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeNetworkAcl(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *VpcService) DeleteAclResources(id string) (object map[string]interface{}, err error) {
acl, err := s.DescribeNetworkAcl(id)
if err != nil {
return object, WrapError(err)
}
deleteResources := make([]map[string]interface{}, 0)
res, err := jsonpath.Get("$.Resources.Resource", acl)
if err != nil {
return object, WrapError(err)
}
resources, _ := res.([]interface{})
if resources != nil && len(resources) < 1 {
return object, nil
}
for _, val := range resources {
item, _ := val.(map[string]interface{})
deleteResources = append(deleteResources, map[string]interface{}{
"ResourceId": item["ResourceId"],
"ResourceType": item["ResourceType"],
})
}
var response map[string]interface{}
request := map[string]interface{}{
"NetworkAclId": id,
"Resource": deleteResources,
"RegionId": s.client.RegionId,
}
action := "UnassociateNetworkAcl"
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
request["ClientToken"] = buildClientToken("UnassociateNetworkAcl")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(10*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return response, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
stateConf := BuildStateConf([]string{}, []string{"Available"}, 10*time.Minute, 5*time.Second, s.NetworkAclStateRefreshFunc(id, []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return response, WrapErrorf(err, IdMsg, id)
}
return object, nil
}
func (s *VpcService) DescribeEipAddress(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeEipAddresses"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"AllocationId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.EipAddresses.EipAddress", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.EipAddresses.EipAddress", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("EIP", id)), NotFoundWithResponse, response)
} else {
if v.([]interface{})[0].(map[string]interface{})["AllocationId"].(string) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("EIP", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *VpcService) EipAddressStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeEipAddress(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *VpcService) DescribeExpressConnectPhysicalConnection(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribePhysicalConnections"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
}
filterMapList := make([]map[string]interface{}, 0)
filterMapList = append(filterMapList, map[string]interface{}{
"Key": "PhysicalConnectionId",
"Value": []string{id},
})
request["Filter"] = filterMapList
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.PhysicalConnectionSet.PhysicalConnectionType", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.PhysicalConnectionSet.PhysicalConnectionType", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ExpressConnect", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["PhysicalConnectionId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("ExpressConnect", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *VpcService) ExpressConnectPhysicalConnectionStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeExpressConnectPhysicalConnection(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *VpcService) DescribeExpressConnectVirtualBorderRouter(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeVirtualBorderRouters"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"PageNumber": 1,
"PageSize": 50,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.VirtualBorderRouterSet.VirtualBorderRouterType", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.VirtualBorderRouterSet.VirtualBorderRouterType", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("ExpressConnect", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["VbrId"]) == id {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("ExpressConnect", id)), NotFoundWithResponse, response)
}
return
}
func (s *VpcService) ExpressConnectVirtualBorderRouterStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeExpressConnectVirtualBorderRouter(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *VpcService) DescribeVpcDhcpOptionsSet(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetDhcpOptionsSet"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"DhcpOptionsSetId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"InvalidRegionId.NotFound"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC:DhcpOptionsSet", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
if _, ok := object["DhcpOptionsSetId"]; !ok {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC:DhcpOptionsSet", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, nil
}
func (s *VpcService) VpcDhcpOptionsSetStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeVpcDhcpOptionsSet(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *VpcService) DescribeVpcDhcpOptionsSetAttachment(id string) (object map[string]interface{}, err error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
return object, WrapError(err)
}
object, err = s.DescribeVpcDhcpOptionsSet(parts[1])
if err != nil {
return object, WrapError(err)
}
return object, nil
}
func (s *VpcService) DescribeVpcDhcpOptionsSetAttachmentStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
parts, err := ParseResourceId(id, 2)
if err != nil {
return nil, "", WrapError(err)
}
object, err := s.DescribeVpcDhcpOptionsSetAttachment(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
status := ""
if associateVpcsList, ok := object["AssociateVpcs"]; ok {
for _, associateVpcsListItem := range associateVpcsList.([]interface{}) {
if associateVpcsListItem != nil {
associateVpcsListItemMap, ok := associateVpcsListItem.(map[string]interface{})
if ok && associateVpcsListItemMap["VpcId"] == parts[0] {
status = associateVpcsListItemMap["AssociateStatus"].(string)
break
}
}
}
}
for _, failState := range failStates {
if status == failState {
return object, fmt.Sprint(object["AssociateStatus"]), WrapError(Error(FailedToReachTargetStatus, status))
}
}
return object, status, nil
}
}
func (s *VpcService) DescribeVpcNatIpCidr(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListNatIpCidrs"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"NatGatewayId": parts[0],
"NatIpCidr": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
request["ClientToken"] = buildClientToken("ListNatIpCidrs")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.NatIpCidrs", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.NatIpCidrs", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["NatIpCidr"]) != parts[1] {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *VpcService) DescribeVpcNatIp(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
parts, err := ParseResourceId(id, 2)
if err != nil {
return nil, WrapError(err)
}
action := "ListNatIps"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"NatGatewayId": parts[0],
"NatIpIds": []string{parts[1]},
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
request["ClientToken"] = buildClientToken("ListNatIps")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.NatIps", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.NatIps", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["NatIpId"]) != parts[1] {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *VpcService) VpcNatIpStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeVpcNatIp(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["NatIpStatus"]) == failState {
return object, fmt.Sprint(object["NatIpStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["NatIpStatus"])))
}
}
return object, fmt.Sprint(object["NatIpStatus"]), nil
}
}
func (s *VpcService) DescribeVpcTrafficMirrorFilter(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListTrafficMirrorFilters"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"TrafficMirrorFilterIds": []string{id},
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.TrafficMirrorFilters", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.TrafficMirrorFilters", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["TrafficMirrorFilterId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *VpcService) VpcTrafficMirrorFilterStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeVpcTrafficMirrorFilter(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["TrafficMirrorFilterStatus"]) == failState {
return object, fmt.Sprint(object["TrafficMirrorFilterStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["TrafficMirrorFilterStatus"])))
}
}
return object, fmt.Sprint(object["TrafficMirrorFilterStatus"]), nil
}
}
func (s *VpcService) DescribeVpcTrafficMirrorFilterEgressRule(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListTrafficMirrorFilters"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"MaxResults": 10,
"TrafficMirrorFilterIds": []string{parts[0]},
}
idExist := false
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.TrafficMirrorFilters", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.TrafficMirrorFilters", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
EgressRules := v.(map[string]interface{})["EgressRules"]
if EgressRulesMap, ok := EgressRules.([]interface{}); ok {
for _, v := range EgressRulesMap {
if fmt.Sprint(v.(map[string]interface{})["TrafficMirrorFilterRuleId"]) == parts[1] {
idExist = true
return v.(map[string]interface{}), nil
}
}
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
return
}
func (s *VpcService) VpcTrafficMirrorFilterEgressRuleStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeVpcTrafficMirrorFilterEgressRule(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["TrafficMirrorFilterRuleStatus"]) == failState {
return object, fmt.Sprint(object["TrafficMirrorFilterRuleStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["TrafficMirrorFilterRuleStatus"])))
}
}
return object, fmt.Sprint(object["TrafficMirrorFilterRuleStatus"]), nil
}
}
func (s *VpcService) DescribeVpcTrafficMirrorFilterIngressRule(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListTrafficMirrorFilters"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"MaxResults": 10,
"TrafficMirrorFilterIds": []string{parts[0]},
}
idExist := false
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.TrafficMirrorFilters", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.TrafficMirrorFilters", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
EgressRules := v.(map[string]interface{})["IngressRules"]
if EgressRulesMap, ok := EgressRules.([]interface{}); ok {
for _, v := range EgressRulesMap {
if fmt.Sprint(v.(map[string]interface{})["TrafficMirrorFilterRuleId"]) == parts[1] {
idExist = true
return v.(map[string]interface{}), nil
}
}
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
return
}
func (s *VpcService) VpcTrafficMirrorFilterIngressRuleStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeVpcTrafficMirrorFilterIngressRule(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["TrafficMirrorFilterRuleStatus"]) == failState {
return object, fmt.Sprint(object["TrafficMirrorFilterRuleStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["TrafficMirrorFilterRuleStatus"])))
}
}
return object, fmt.Sprint(object["TrafficMirrorFilterRuleStatus"]), nil
}
}
func (s *VpcService) DescribeVpcTrafficMirrorSession(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListTrafficMirrorSessions"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"TrafficMirrorSessionIds": []string{id},
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.TrafficMirrorSessions", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.TrafficMirrorSessions", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["TrafficMirrorSessionId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *VpcService) VpcTrafficMirrorSessionStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeVpcTrafficMirrorSession(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["TrafficMirrorSessionStatus"]) == failState {
return object, fmt.Sprint(object["TrafficMirrorSessionStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["TrafficMirrorSessionStatus"])))
}
}
return object, fmt.Sprint(object["TrafficMirrorSessionStatus"]), nil
}
}
func (s *VpcService) DescribeVpcIpv6Gateway(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeIpv6GatewayAttribute"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"Ipv6GatewayId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
if Ipv6GatewayId, ok := object["Ipv6GatewayId"]; !ok || fmt.Sprint(Ipv6GatewayId) == "" {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
return object, nil
}
func (s *VpcService) VpcIpv6GatewayStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeVpcIpv6Gateway(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *VpcService) DescribeVpcIpv6EgressRule(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
action := "DescribeIpv6EgressOnlyRules"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"PageSize": PageSizeLarge,
"PageNumber": 1,
"Ipv6GatewayId": parts[0],
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Ipv6EgressOnlyRules.Ipv6EgressOnlyRule", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Ipv6EgressOnlyRules.Ipv6EgressOnlyRule", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["Ipv6EgressOnlyRuleId"]) == parts[1] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
return
}
func (s *VpcService) VpcIpv6EgressRuleStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeVpcIpv6EgressRule(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *VpcService) DescribeVpcIpv6InternetBandwidth(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeIpv6Addresses"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"Ipv6InternetBandwidthId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Ipv6Addresses.Ipv6Address", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Ipv6Addresses.Ipv6Address", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["Ipv6InternetBandwidth"].(map[string]interface{})["Ipv6InternetBandwidthId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *VpcService) DescribeVpcBgpGroup(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeBgpGroups"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"BgpGroupId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.BgpGroups.BgpGroup", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.BgpGroups.BgpGroup", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["BgpGroupId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *VpcService) VpcBgpGroupStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeVpcBgpGroup(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *VpcService) DescribeVpcVbrHa(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeVbrHa"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"VbrHaId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
request["ClientToken"] = buildClientToken("DescribeVbrHa")
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
if vbrHaId, ok := object["VbrHaId"]; !ok || fmt.Sprint(vbrHaId) == "" {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
return object, nil
}
func (s *VpcService) VpcVbrHaStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeVpcVbrHa(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *VpcService) DescribeVpcBgpPeer(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeBgpPeers"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"BgpPeerId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.BgpPeers.BgpPeer", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.BgpPeers.BgpPeer", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
} else {
if fmt.Sprint(v.([]interface{})[0].(map[string]interface{})["BgpPeerId"]) != id {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
}
object = v.([]interface{})[0].(map[string]interface{})
return object, nil
}
func (s *VpcService) VpcBgpPeerStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeVpcBgpPeer(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
func (s *VpcService) DescribeVpcBgpNetwork(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVpcClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeBgpNetworks"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"RouterId": parts[0],
"PageNumber": 1,
"PageSize": PageSizeMedium,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.BgpNetworks.BgpNetwork", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.BgpNetworks.BgpNetwork", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["DstCidrBlock"]) == parts[1] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("VPC", id)), NotFoundWithResponse, response)
}
return
}
func (s *VpcService) VpcBgpNetworkStateRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeVpcBgpNetwork(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil as if we didn't find anything.
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["Status"]) == failState {
return object, fmt.Sprint(object["Status"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["Status"])))
}
}
return object, fmt.Sprint(object["Status"]), nil
}
}
package alicloud
import (
"time"
"strings"
"encoding/json"
"fmt"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
)
type VpnGatewayService struct {
client *connectivity.AliyunClient
}
func (s *VpnGatewayService) DescribeVpnGateway(id string) (v vpc.DescribeVpnGatewayResponse, err error) {
request := vpc.CreateDescribeVpnGatewayRequest()
request.RegionId = s.client.RegionId
request.VpnGatewayId = id
raw, err := s.client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeVpnGateway(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"Forbidden", "InvalidVpnGatewayInstanceId.NotFound"}) {
return v, WrapErrorf(Error(GetNotFoundMessage("VpnGateway", id)), NotFoundMsg, ProviderERROR)
}
return v, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*vpc.DescribeVpnGatewayResponse)
if response.VpnGatewayId != id {
return v, WrapErrorf(Error(GetNotFoundMessage("VpnGateway", id)), NotFoundMsg, ProviderERROR)
}
return *response, nil
}
func (s *VpnGatewayService) DescribeVpnCustomerGateway(id string) (v vpc.DescribeCustomerGatewayResponse, err error) {
request := vpc.CreateDescribeCustomerGatewayRequest()
request.RegionId = s.client.RegionId
request.CustomerGatewayId = id
raw, err := s.client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeCustomerGateway(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"Forbidden", "InvalidCustomerGatewayInstanceId.NotFound"}) {
return v, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return v, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*vpc.DescribeCustomerGatewayResponse)
if response.CustomerGatewayId != id {
return v, WrapErrorf(Error(GetNotFoundMessage("VpnCustomerGateway", id)), NotFoundMsg, ProviderERROR)
}
return *response, nil
}
func (s *VpnGatewayService) DescribeVpnConnection(id string) (v vpc.DescribeVpnConnectionResponse, err error) {
request := vpc.CreateDescribeVpnConnectionRequest()
request.RegionId = s.client.RegionId
request.VpnConnectionId = id
raw, err := s.client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeVpnConnection(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"Forbidden", "InvalidVpnConnectionInstanceId.NotFound"}) {
return v, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return v, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*vpc.DescribeVpnConnectionResponse)
if response.VpnConnectionId != id {
return v, WrapErrorf(Error(GetNotFoundMessage("VpnConnection", id)), NotFoundMsg, ProviderERROR)
}
return *response, nil
}
func (s *VpnGatewayService) DescribeSslVpnServer(id string) (v vpc.SslVpnServer, err error) {
request := vpc.CreateDescribeSslVpnServersRequest()
request.RegionId = s.client.RegionId
request.SslVpnServerId = id
raw, err := s.client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeSslVpnServers(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"Forbidden", "InvalidSslVpnServerId.NotFound"}) {
return v, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return v, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*vpc.DescribeSslVpnServersResponse)
if len(response.SslVpnServers.SslVpnServer) == 0 || response.SslVpnServers.SslVpnServer[0].SslVpnServerId != id {
return v, WrapErrorf(Error(GetNotFoundMessage("SslVpnGateway", id)), NotFoundMsg, ProviderERROR)
}
return response.SslVpnServers.SslVpnServer[0], nil
}
func (s *VpnGatewayService) DescribeSslVpnClientCert(id string) (v vpc.DescribeSslVpnClientCertResponse, err error) {
request := vpc.CreateDescribeSslVpnClientCertRequest()
request.RegionId = s.client.RegionId
request.SslVpnClientCertId = id
raw, err := s.client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeSslVpnClientCert(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"Forbidden", "InvalidSslVpnClientCertId.NotFound"}) {
return v, WrapErrorf(err, NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return v, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ := raw.(*vpc.DescribeSslVpnClientCertResponse)
if response.SslVpnClientCertId != id {
return v, WrapErrorf(Error(GetNotFoundMessage("SslVpnClientCert", id)), NotFoundMsg, ProviderERROR)
}
return *response, nil
}
func (s *VpnGatewayService) DescribeVpnRouteEntry(id string) (v vpc.VpnRouteEntry, err error) {
request := vpc.CreateDescribeVpnRouteEntriesRequest()
parts, err := ParseResourceId(id, 3)
if err != nil {
return v, WrapError(err)
}
gatewayId := parts[0]
request.VpnGatewayId = gatewayId
raw, err := s.client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
return vpcClient.DescribeVpnRouteEntries(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"Forbidden", "InvalidVpnGatewayInstanceId.NotFound"}) {
return v, WrapErrorf(Error(GetNotFoundMessage("VpnRouterEntry", id)), NotFoundMsg, AlibabaCloudSdkGoERROR)
}
return v, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw)
response, _ := raw.(*vpc.DescribeVpnRouteEntriesResponse)
for _, routeEntry := range response.VpnRouteEntries.VpnRouteEntry {
if id == gatewayId+":"+routeEntry.NextHop+":"+routeEntry.RouteDest {
return routeEntry, nil
}
}
return v, WrapErrorf(Error(GetNotFoundMessage("VpnRouterEntry", id)), NotFoundMsg, ProviderERROR)
}
func (s *VpnGatewayService) WaitForVpnGateway(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeVpnGateway(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if strings.EqualFold(object.Status, string(status)) {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.Status, string(status), ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *VpnGatewayService) WaitForVpnConnection(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeVpnConnection(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if status != Deleted && object.VpnConnectionId == id {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, Null, string(status), ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *VpnGatewayService) WaitForVpnCustomerGateway(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeVpnCustomerGateway(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.CustomerGatewayId == id && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, Null, string(status), ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *VpnGatewayService) WaitForSslVpnServer(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeSslVpnServer(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.SslVpnServerId == id && status != Deleted {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, Null, string(status), ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *VpnGatewayService) WaitForSslVpnClientCert(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeSslVpnClientCert(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if object.Status == string(status) {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, object.Status, string(status), ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *VpnGatewayService) WaitForVpnRouteEntry(id string, status Status, timeout int) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
object, err := s.DescribeVpnRouteEntry(id)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
parts, err := ParseResourceId(id, 3)
if err != nil {
return WrapError(err)
}
if object.NextHop == parts[1] && object.RouteDest == parts[2] && string(status) != string(Deleted) {
return nil
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, id, GetFunc(1), timeout, Null, string(status), ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *VpnGatewayService) ParseIkeConfig(ike vpc.IkeConfig) (ikeConfigs []map[string]interface{}) {
item := map[string]interface{}{
"ike_auth_alg": ike.IkeAuthAlg,
"ike_enc_alg": ike.IkeEncAlg,
"ike_lifetime": ike.IkeLifetime,
"ike_local_id": ike.LocalId,
"ike_mode": ike.IkeMode,
"ike_pfs": ike.IkePfs,
"ike_remote_id": ike.RemoteId,
"ike_version": ike.IkeVersion,
"psk": ike.Psk,
}
ikeConfigs = append(ikeConfigs, item)
return
}
func (s *VpnGatewayService) ParseIpsecConfig(ipsec vpc.IpsecConfig) (ipsecConfigs []map[string]interface{}) {
item := map[string]interface{}{
"ipsec_auth_alg": ipsec.IpsecAuthAlg,
"ipsec_enc_alg": ipsec.IpsecEncAlg,
"ipsec_lifetime": ipsec.IpsecLifetime,
"ipsec_pfs": ipsec.IpsecPfs,
}
ipsecConfigs = append(ipsecConfigs, item)
return
}
func (s *VpnGatewayService) AssembleIkeConfig(ikeCfgParam []interface{}) (string, error) {
var ikeCfg IkeConfig
v := ikeCfgParam[0]
item := v.(map[string]interface{})
ikeCfg = IkeConfig{
IkeAuthAlg: item["ike_auth_alg"].(string),
IkeEncAlg: item["ike_enc_alg"].(string),
IkeLifetime: item["ike_lifetime"].(int),
LocalId: item["ike_local_id"].(string),
IkeMode: item["ike_mode"].(string),
IkePfs: item["ike_pfs"].(string),
RemoteId: item["ike_remote_id"].(string),
IkeVersion: item["ike_version"].(string),
Psk: item["psk"].(string),
}
data, err := json.Marshal(ikeCfg)
if err != nil {
return "", WrapError(err)
}
return string(data), nil
}
func (s *VpnGatewayService) AssembleIpsecConfig(ipsecCfgParam []interface{}) (string, error) {
var ipsecCfg IpsecConfig
v := ipsecCfgParam[0]
item := v.(map[string]interface{})
ipsecCfg = IpsecConfig{
IpsecAuthAlg: item["ipsec_auth_alg"].(string),
IpsecEncAlg: item["ipsec_enc_alg"].(string),
IpsecLifetime: item["ipsec_lifetime"].(int),
IpsecPfs: item["ipsec_pfs"].(string),
}
data, err := json.Marshal(ipsecCfg)
if err != nil {
return "", WrapError(err)
}
return string(data), nil
}
func (s *VpnGatewayService) AssembleNetworkSubnetToString(list []interface{}) string {
if len(list) < 1 {
return ""
}
var items []string
for _, id := range list {
items = append(items, fmt.Sprintf("%s", id))
}
return fmt.Sprintf("%s", strings.Join(items, COMMA_SEPARATED))
}
func TimestampToStr(timestamp int64) string {
tm := time.Unix(timestamp/1000, 0)
timeString := tm.Format("2006-01-02T15:04:05Z")
return timeString
}
package alicloud
import (
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
type VsService struct {
client *connectivity.AliyunClient
}
func (s *VsService) DescribeVideoSurveillanceSystemGroup(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewVsClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeGroup"
request := map[string]interface{}{
"Id": id,
"IncludeStats": "true",
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2018-12-12"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Param.Invalid.Id", "NotFound.Group"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("VideoSurveillanceSystem:Group", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"encoding/json"
"fmt"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
)
type Waf_openapiService struct {
client *connectivity.AliyunClient
}
func (s *Waf_openapiService) convertLogHeadersToString(v []interface{}) (string, error) {
arrayMaps := make([]interface{}, len(v))
for i, vv := range v {
item := vv.(map[string]interface{})
arrayMaps[i] = map[string]string{
"k": item["key"].(string),
"v": item["value"].(string),
}
}
maps, err := json.Marshal(arrayMaps)
if err != nil {
return "", WrapError(err)
}
return string(maps), nil
}
func (s *Waf_openapiService) DescribeWafDomain(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewWafClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeDomain"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"Domain": parts[1],
"InstanceId": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
if IsExpectedErrors(err, []string{"ComboError", "DomainNotExist"}) {
err = WrapErrorf(Error(GetNotFoundMessage("WafDomain", id)), NotFoundMsg, ProviderERROR)
return object, err
}
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return object, err
}
addDebug(action, response, request)
v, err := jsonpath.Get("$.Domain", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Domain", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *Waf_openapiService) DescribeWafInstance(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewWafClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeInstanceInfo"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"InstanceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
return
}
addDebug(action, response, request)
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *Waf_openapiService) DescribeWafCertificate(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewWafClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeCertificates"
parts, err := ParseResourceId(id, 3)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"Domain": parts[1],
"InstanceId": parts[0],
}
idExist := false
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Certificates", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Certificates", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("WAF", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["CertificateId"]) == parts[2] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("WAF", id)), NotFoundWithResponse, response)
}
return object, nil
}
func (s *Waf_openapiService) DescribeProtectionModuleStatus(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewWafClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeProtectionModuleStatus"
parts, err := ParseResourceId(id, 3)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"DefenseType": parts[2],
"Domain": parts[1],
"InstanceId": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *Waf_openapiService) DescribeWafProtectionModule(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewWafClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeProtectionModuleMode"
parts, err := ParseResourceId(id, 3)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"DefenseType": parts[2],
"Domain": parts[1],
"InstanceId": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-09-10"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$", response)
}
object = v.(map[string]interface{})
return object, nil
}
package alicloud
import (
"fmt"
"log"
"regexp"
"strings"
"time"
"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/alibaba-cloud-sdk-go/services/bssopenapi"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ram"
"github.com/aliyun/alibaba-cloud-sdk-go/services/yundun_bastionhost"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/pkg/errors"
)
type YundunBastionhostService struct {
client *connectivity.AliyunClient
}
type BastionhostPolicyRequired struct {
PolicyName string
PolicyType string
}
const (
BastionhostRoleDefaultDescription = "Bastionhost will access other cloud resources by playing this role by default"
BastionhostRoleName = "AliyunBastionHostDefaultRole"
BastionhostAssumeRolePolicy = `{
"Statement": [
{
"Action": "sts:AssumeRole",
"Effect": "Allow",
"Principal": {
"Service": [
"bastionhost.aliyuncs.com"
]
}
}
],
"Version": "1"
}`
BastionhostResourceType = "INSTANCE"
)
var bastionhostpolicyRequired = []BastionhostPolicyRequired{
{
PolicyName: "AliyunBastionHostRolePolicy",
PolicyType: "System",
},
}
func (s *YundunBastionhostService) DescribeBastionhostInstance(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewBastionhostClient()
if err != nil {
return nil, WrapError(err)
}
action := "DescribeInstanceAttribute"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"InstanceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Commodity.BizError.InvalidStatus"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Instance", id)), NotFoundWithResponse, response)
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.InstanceAttribute", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.InstanceAttribute", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *YundunBastionhostService) StartBastionhostInstance(instanceId string, vSwitchId string, securityGroupIds []string) error {
request := yundun_bastionhost.CreateStartInstanceRequest()
request.InstanceId = instanceId
request.VswitchId = vSwitchId
request.SecurityGroupIds = &securityGroupIds
raw, err := s.client.WithBastionhostClient(func(BastionhostClient *yundun_bastionhost.Client) (interface{}, error) {
return BastionhostClient.StartInstance(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, instanceId, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}
func (s *YundunBastionhostService) UpdateBastionhostInstanceDescription(instanceId string, description string) error {
request := yundun_bastionhost.CreateModifyInstanceAttributeRequest()
request.InstanceId = instanceId
request.Description = description
raw, err := s.client.WithBastionhostClient(func(BastionhostClient *yundun_bastionhost.Client) (interface{}, error) {
return BastionhostClient.ModifyInstanceAttribute(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, instanceId, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}
func (s *YundunBastionhostService) UpdateBastionhostSecurityGroups(instanceId string, securityGroups []string) error {
request := yundun_bastionhost.CreateConfigInstanceSecurityGroupsRequest()
request.InstanceId = instanceId
request.SecurityGroupIds = &securityGroups
raw, err := s.client.WithBastionhostClient(func(BastionhostClient *yundun_bastionhost.Client) (interface{}, error) {
return BastionhostClient.ConfigInstanceSecurityGroups(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, instanceId, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}
func (s *YundunBastionhostService) UpdateInstanceSpec(schemaSpecMap map[string]string, d *schema.ResourceData, meta interface{}) error {
request := bssopenapi.CreateModifyInstanceRequest()
request.InstanceId = d.Id()
request.ProductCode = "bastionhost"
request.SubscriptionType = "Subscription"
// only support upgrade
request.ModifyType = "Upgrade"
params := make([]bssopenapi.ModifyInstanceParameter, 0, len(schemaSpecMap))
for schemaName, spec := range schemaSpecMap {
params = append(params, bssopenapi.ModifyInstanceParameter{Code: schemaName, Value: d.Get(spec).(string)})
}
request.Parameter = ¶ms
request.RegionId = string(connectivity.Hangzhou)
var response *bssopenapi.ModifyInstanceResponse
err := resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithBssopenapiClient(func(bssopenapiClient *bssopenapi.Client) (interface{}, error) {
return bssopenapiClient.ModifyInstance(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"NotApplicable"}) {
request.RegionId = string(connectivity.APSouthEast1)
request.Domain = connectivity.BssOpenAPIEndpointInternational
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response = raw.(*bssopenapi.ModifyInstanceResponse)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
if !response.Success {
return WrapError(Error(response.Message))
}
return nil
}
func (s *YundunBastionhostService) BastionhostInstanceRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeBastionhostInstance(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil if nothing matched
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if fmt.Sprint(object["InstanceStatus"]) == failState {
return object, fmt.Sprint(object["InstanceStatus"]), WrapError(Error(FailedToReachTargetStatus, fmt.Sprint(object["InstanceStatus"])))
}
}
return object, fmt.Sprint(object["InstanceStatus"]), nil
}
}
func (s *YundunBastionhostService) createRole() error {
createRoleRequest := ram.CreateCreateRoleRequest()
createRoleRequest.RoleName = BastionhostRoleName
createRoleRequest.Description = BastionhostRoleDefaultDescription
createRoleRequest.AssumeRolePolicyDocument = BastionhostAssumeRolePolicy
raw, err := s.client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.CreateRole(createRoleRequest)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, BastionhostRoleName, createRoleRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(createRoleRequest.GetActionName(), raw, createRoleRequest.RpcRequest, createRoleRequest)
return nil
}
func (s *YundunBastionhostService) attachPolicy(policyToBeAttached []BastionhostPolicyRequired) error {
attachPolicyRequest := ram.CreateAttachPolicyToRoleRequest()
for _, policy := range policyToBeAttached {
attachPolicyRequest.RoleName = BastionhostRoleName
attachPolicyRequest.PolicyName = policy.PolicyName
attachPolicyRequest.PolicyType = policy.PolicyType
raw, err := s.client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.AttachPolicyToRole(attachPolicyRequest)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, BastionhostRoleName, attachPolicyRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
if response, err := raw.(*ram.AttachPolicyToRoleResponse); !err || !response.IsSuccess() {
return WrapError(errors.New("attach policy to role failed"))
}
addDebug(attachPolicyRequest.GetActionName(), raw, attachPolicyRequest.RpcRequest, attachPolicyRequest)
}
return nil
}
func (s *YundunBastionhostService) ProcessRolePolicy() error {
getRoleRequest := ram.CreateGetRoleRequest()
getRoleRequest.RoleName = BastionhostRoleName
raw, err := s.client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.GetRole(getRoleRequest)
})
response, _ := raw.(*ram.GetRoleResponse)
if err != nil || response == nil || response.Role.RoleName != BastionhostRoleName {
if err := s.createRole(); err != nil {
return err
}
}
addDebug(getRoleRequest.GetActionName(), raw, getRoleRequest.RpcRequest, getRoleRequest)
listPolicyForRoleRequest := ram.CreateListPoliciesForRoleRequest()
listPolicyForRoleRequest.RoleName = BastionhostRoleName
raw, err = s.client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.ListPoliciesForRole(listPolicyForRoleRequest)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, BastionhostRoleName, listPolicyForRoleRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(listPolicyForRoleRequest.GetActionName(), raw, listPolicyForRoleRequest.RpcRequest, listPolicyForRoleRequest)
var policyToAttach []BastionhostPolicyRequired
if response, _ := raw.(*ram.ListPoliciesForRoleResponse); response != nil && response.IsSuccess() {
for _, required := range bastionhostpolicyRequired {
contains := false
for _, policy := range response.Policies.Policy {
if required.PolicyName == policy.PolicyName {
contains = true
}
}
if !contains {
policyToAttach = append(policyToAttach, required)
}
}
}
if policyToAttach != nil && len(policyToAttach) > 0 {
return s.attachPolicy(policyToAttach)
}
return nil
}
func (s *YundunBastionhostService) DescribeTags(resourceId string, resourceTags map[string]interface{}, resourceType TagResourceType) (tags []yundun_bastionhost.TagResource, err error) {
request := yundun_bastionhost.CreateListTagResourcesRequest()
request.RegionId = s.client.RegionId
request.ResourceType = strings.ToUpper(string(resourceType))
request.ResourceId = &[]string{resourceId}
if resourceTags != nil && len(resourceTags) > 0 {
var reqTags []yundun_bastionhost.ListTagResourcesTag
for key, value := range resourceTags {
reqTags = append(reqTags, yundun_bastionhost.ListTagResourcesTag{
Key: key,
Value: value.(string),
})
}
request.Tag = &reqTags
}
var raw interface{}
raw, err = s.client.WithBastionhostClient(func(client *yundun_bastionhost.Client) (interface{}, error) {
return client.ListTagResources(request)
})
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, resourceId, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
response, _ := raw.(*yundun_bastionhost.ListTagResourcesResponse)
return response.TagResources.TagResource, nil
}
func (s *YundunBastionhostService) tagsToMap(tags []yundun_bastionhost.TagResource) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !s.ignoreTag(t) {
result[t.TagKey] = t.TagValue
}
}
return result
}
func (s *YundunBastionhostService) ignoreTag(t yundun_bastionhost.TagResource) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, t.TagKey)
ok, _ := regexp.MatchString(v, t.TagKey)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific t %s (val: %s), ignoring.\n", t.TagKey, t.TagValue)
return true
}
}
return false
}
func (s *YundunBastionhostService) setInstanceTags(d *schema.ResourceData, resourceType TagResourceType) error {
if d.HasChange("tags") {
oraw, nraw := d.GetChange("tags")
o := oraw.(map[string]interface{})
n := nraw.(map[string]interface{})
create, remove := s.diffTags(s.tagsFromMap(o), s.tagsFromMap(n))
if len(remove) > 0 {
var tagKey []string
for _, v := range remove {
tagKey = append(tagKey, v.Key)
}
request := yundun_bastionhost.CreateUntagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.ResourceType = strings.ToUpper(string(resourceType))
request.TagKey = &tagKey
request.RegionId = s.client.RegionId
raw, err := s.client.WithBastionhostClient(func(client *yundun_bastionhost.Client) (interface{}, error) {
return client.UntagResources(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
if len(create) > 0 {
request := yundun_bastionhost.CreateTagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.Tag = &create
request.ResourceType = strings.ToUpper(string(resourceType))
request.RegionId = s.client.RegionId
raw, err := s.client.WithBastionhostClient(func(client *yundun_bastionhost.Client) (interface{}, error) {
return client.TagResources(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
}
return nil
}
func (s *YundunBastionhostService) diffTags(oldTags, newTags []yundun_bastionhost.TagResourcesTag) ([]yundun_bastionhost.TagResourcesTag, []yundun_bastionhost.TagResourcesTag) {
// First, we're creating everything we have
create := make(map[string]interface{})
for _, t := range newTags {
create[t.Key] = t.Value
}
// Build the list of what to remove
var remove []yundun_bastionhost.TagResourcesTag
for _, t := range oldTags {
old, ok := create[t.Key]
if !ok || old != t.Value {
// Delete it!
remove = append(remove, t)
}
}
return s.tagsFromMap(create), remove
}
func (s *YundunBastionhostService) tagsFromMap(m map[string]interface{}) []yundun_bastionhost.TagResourcesTag {
result := make([]yundun_bastionhost.TagResourcesTag, 0, len(m))
for k, v := range m {
result = append(result, yundun_bastionhost.TagResourcesTag{
Key: k,
Value: v.(string),
})
}
return result
}
func (s *YundunBastionhostService) UpdateResourceGroup(resourceId, resourceGroupId string) error {
request := yundun_bastionhost.CreateMoveResourceGroupRequest()
request.RegionId = s.client.RegionId
request.ResourceId = resourceId
request.ResourceType = BastionhostResourceType
request.ResourceGroupId = resourceGroupId
raw, err := s.client.WithBastionhostClient(func(BastionhostClient *yundun_bastionhost.Client) (interface{}, error) {
return BastionhostClient.MoveResourceGroup(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, resourceId, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}
func (s *YundunBastionhostService) DescribeBastionhostUserGroup(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewBastionhostClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetUserGroup"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"InstanceId": parts[0],
"UserGroupId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Commodity.BizError.InvalidStatus", "OBJECT_NOT_FOUND"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Bastionhost:UserGroup", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.UserGroup", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.UserGroup", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *YundunBastionhostService) DescribeBastionhostUser(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewBastionhostClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetUser"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"InstanceId": parts[0],
"UserId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Commodity.BizError.InvalidStatus", "OBJECT_NOT_FOUND"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Bastionhost:User", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.User", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.User", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *YundunBastionhostService) DescribeBastionhostHostGroup(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewBastionhostClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetHostGroup"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"HostGroupId": parts[1],
"InstanceId": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Commodity.BizError.InvalidStatus", "OBJECT_NOT_FOUND"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Bastionhost:HostGroup", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.HostGroup", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.HostGroup", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *YundunBastionhostService) DescribeBastionhostUserAttachment(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewBastionhostClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListUsers"
parts, err := ParseResourceId(id, 3)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"InstanceId": parts[0],
"UserGroupId": parts[1],
"PageNumber": 1,
"PageSize": 50,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Commodity.BizError.InvalidStatus"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Bastionhost:UserAttachment", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Users", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Users", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("Bastionhost", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["UserId"]) == parts[2] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("Bastionhost", id)), NotFoundWithResponse, response)
}
return
}
func (s *YundunBastionhostService) DescribeBastionhostHost(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewBastionhostClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetHost"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"HostId": parts[1],
"InstanceId": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(false)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Commodity.BizError.InvalidStatus", "OBJECT_NOT_FOUND"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Bastionhost:Host", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Host", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Host", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *YundunBastionhostService) DescribeBastionhostHostAccount(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewBastionhostClient()
if err != nil {
return nil, WrapError(err)
}
action := "GetHostAccount"
parts, err := ParseResourceId(id, 2)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"HostAccountId": parts[1],
"InstanceId": parts[0],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Commodity.BizError.InvalidStatus", "OBJECT_NOT_FOUND"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Bastionhost:HostAccount", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.HostAccount", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.HostAccount", response)
}
object = v.(map[string]interface{})
return object, nil
}
func (s *YundunBastionhostService) DescribeBastionhostHostAttachment(id string) (object map[string]interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewBastionhostClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListHosts"
parts, err := ParseResourceId(id, 3)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"HostGroupId": parts[1],
"InstanceId": parts[0],
"PageNumber": 1,
"PageSize": 0,
}
idExist := false
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Commodity.BizError.InvalidStatus"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Bastionhost:HostAttachment", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.Hosts", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Hosts", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("Bastionhost", id)), NotFoundWithResponse, response)
}
for _, v := range v.([]interface{}) {
if fmt.Sprint(v.(map[string]interface{})["HostId"]) == parts[2] {
idExist = true
return v.(map[string]interface{}), nil
}
}
if len(v.([]interface{})) < request["PageSize"].(int) {
break
}
request["PageNumber"] = request["PageNumber"].(int) + 1
}
if !idExist {
return object, WrapErrorf(Error(GetNotFoundMessage("Bastionhost", id)), NotFoundWithResponse, response)
}
return
}
func (s *YundunBastionhostService) DescribeBastionhostHostAccountUserAttachment(id string) (object []interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewBastionhostClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListHostAccountsForUser"
parts, err := ParseResourceId(id, 3)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"HostId": parts[2],
"InstanceId": parts[0],
"UserId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(10*time.Second, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Commodity.BizError.InvalidStatus", "OBJECT_NOT_FOUND"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Bastionhost:HostAccountUserAttachment", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.HostAccounts", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.HostAccounts", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("Bastionhost", id)), NotFoundWithResponse, response)
}
return v.([]interface{}), nil
}
func (s *YundunBastionhostService) DescribeBastionhostHostAccountUserGroupAttachment(id string) (object []interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewBastionhostClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListHostAccountsForUserGroup"
parts, err := ParseResourceId(id, 3)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"HostId": parts[2],
"InstanceId": parts[0],
"UserGroupId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(10*time.Second, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Commodity.BizError.InvalidStatus", "OBJECT_NOT_FOUND"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Bastionhost:HostAccountUserGroupAttachment", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.HostAccounts", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.HostAccounts", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("Bastionhost", id)), NotFoundWithResponse, response)
}
return v.([]interface{}), nil
}
func (s *YundunBastionhostService) DescribeBastionhostHostGroupAccountUserAttachment(id string) (object []interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewBastionhostClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListHostGroupAccountNamesForUser"
parts, err := ParseResourceId(id, 3)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"HostGroupId": parts[2],
"InstanceId": parts[0],
"UserId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(10*time.Second, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Commodity.BizError.InvalidStatus", "OBJECT_NOT_FOUND"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Bastionhost:HostGroupAccountUserAttachment", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.HostAccountNames", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.HostAccountNames", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("Bastionhost", id)), NotFoundWithResponse, response)
}
return v.([]interface{}), nil
}
func (s *YundunBastionhostService) DescribeBastionhostHostGroupAccountUserGroupAttachment(id string) (object []interface{}, err error) {
var response map[string]interface{}
conn, err := s.client.NewBastionhostClient()
if err != nil {
return nil, WrapError(err)
}
action := "ListHostGroupAccountNamesForUserGroup"
parts, err := ParseResourceId(id, 3)
if err != nil {
err = WrapError(err)
return
}
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"HostGroupId": parts[2],
"InstanceId": parts[0],
"UserGroupId": parts[1],
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(10*time.Second, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
if IsExpectedErrors(err, []string{"Commodity.BizError.InvalidStatus", "OBJECT_NOT_FOUND"}) {
return object, WrapErrorf(Error(GetNotFoundMessage("Bastionhost:HostGroupAccountUserGroupAttachment", id)), NotFoundMsg, ProviderERROR, fmt.Sprint(response["RequestId"]))
}
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
v, err := jsonpath.Get("$.HostAccountNames", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.HostAccountNames", response)
}
if len(v.([]interface{})) < 1 {
return object, WrapErrorf(Error(GetNotFoundMessage("Bastionhost", id)), NotFoundWithResponse, response)
}
return v.([]interface{}), nil
}
func (s *YundunBastionhostService) EnableInstancePublicAccess(id string) (err error) {
var response map[string]interface{}
conn, err := s.client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
action := "EnableInstancePublicAccess"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"InstanceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
return nil
}
func (s *YundunBastionhostService) DisableInstancePublicAccess(id string) (err error) {
var response map[string]interface{}
conn, err := s.client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
action := "DisableInstancePublicAccess"
request := map[string]interface{}{
"RegionId": s.client.RegionId,
"InstanceId": id,
}
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}
return nil
}
package alicloud
import (
"log"
"regexp"
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/bssopenapi"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ram"
"github.com/aliyun/alibaba-cloud-sdk-go/services/yundun_dbaudit"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/pkg/errors"
)
type DbauditService struct {
client *connectivity.AliyunClient
}
type PolicyRequired struct {
PolicyName string
PolicyType string
}
const (
RoleDefaultDescription = "DbAudit perform the default role to access your other cloud resources"
RoleName = "AliyunDbAuditDefaultRole"
AssumeRolePolicy = `{
"Statement": [
{
"Action": "sts:AssumeRole",
"Effect": "Allow",
"Principal": {
"Service": [
"dbaudit.aliyuncs.com"
]
}
}
],
"Version": "1"
}`
DBauditResourceType = "INSTANCE"
)
var policyRequired = []PolicyRequired{
{
PolicyName: "AliyunDbAuditRolePolicy",
PolicyType: "System",
},
{
PolicyName: "AliyunLogFullAccess",
PolicyType: "System",
},
}
func (s *DbauditService) DescribeYundunDbauditInstance(id string) (v yundun_dbaudit.Instance, err error) {
request := yundun_dbaudit.CreateDescribeInstancesRequest()
var instanceIds []string
instanceIds = append(instanceIds, id)
request.InstanceId = &instanceIds
request.PageSize = requests.NewInteger(PageSizeSmall)
request.CurrentPage = requests.NewInteger(1)
raw, err := s.client.WithDbauditClient(func(dbauditClient *yundun_dbaudit.Client) (interface{}, error) {
return dbauditClient.DescribeInstances(request)
})
if err != nil {
return v, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response := raw.(*yundun_dbaudit.DescribeInstancesResponse)
if len(response.Instances) == 0 || response.Instances[0].InstanceId != id {
return v, WrapErrorf(Error(GetNotFoundMessage("Yundun_dbaudit Instance", id)), NotFoundMsg, ProviderERROR)
}
v = response.Instances[0]
return
}
func (s *DbauditService) DescribeDbauditInstanceAttribute(id string) (v yundun_dbaudit.InstanceAttribute, err error) {
request := yundun_dbaudit.CreateDescribeInstanceAttributeRequest()
request.InstanceId = id
raw, err := s.client.WithDbauditClient(func(dbauditClient *yundun_dbaudit.Client) (interface{}, error) {
return dbauditClient.DescribeInstanceAttribute(request)
})
if err != nil {
return v, WrapErrorf(err, DefaultErrorMsg, id, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
response, _ := raw.(*yundun_dbaudit.DescribeInstanceAttributeResponse)
if response.InstanceAttribute.InstanceId != id {
return v, WrapErrorf(Error(GetNotFoundMessage("Yundun_dbaudit Instance", id)), NotFoundMsg, ProviderERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
v = response.InstanceAttribute
return v, WrapError(err)
}
func (s *DbauditService) StartDbauditInstance(instanceId string, vSwitchId string) error {
request := yundun_dbaudit.CreateStartInstanceRequest()
request.InstanceId = instanceId
request.VswitchId = vSwitchId
raw, err := s.client.WithDbauditClient(func(dbauditClient *yundun_dbaudit.Client) (interface{}, error) {
return dbauditClient.StartInstance(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, instanceId, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}
func (s *DbauditService) UpdateDbauditInstanceDescription(instanceId string, description string) error {
request := yundun_dbaudit.CreateModifyInstanceAttributeRequest()
request.InstanceId = instanceId
request.Description = description
raw, err := s.client.WithDbauditClient(func(dbauditClient *yundun_dbaudit.Client) (interface{}, error) {
return dbauditClient.ModifyInstanceAttribute(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, instanceId, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}
func (s *DbauditService) UpdateInstanceSpec(schemaName string, specName string, d *schema.ResourceData, meta interface{}) error {
request := bssopenapi.CreateModifyInstanceRequest()
request.InstanceId = d.Id()
request.ProductCode = "dbaudit"
request.SubscriptionType = "Subscription"
// only support upgrade
request.ModifyType = "Upgrade"
request.Parameter = &[]bssopenapi.ModifyInstanceParameter{
{
Code: specName,
Value: d.Get(schemaName).(string),
},
}
request.RegionId = string(connectivity.Hangzhou)
var response *bssopenapi.ModifyInstanceResponse
err := resource.Retry(3*time.Minute, func() *resource.RetryError {
raw, err := s.client.WithBssopenapiClient(func(bssopenapiClient *bssopenapi.Client) (interface{}, error) {
return bssopenapiClient.ModifyInstance(request)
})
if err != nil {
if IsExpectedErrors(err, []string{"NotApplicable"}) {
request.RegionId = string(connectivity.APSouthEast1)
request.Domain = connectivity.BssOpenAPIEndpointInternational
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response = raw.(*bssopenapi.ModifyInstanceResponse)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
if !response.Success {
return WrapError(Error(response.Message))
}
return nil
}
func (s *DbauditService) DbauditInstanceRefreshFunc(id string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeYundunDbauditInstance(id)
if err != nil {
if NotFoundError(err) {
// Set this to nil if nothing matched
return nil, "", nil
}
return nil, "", WrapError(err)
}
for _, failState := range failStates {
if object.InstanceStatus == failState {
return object, object.InstanceStatus, WrapError(Error(FailedToReachTargetStatus, object.InstanceStatus))
}
}
return object, object.InstanceStatus, nil
}
}
func (s *DbauditService) createRole() error {
createRoleRequest := ram.CreateCreateRoleRequest()
createRoleRequest.RoleName = RoleName
createRoleRequest.Description = RoleDefaultDescription
createRoleRequest.AssumeRolePolicyDocument = AssumeRolePolicy
raw, err := s.client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.CreateRole(createRoleRequest)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, RoleName, createRoleRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(createRoleRequest.GetActionName(), raw, createRoleRequest.RpcRequest, createRoleRequest)
return nil
}
func (s *DbauditService) attachPolicy(policyToBeAttached []PolicyRequired) error {
log.Printf("DEBUG attachPolicy policyRequred %v", policyToBeAttached)
attachPolicyRequest := ram.CreateAttachPolicyToRoleRequest()
for _, policy := range policyToBeAttached {
log.Printf("DEBUG attach Policy in policyRequred %v", policy)
attachPolicyRequest.RoleName = RoleName
attachPolicyRequest.PolicyName = policy.PolicyName
attachPolicyRequest.PolicyType = policy.PolicyType
raw, err := s.client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.AttachPolicyToRole(attachPolicyRequest)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, RoleName, attachPolicyRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
if response, err := raw.(*ram.AttachPolicyToRoleResponse); !err || !response.IsSuccess() {
log.Printf("AttachPolicyToRoleError [%v]", response)
return errors.New("attach policy to role failed")
}
addDebug(attachPolicyRequest.GetActionName(), raw, attachPolicyRequest.RpcRequest, attachPolicyRequest)
}
return nil
}
func (s *DbauditService) ProcessRolePolicy() error {
getRoleRequest := ram.CreateGetRoleRequest()
getRoleRequest.RoleName = RoleName
raw, err := s.client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.GetRole(getRoleRequest)
})
log.Printf("DEBUG ProcessRolePolicy create role %v", raw.(*ram.GetRoleResponse))
addDebug(getRoleRequest.GetActionName(), raw, getRoleRequest.RpcRequest, getRoleRequest)
response, _ := raw.(*ram.GetRoleResponse)
if err != nil || response == nil || response.Role.RoleName != RoleName {
if err := s.createRole(); err != nil {
return WrapError(err)
}
}
listPolicyForRoleRequest := ram.CreateListPoliciesForRoleRequest()
listPolicyForRoleRequest.RoleName = RoleName
raw, err = s.client.WithRamClient(func(ramClient *ram.Client) (interface{}, error) {
return ramClient.ListPoliciesForRole(listPolicyForRoleRequest)
})
addDebug(listPolicyForRoleRequest.GetActionName(), raw, listPolicyForRoleRequest.RpcRequest, listPolicyForRoleRequest)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, RoleName, listPolicyForRoleRequest.GetActionName(), AlibabaCloudSdkGoERROR)
}
var policyToAttach []PolicyRequired
if response, _ := raw.(*ram.ListPoliciesForRoleResponse); response != nil && response.IsSuccess() {
for _, required := range policyRequired {
contains := false
for _, policy := range response.Policies.Policy {
if required.PolicyName == policy.PolicyName {
contains = true
}
}
if !contains {
policyToAttach = append(policyToAttach, required)
}
}
}
if policyToAttach != nil && len(policyToAttach) > 0 {
return s.attachPolicy(policyToAttach)
}
return nil
}
func (s *DbauditService) WaitForYundunDbauditInstance(instanceId string, status Status, timeoutSenconds time.Duration) error {
deadline := time.Now().Add(timeoutSenconds * time.Second)
for {
_, err := s.DescribeYundunDbauditInstance(instanceId)
if err != nil {
if NotFoundError(err) {
if status == Deleted {
return nil
}
} else {
return WrapError(err)
}
}
if time.Now().After(deadline) {
return WrapErrorf(err, WaitTimeoutMsg, instanceId, GetFunc(1), timeoutSenconds, "", "", ProviderERROR)
}
time.Sleep(DefaultIntervalShort * time.Second)
}
}
func (s *DbauditService) DescribeTags(resourceId string, resourceTags map[string]interface{}, resourceType TagResourceType) (tags []yundun_dbaudit.TagResource, err error) {
request := yundun_dbaudit.CreateListTagResourcesRequest()
request.RegionId = s.client.RegionId
request.ResourceType = strings.ToUpper(string(resourceType))
request.ResourceId = &[]string{resourceId}
if resourceTags != nil && len(resourceTags) > 0 {
var reqTags []yundun_dbaudit.ListTagResourcesTag
for key, value := range resourceTags {
reqTags = append(reqTags, yundun_dbaudit.ListTagResourcesTag{
Key: key,
Value: value.(string),
})
}
request.Tag = &reqTags
}
var raw interface{}
raw, err = s.client.WithDbauditClient(func(dbauditClient *yundun_dbaudit.Client) (interface{}, error) {
return dbauditClient.ListTagResources(request)
})
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
if err != nil {
err = WrapErrorf(err, DefaultErrorMsg, resourceId, request.GetActionName(), AlibabaCloudSdkGoERROR)
return
}
response, _ := raw.(*yundun_dbaudit.ListTagResourcesResponse)
return response.TagResources, nil
}
func (s *DbauditService) tagsToMap(tags []yundun_dbaudit.TagResource) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !s.ignoreTag(t) {
result[t.TagKey] = t.TagValue
}
}
return result
}
func (s *DbauditService) ignoreTag(t yundun_dbaudit.TagResource) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, t.TagKey)
ok, _ := regexp.MatchString(v, t.TagKey)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific t %s (val: %s), ignoring.\n", t.TagKey, t.TagValue)
return true
}
}
return false
}
func (s *DbauditService) setInstanceTags(d *schema.ResourceData, resourceType TagResourceType) error {
if d.HasChange("tags") {
oraw, nraw := d.GetChange("tags")
o := oraw.(map[string]interface{})
n := nraw.(map[string]interface{})
create, remove := s.diffTags(s.tagsFromMap(o), s.tagsFromMap(n))
if len(remove) > 0 {
var tagKey []string
for _, v := range remove {
tagKey = append(tagKey, v.Key)
}
request := yundun_dbaudit.CreateUntagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.ResourceType = strings.ToUpper(string(resourceType))
request.TagKey = &tagKey
request.RegionId = s.client.RegionId
raw, err := s.client.WithDbauditClient(func(client *yundun_dbaudit.Client) (interface{}, error) {
return client.UntagResources(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
if len(create) > 0 {
request := yundun_dbaudit.CreateTagResourcesRequest()
request.ResourceId = &[]string{d.Id()}
request.Tag = &create
request.ResourceType = strings.ToUpper(string(resourceType))
request.RegionId = s.client.RegionId
raw, err := s.client.WithDbauditClient(func(client *yundun_dbaudit.Client) (interface{}, error) {
return client.TagResources(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
}
return nil
}
func (s *DbauditService) diffTags(oldTags, newTags []yundun_dbaudit.TagResourcesTag) ([]yundun_dbaudit.TagResourcesTag, []yundun_dbaudit.TagResourcesTag) {
// First, we're creating everything we have
create := make(map[string]interface{})
for _, t := range newTags {
create[t.Key] = t.Value
}
// Build the list of what to remove
var remove []yundun_dbaudit.TagResourcesTag
for _, t := range oldTags {
old, ok := create[t.Key]
if !ok || old != t.Value {
// Delete it!
remove = append(remove, t)
}
}
return s.tagsFromMap(create), remove
}
func (s *DbauditService) tagsFromMap(m map[string]interface{}) []yundun_dbaudit.TagResourcesTag {
result := make([]yundun_dbaudit.TagResourcesTag, 0, len(m))
for k, v := range m {
result = append(result, yundun_dbaudit.TagResourcesTag{
Key: k,
Value: v.(string),
})
}
return result
}
func (s *DbauditService) UpdateResourceGroup(resourceId, resourceGroupId string) error {
request := yundun_dbaudit.CreateMoveResourceGroupRequest()
request.RegionId = s.client.RegionId
request.ResourceId = resourceId
request.ResourceType = DBauditResourceType
request.ResourceGroupId = resourceGroupId
raw, err := s.client.WithDbauditClient(func(dbauditClient *yundun_dbaudit.Client) (interface{}, error) {
return dbauditClient.MoveResourceGroup(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, resourceId, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
}
package alicloud
import (
"log"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/aliyun/alibaba-cloud-sdk-go/services/slb"
"github.com/aliyun/alibaba-cloud-sdk-go/services/gpdb"
"regexp"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cdn"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
"github.com/aliyun/alibaba-cloud-sdk-go/services/elasticsearch"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ess"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ots"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func String(v string) *string {
return &v
}
func tagsSchema() *schema.Schema {
return &schema.Schema{
Type: schema.TypeMap,
Optional: true,
}
}
func tagsSchemaComputed() *schema.Schema {
return &schema.Schema{
Type: schema.TypeMap,
Optional: true,
Computed: true,
}
}
func tagsSchemaWithIgnore() *schema.Schema {
return &schema.Schema{
Type: schema.TypeMap,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringDoesNotMatch(regexp.MustCompile(`(^acs:.*)|(^aliyun.*)|(/.*http://.*\.\w+/gm)|(/.*https://.*\.\w+/gm)`), "It cannot begin with \"aliyun\", \"acs:\"; without \"http://\", and \"https://\"."),
},
}
}
func parsingTags(d *schema.ResourceData) (map[string]interface{}, []string) {
oraw, nraw := d.GetChange("tags")
removedTags := oraw.(map[string]interface{})
addedTags := nraw.(map[string]interface{})
// Build the list of what to remove
removed := make([]string, 0)
for key, value := range removedTags {
old, ok := addedTags[key]
if !ok || old != value {
// Delete it!
removed = append(removed, key)
}
}
return addedTags, removed
}
func tagsToMap(tags interface{}) map[string]interface{} {
result := make(map[string]interface{})
if tags == nil {
return result
}
switch v := tags.(type) {
case map[string]interface{}:
for key, value := range tags.(map[string]interface{}) {
if !tagIgnored(key, value) {
result[key] = value
}
}
case []interface{}:
if len(tags.([]interface{})) < 1 {
return result
}
for _, tag := range tags.([]interface{}) {
t := tag.(map[string]interface{})
var tagKey string
var tagValue interface{}
if v, ok := t["TagKey"]; ok {
tagKey = v.(string)
tagValue = t["TagValue"]
} else if v, ok := t["Key"]; ok {
tagKey = v.(string)
tagValue = t["Value"]
}
if !tagIgnored(tagKey, tagValue) {
result[tagKey] = tagValue
}
}
default:
log.Printf("\u001B[31m[ERROR]\u001B[0m Unknown tags type %s. The tags value is: %v.", v, tags)
}
return result
}
func tagIgnored(tagKey string, tagValue interface{}) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, tagKey)
ok, _ := regexp.MatchString(v, tagKey)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific tag %s (val: %s), ignoring.\n", tagKey, tagValue)
return true
}
}
return false
}
// setTags is a helper to set the tags for a resource. It expects the
// tags field to be named "tags"
func setTags(client *connectivity.AliyunClient, resourceType TagResourceType, d *schema.ResourceData) error {
if d.HasChange("tags") {
oraw, nraw := d.GetChange("tags")
return updateTags(client, []string{d.Id()}, resourceType, oraw, nraw)
}
return nil
}
func setCdnTags(client *connectivity.AliyunClient, resourceType TagResourceType, d *schema.ResourceData) error {
if d.HasChange("tags") {
oraw, nraw := d.GetChange("tags")
return updateCdnTags(client, []string{d.Id()}, resourceType, oraw, nraw)
}
return nil
}
func setVolumeTags(client *connectivity.AliyunClient, resourceType TagResourceType, d *schema.ResourceData) error {
ecsService := EcsService{client}
if d.HasChange("volume_tags") {
request := ecs.CreateDescribeDisksRequest()
request.InstanceId = d.Id()
var response *ecs.DescribeDisksResponse
wait := incrementalWait(1*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.DescribeDisks(request)
})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
response, _ = raw.(*ecs.DescribeDisksResponse)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR)
}
if len(response.Disks.Disk) == 0 {
return WrapError(Error("no specified system disk"))
}
var ids []string
systemDiskTag := make(map[string]interface{})
for _, disk := range response.Disks.Disk {
ids = append(ids, disk.DiskId)
if disk.Type == "system" {
for _, t := range disk.Tags.Tag {
if !ecsService.ecsTagIgnored(t) {
systemDiskTag[t.TagKey] = t.TagValue
}
}
}
}
oraw, nraw := d.GetChange("volume_tags")
if d.IsNewResource() {
oraw = systemDiskTag
}
return updateTags(client, ids, resourceType, oraw, nraw)
}
return nil
}
func updateTags(client *connectivity.AliyunClient, ids []string, resourceType TagResourceType, oraw, nraw interface{}) error {
o := oraw.(map[string]interface{})
n := nraw.(map[string]interface{})
create, remove := diffTags(tagsFromMap(o), tagsFromMap(n))
// Set tags
if len(remove) > 0 {
request := ecs.CreateUntagResourcesRequest()
request.ResourceType = string(resourceType)
request.ResourceId = &ids
var tagsKey []string
for _, t := range remove {
tagsKey = append(tagsKey, t.Key)
}
request.TagKey = &tagsKey
wait := incrementalWait(1*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.UntagResources(request)
})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ids, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
if len(create) > 0 {
request := ecs.CreateTagResourcesRequest()
request.ResourceType = string(resourceType)
request.ResourceId = &ids
var tags []ecs.TagResourcesTag
for _, t := range create {
tags = append(tags, ecs.TagResourcesTag{
Key: t.Key,
Value: t.Value,
})
}
request.Tag = &tags
wait := incrementalWait(1*time.Second, 1*time.Second)
err := resource.Retry(10*time.Minute, func() *resource.RetryError {
raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
return ecsClient.TagResources(request)
})
if err != nil {
if IsThrottling(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
return nil
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ids, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
}
return nil
}
func updateCdnTags(client *connectivity.AliyunClient, ids []string, resourceType TagResourceType, oraw, nraw interface{}) error {
o := oraw.(map[string]interface{})
n := nraw.(map[string]interface{})
create, remove := diffTags(tagsFromMap(o), tagsFromMap(n))
// Set tags
if len(remove) > 0 {
request := cdn.CreateUntagResourcesRequest()
request.ResourceType = string(resourceType)
request.ResourceId = &ids
var tagsKey []string
for _, t := range remove {
tagsKey = append(tagsKey, t.Key)
}
request.TagKey = &tagsKey
raw, err := client.WithCdnClient_new(func(cdnClient *cdn.Client) (interface{}, error) {
return cdnClient.UntagResources(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ids, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
if len(create) > 0 {
request := cdn.CreateTagResourcesRequest()
request.ResourceType = string(resourceType)
request.ResourceId = &ids
var tags []cdn.TagResourcesTag
for _, t := range create {
tags = append(tags, cdn.TagResourcesTag{
Key: t.Key,
Value: t.Value,
})
}
request.Tag = &tags
raw, err := client.WithCdnClient_new(func(cdnClient *cdn.Client) (interface{}, error) {
return cdnClient.TagResources(request)
})
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, ids, request.GetActionName(), AlibabaCloudSdkGoERROR)
}
addDebug(request.GetActionName(), raw, request.RpcRequest, request)
}
return nil
}
// diffTags takes our tags locally and the ones remotely and returns
// the set of tags that must be created, and the set of tags that must
// be destroyed.
func diffTags(oldTags, newTags []Tag) ([]Tag, []Tag) {
// First, we're creating everything we have
create := make(map[string]interface{})
for _, t := range newTags {
create[t.Key] = t.Value
}
// Build the list of what to remove
var remove []Tag
for _, t := range oldTags {
old, ok := create[t.Key]
if !ok || old != t.Value {
// Delete it!
remove = append(remove, t)
}
}
return tagsFromMap(create), remove
}
func diffGpdbTags(oldTags, newTags []gpdb.TagResourcesTag) ([]gpdb.TagResourcesTag, []gpdb.TagResourcesTag) {
// First, we're creating everything we have
create := make(map[string]interface{})
for _, t := range newTags {
create[t.Key] = t.Value
}
// Build the list of what to remove
var remove []gpdb.TagResourcesTag
for _, t := range oldTags {
old, ok := create[t.Key]
if !ok || old != t.Value {
// Delete it!
remove = append(remove, t)
}
}
return gpdbTagsFromMap(create), remove
}
// tagsFromMap returns the tags for the given map of data.
func tagsFromMap(m map[string]interface{}) []Tag {
result := make([]Tag, 0, len(m))
for k, v := range m {
result = append(result, Tag{
Key: k,
Value: v.(string),
})
}
return result
}
func gpdbTagsFromMap(m map[string]interface{}) []gpdb.TagResourcesTag {
result := make([]gpdb.TagResourcesTag, 0, len(m))
for k, v := range m {
result = append(result, gpdb.TagResourcesTag{
Key: k,
Value: v.(string),
})
}
return result
}
func ecsTagsToMap(tags []ecs.Tag) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !ecsTagIgnored(t) {
result[t.TagKey] = t.TagValue
}
}
return result
}
func elasticsearchTagsToMap(tags []elasticsearch.Tag) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !elasticsearchTagIgnored(t.TagKey, t.TagValue) {
result[t.TagKey] = t.TagValue
}
}
return result
}
func vpcTagsToMap(tags []vpc.Tag) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !vpcTagIgnored(t) {
result[t.Key] = t.Value
}
}
return result
}
func cdnTagsToMap(tags []cdn.TagItem) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !cdnTagIgnored(t) {
result[t.Key] = t.Value
}
}
return result
}
func slbTagsToMap(tags []slb.TagResource) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !slbTagIgnored(t) {
result[t.TagKey] = t.TagValue
}
}
return result
}
func essTagsToMap(tags []ess.Tag) map[string]string {
result := make(map[string]string)
for _, t := range tags {
if !essTagIgnored(t) {
result[t.Key] = t.Value
}
}
return result
}
func otsTagsToMap(tags []ots.TagInfo) map[string]string {
result := make(map[string]string)
for _, t := range tags {
result[t.TagKey] = t.TagValue
}
return result
}
func tagsMapEqual(expectMap map[string]interface{}, compareMap map[string]string) bool {
if len(expectMap) != len(compareMap) {
return false
} else {
for key, eVal := range expectMap {
if eStr, ok := eVal.(string); !ok {
// type is mismatch.
return false
} else {
if cStr, ok := compareMap[key]; ok {
if eStr != cStr {
return false
}
} else {
return false
}
}
}
}
return true
}
// tagIgnored compares a tag against a list of strings and checks if it should be ignored or not
func ecsTagIgnored(t ecs.Tag) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, t.TagKey)
ok, _ := regexp.MatchString(v, t.TagKey)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific tag %s (val: %s), ignoring.\n", t.TagKey, t.TagValue)
return true
}
}
return false
}
func vpcTagIgnored(t vpc.Tag) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, t.Key)
ok, _ := regexp.MatchString(v, t.Key)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific tag %s (val: %s), ignoring.\n", t.Key, t.Value)
return true
}
}
return false
}
// tagIgnored compares a tag against a list of strings and checks if it should be ignored or not
func essTagIgnored(t ess.Tag) bool {
filter := []string{"^aliyun", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, t.Key)
ok, _ := regexp.MatchString(v, t.Key)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific tag %s (val: %s), ignoring.\n", t.Key, t.Value)
return true
}
}
return false
}
func cdnTagIgnored(t cdn.TagItem) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, t.Key)
ok, _ := regexp.MatchString(v, t.Key)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific tag %s (val: %s), ignoring.\n", t.Key, t.Value)
return true
}
}
return false
}
func slbTagIgnored(t slb.TagResource) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, t.TagKey)
ok, _ := regexp.MatchString(v, t.TagKey)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific tag %s (val: %s), ignoring.\n", t.TagKey, t.TagValue)
return true
}
}
return false
}
func elasticsearchTagIgnored(tagKey, tagValue string) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
log.Printf("[DEBUG] Matching prefix %v with %v\n", v, tagKey)
ok, _ := regexp.MatchString(v, tagKey)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific tag %s (val: %s), ignoring.\n", tagKey, tagValue)
return true
}
}
return false
}
func ignoredTags(tagKey string, tagValue interface{}) bool {
filter := []string{"^aliyun", "^acs:", "^http://", "^https://"}
for _, v := range filter {
ok, _ := regexp.MatchString(v, tagKey)
if ok {
log.Printf("[DEBUG] Found Alibaba Cloud specific tag with key: %s and value: %s, ignoring.\n", tagKey, tagValue)
return true
}
}
return false
}
package alicloud
import (
"encoding/json"
"fmt"
"net"
"regexp"
"strconv"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"gopkg.in/yaml.v2"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
// validateCIDRNetworkAddress ensures that the string value is a valid CIDR that
// represents a network address - it adds an error otherwise
func validateCIDRNetworkAddress(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
_, ipnet, err := net.ParseCIDR(value)
if err != nil {
errors = append(errors, fmt.Errorf(
"%q must contain a valid CIDR, got error parsing: %s", k, err))
return
}
if ipnet == nil || value != ipnet.String() {
errors = append(errors, fmt.Errorf(
"%q must contain a valid network CIDR, expected %q, got %q",
k, ipnet, value))
}
return
}
func validateVpnCIDRNetworkAddress(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
cidrs := strings.Split(value, ",")
for _, cidr := range cidrs {
_, ipnet, err := net.ParseCIDR(cidr)
if err != nil {
errors = append(errors, fmt.Errorf(
"%q must contain a valid CIDR, got error parsing: %s", k, err))
return
}
if ipnet == nil || cidr != ipnet.String() {
errors = append(errors, fmt.Errorf(
"%q must contain a valid network CIDR, expected %q, got %q",
k, ipnet, cidr))
return
}
}
return
}
func validateSwitchCIDRNetworkAddress(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
_, ipnet, err := net.ParseCIDR(value)
if err != nil {
errors = append(errors, fmt.Errorf(
"%q must contain a valid CIDR, got error parsing: %s", k, err))
return
}
if ipnet == nil || value != ipnet.String() {
errors = append(errors, fmt.Errorf(
"%q must contain a valid network CIDR, expected %q, got %q",
k, ipnet, value))
return
}
mark, _ := strconv.Atoi(strings.Split(ipnet.String(), "/")[1])
if mark < 16 || mark > 29 {
errors = append(errors, fmt.Errorf(
"%q must contain a network CIDR which mark between 16 and 29",
k))
}
return
}
func validateAllowedSplitStringValue(ss []string, splitStr string) schema.SchemaValidateFunc {
return func(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
existed := false
tsList := strings.Split(value, splitStr)
for _, ts := range tsList {
existed = false
for _, s := range ss {
if ts == s {
existed = true
break
}
}
}
if !existed {
errors = append(errors, fmt.Errorf(
"%q must contain a valid string value should in %#v, got %q",
k, ss, value))
}
return
}
}
func validateStringConvertInt64() schema.SchemaValidateFunc {
return func(v interface{}, k string) (ws []string, errors []error) {
if value, ok := v.(string); ok {
_, err := strconv.ParseInt(value, 10, 64)
if err != nil {
errors = append(errors, fmt.Errorf(
"%q should be convert to int64, got %q", k, value))
}
} else {
errors = append(errors, fmt.Errorf(
"%q should be convert to string, got %q", k, value))
}
return
}
}
func validateForwardPort(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
if value != "any" {
valueConv, err := strconv.Atoi(value)
if err != nil || valueConv < 1 || valueConv > 65535 {
errors = append(errors, fmt.Errorf("%q must be a valid port between 1 and 65535 or any ", k))
}
}
return
}
func validateOssBucketDateTimestamp(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
_, err := time.Parse("2006-01-02", value)
if err != nil {
errors = append(errors, fmt.Errorf(
"%q cannot be parsed as date YYYY-MM-DD Format", value))
}
return
}
func validateOnsGroupId(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
if !(strings.HasPrefix(value, "GID-") || strings.HasPrefix(value, "GID_")) {
errors = append(errors, fmt.Errorf("%q is invalid, it must start with 'GID-' or 'GID_'", k))
}
if reg := regexp.MustCompile(`^[\w\-]{7,64}$`); !reg.MatchString(value) {
errors = append(errors, fmt.Errorf("%q length is limited to 7-64 and only characters such as letters, digits, '_' and '-' are allowed", k))
}
return
}
func validateRR(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
if strings.HasPrefix(value, "-") || strings.HasSuffix(value, "-") {
errors = append(errors, fmt.Errorf("RR is invalid, it can not starts or ends with '-'"))
}
if len(value) > 253 {
errors = append(errors, fmt.Errorf("RR can not longer than 253 characters."))
}
for _, part := range strings.Split(value, ".") {
if len(part) > 63 {
errors = append(errors, fmt.Errorf("Each part of RR split with . can not longer than 63 characters."))
return
}
}
return
}
// Takes a value containing JSON string and passes it through
// the JSON parser to normalize it, returns either a parsing
// error or normalized JSON string.
func normalizeYamlString(yamlString interface{}) (string, error) {
var j interface{}
if yamlString == nil || yamlString.(string) == "" {
return "", nil
}
s := yamlString.(string)
err := yaml.Unmarshal([]byte(s), &j)
if err != nil {
return s, err
}
// The error is intentionally ignored here to allow empty policies to passthrough validation.
// This covers any interpolated values
bytes, _ := yaml.Marshal(j)
return string(bytes[:]), nil
}
// Takes a value containing JSON string and passes it through
// the JSON parser to normalize it, returns either a parsing
// error or normalized JSON string.
func normalizeJsonString(jsonString interface{}) (string, error) {
var j interface{}
if jsonString == nil || jsonString.(string) == "" {
return "", nil
}
s := jsonString.(string)
err := json.Unmarshal([]byte(s), &j)
if err != nil {
return s, err
}
// The error is intentionally ignored here to allow empty policies to passthrough validation.
// This covers any interpolated values
bytes, _ := json.Marshal(j)
return string(bytes[:]), nil
}
func validateYamlString(v interface{}, k string) (ws []string, errors []error) {
if _, err := normalizeYamlString(v); err != nil {
errors = append(errors, fmt.Errorf("%q contains an invalid YAML: %s", k, err))
}
return
}
func validateDBConnectionPort(v interface{}, k string) (ws []string, errors []error) {
if value := v.(string); value != "" {
port, err := strconv.Atoi(value)
if err != nil {
errors = append(errors, err)
}
if port < 1000 || port > 5999 {
errors = append(errors, fmt.Errorf("%q cannot be less than 3001 and larger than 3999.", k))
}
}
return
}
func validateSslVpnPortValue(is []int) schema.SchemaValidateFunc {
return func(v interface{}, k string) (ws []string, errors []error) {
ws, errors = validation.IntBetween(1, 65535)(v, k)
if errors != nil {
return
}
value := v.(int)
for _, i := range is {
if i == value {
errors = append(errors, fmt.Errorf(
"%q must contain a valid int value should not be in array %#v, got %q",
k, is, value))
return
}
}
return
}
}
// below copy/pasta from https://github.com/hashicorp/terraform-plugin-sdk/blob/master/helper/validation/validation.go
// alicloud vendor contains very old version of Terraform which lacks this functions
// IntBetween returns a SchemaValidateFunc which tests if the provided value
// is of type int and is between min and max (inclusive)
func intBetween(min, max int) schema.SchemaValidateFunc {
return func(i interface{}, k string) (s []string, es []error) {
v, ok := i.(int)
if !ok {
es = append(es, fmt.Errorf("expected type of %s to be int", k))
return
}
if v < min || v > max {
es = append(es, fmt.Errorf("expected %s to be in the range (%d - %d), got %d", k, min, max, v))
return
}
return
}
}
// Validate length(2~128) and prefix of the name.
func validateNormalName(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
if len(value) < 2 || len(value) > 128 {
errors = append(errors, fmt.Errorf("%s cannot be longer than 128 characters", k))
}
if strings.HasPrefix(value, "http://") || strings.HasPrefix(value, "https://") {
errors = append(errors, fmt.Errorf("%s cannot starts with http:// or https://", k))
}
return
}